PHIEliminationUtils.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===-- PHIEliminationUtils.cpp - Helper functions for PHI elimination ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "PHIEliminationUtils.h"
  9. #include "llvm/ADT/SmallPtrSet.h"
  10. #include "llvm/CodeGen/MachineFunction.h"
  11. #include "llvm/CodeGen/MachineRegisterInfo.h"
  12. using namespace llvm;
  13. // findCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
  14. // when following the CFG edge to SuccMBB. This needs to be after any def of
  15. // SrcReg, but before any subsequent point where control flow might jump out of
  16. // the basic block.
  17. MachineBasicBlock::iterator
  18. llvm::findPHICopyInsertPoint(MachineBasicBlock* MBB, MachineBasicBlock* SuccMBB,
  19. unsigned SrcReg) {
  20. // Handle the trivial case trivially.
  21. if (MBB->empty())
  22. return MBB->begin();
  23. // Usually, we just want to insert the copy before the first terminator
  24. // instruction. However, for the edge going to a landing pad, we must insert
  25. // the copy before the call/invoke instruction. Similarly for an INLINEASM_BR
  26. // going to an indirect target. This is similar to SplitKit.cpp's
  27. // computeLastInsertPoint, and similarly assumes that there cannot be multiple
  28. // instructions that are Calls with EHPad successors or INLINEASM_BR in a
  29. // block.
  30. bool EHPadSuccessor = SuccMBB->isEHPad();
  31. if (!EHPadSuccessor && !SuccMBB->isInlineAsmBrIndirectTarget())
  32. return MBB->getFirstTerminator();
  33. // Discover any defs in this basic block.
  34. SmallPtrSet<MachineInstr *, 8> DefsInMBB;
  35. MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
  36. for (MachineInstr &RI : MRI.def_instructions(SrcReg))
  37. if (RI.getParent() == MBB)
  38. DefsInMBB.insert(&RI);
  39. MachineBasicBlock::iterator InsertPoint = MBB->begin();
  40. // Insert the copy at the _latest_ point of:
  41. // 1. Immediately AFTER the last def
  42. // 2. Immediately BEFORE a call/inlineasm_br.
  43. for (auto I = MBB->rbegin(), E = MBB->rend(); I != E; ++I) {
  44. if (DefsInMBB.contains(&*I)) {
  45. InsertPoint = std::next(I.getReverse());
  46. break;
  47. }
  48. if ((EHPadSuccessor && I->isCall()) ||
  49. I->getOpcode() == TargetOpcode::INLINEASM_BR) {
  50. InsertPoint = I.getReverse();
  51. break;
  52. }
  53. }
  54. // Make sure the copy goes after any phi nodes but before
  55. // any debug nodes.
  56. return MBB->SkipPHIsAndLabels(InsertPoint);
  57. }