lowering_function_context.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/lowering/lowering_function_context.h"
  5. #include "common/vlog.h"
  6. #include "toolchain/semantics/semantics_ir.h"
  7. #include "toolchain/semantics/semantics_node_kind.h"
  8. namespace Carbon {
  9. LoweringFunctionContext::LoweringFunctionContext(
  10. LoweringContext& lowering_context, llvm::Function* function)
  11. : lowering_context_(&lowering_context),
  12. function_(function),
  13. builder_(lowering_context.llvm_context()) {}
  14. auto LoweringFunctionContext::GetBlock(SemanticsNodeBlockId block_id)
  15. -> llvm::BasicBlock* {
  16. llvm::BasicBlock*& entry = blocks_[block_id];
  17. if (!entry) {
  18. entry = llvm::BasicBlock::Create(llvm_context(), "", function_);
  19. block_worklist().Push(block_id);
  20. }
  21. return entry;
  22. }
  23. auto LoweringFunctionContext::TryToReuseBlock(SemanticsNodeBlockId block_id,
  24. llvm::BasicBlock* block) -> bool {
  25. if (!blocks_.insert({block_id, block}).second) {
  26. return false;
  27. }
  28. block_worklist().Push(block_id);
  29. if (block == synthetic_block_) {
  30. synthetic_block_ = nullptr;
  31. }
  32. return true;
  33. }
  34. auto LoweringFunctionContext::GetBlockArg(SemanticsNodeBlockId block_id,
  35. SemanticsTypeId type_id)
  36. -> llvm::PHINode* {
  37. llvm::BasicBlock* block = GetBlock(block_id);
  38. // Find the existing phi, if any.
  39. auto phis = block->phis();
  40. if (!phis.empty()) {
  41. CARBON_CHECK(std::next(phis.begin()) == phis.end())
  42. << "Expected at most one phi, found "
  43. << std::distance(phis.begin(), phis.end());
  44. return &*phis.begin();
  45. }
  46. // The number of predecessor slots to reserve.
  47. static constexpr unsigned NumReservedPredecessors = 2;
  48. auto* phi = llvm::PHINode::Create(GetType(type_id), NumReservedPredecessors);
  49. phi->insertInto(block, block->begin());
  50. return phi;
  51. }
  52. auto LoweringFunctionContext::CreateSyntheticBlock() -> llvm::BasicBlock* {
  53. synthetic_block_ = llvm::BasicBlock::Create(llvm_context(), "", function_);
  54. return synthetic_block_;
  55. }
  56. auto LoweringFunctionContext::GetLocalLoaded(SemanticsNodeId node_id)
  57. -> llvm::Value* {
  58. auto* value = GetLocal(node_id);
  59. if (llvm::isa<llvm::AllocaInst, llvm::GetElementPtrInst>(value)) {
  60. auto* load_type = GetType(semantics_ir().GetNode(node_id).type_id());
  61. return builder().CreateLoad(load_type, value);
  62. } else {
  63. // No load is needed.
  64. return value;
  65. }
  66. }
  67. } // namespace Carbon