PHIEliminationUtils.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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/MachineBasicBlock.h"
  11. #include "llvm/CodeGen/MachineFunction.h"
  12. #include "llvm/CodeGen/MachineRegisterInfo.h"
  13. using namespace llvm;
  14. // findCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
  15. // when following the CFG edge to SuccMBB. This needs to be after any def of
  16. // SrcReg, but before any subsequent point where control flow might jump out of
  17. // the basic block.
  18. MachineBasicBlock::iterator
  19. llvm::findPHICopyInsertPoint(MachineBasicBlock* MBB, MachineBasicBlock* SuccMBB,
  20. unsigned SrcReg) {
  21. // Handle the trivial case trivially.
  22. if (MBB->empty())
  23. return MBB->begin();
  24. // Usually, we just want to insert the copy before the first terminator
  25. // instruction. However, for the edge going to a landing pad, we must insert
  26. // the copy before the call/invoke instruction.
  27. if (!SuccMBB->isEHPad())
  28. return MBB->getFirstTerminator();
  29. // Discover any defs/uses in this basic block.
  30. SmallPtrSet<MachineInstr*, 8> DefUsesInMBB;
  31. MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
  32. for (MachineInstr &RI : MRI.reg_instructions(SrcReg)) {
  33. if (RI.getParent() == MBB)
  34. DefUsesInMBB.insert(&RI);
  35. }
  36. MachineBasicBlock::iterator InsertPoint;
  37. if (DefUsesInMBB.empty()) {
  38. // No defs. Insert the copy at the start of the basic block.
  39. InsertPoint = MBB->begin();
  40. } else if (DefUsesInMBB.size() == 1) {
  41. // Insert the copy immediately after the def/use.
  42. InsertPoint = *DefUsesInMBB.begin();
  43. ++InsertPoint;
  44. } else {
  45. // Insert the copy immediately after the last def/use.
  46. InsertPoint = MBB->end();
  47. while (!DefUsesInMBB.count(&*--InsertPoint)) {}
  48. ++InsertPoint;
  49. }
  50. // Make sure the copy goes after any phi nodes but before
  51. // any debug nodes.
  52. return MBB->SkipPHIsAndLabels(InsertPoint);
  53. }