MachineSSAUpdater.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. //===- MachineSSAUpdater.cpp - Unstructured SSA Update Tool ---------------===//
  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. //
  9. // This file implements the MachineSSAUpdater class. It's based on SSAUpdater
  10. // class in lib/Transforms/Utils.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineSSAUpdater.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/CodeGen/MachineBasicBlock.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/CodeGen/MachineInstr.h"
  19. #include "llvm/CodeGen/MachineInstrBuilder.h"
  20. #include "llvm/CodeGen/MachineOperand.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/TargetInstrInfo.h"
  23. #include "llvm/CodeGen/TargetOpcodes.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/IR/DebugLoc.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
  30. #include <utility>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "machine-ssaupdater"
  33. using AvailableValsTy = DenseMap<MachineBasicBlock *, unsigned>;
  34. static AvailableValsTy &getAvailableVals(void *AV) {
  35. return *static_cast<AvailableValsTy*>(AV);
  36. }
  37. MachineSSAUpdater::MachineSSAUpdater(MachineFunction &MF,
  38. SmallVectorImpl<MachineInstr*> *NewPHI)
  39. : InsertedPHIs(NewPHI), TII(MF.getSubtarget().getInstrInfo()),
  40. MRI(&MF.getRegInfo()) {}
  41. MachineSSAUpdater::~MachineSSAUpdater() {
  42. delete static_cast<AvailableValsTy*>(AV);
  43. }
  44. /// Initialize - Reset this object to get ready for a new set of SSA
  45. /// updates. ProtoValue is the value used to name PHI nodes.
  46. void MachineSSAUpdater::Initialize(unsigned V) {
  47. if (!AV)
  48. AV = new AvailableValsTy();
  49. else
  50. getAvailableVals(AV).clear();
  51. VR = V;
  52. VRC = MRI->getRegClass(VR);
  53. }
  54. /// HasValueForBlock - Return true if the MachineSSAUpdater already has a value for
  55. /// the specified block.
  56. bool MachineSSAUpdater::HasValueForBlock(MachineBasicBlock *BB) const {
  57. return getAvailableVals(AV).count(BB);
  58. }
  59. /// AddAvailableValue - Indicate that a rewritten value is available in the
  60. /// specified block with the specified value.
  61. void MachineSSAUpdater::AddAvailableValue(MachineBasicBlock *BB, unsigned V) {
  62. getAvailableVals(AV)[BB] = V;
  63. }
  64. /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
  65. /// live at the end of the specified block.
  66. unsigned MachineSSAUpdater::GetValueAtEndOfBlock(MachineBasicBlock *BB) {
  67. return GetValueAtEndOfBlockInternal(BB);
  68. }
  69. static
  70. unsigned LookForIdenticalPHI(MachineBasicBlock *BB,
  71. SmallVectorImpl<std::pair<MachineBasicBlock *, unsigned>> &PredValues) {
  72. if (BB->empty())
  73. return 0;
  74. MachineBasicBlock::iterator I = BB->begin();
  75. if (!I->isPHI())
  76. return 0;
  77. AvailableValsTy AVals;
  78. for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
  79. AVals[PredValues[i].first] = PredValues[i].second;
  80. while (I != BB->end() && I->isPHI()) {
  81. bool Same = true;
  82. for (unsigned i = 1, e = I->getNumOperands(); i != e; i += 2) {
  83. Register SrcReg = I->getOperand(i).getReg();
  84. MachineBasicBlock *SrcBB = I->getOperand(i+1).getMBB();
  85. if (AVals[SrcBB] != SrcReg) {
  86. Same = false;
  87. break;
  88. }
  89. }
  90. if (Same)
  91. return I->getOperand(0).getReg();
  92. ++I;
  93. }
  94. return 0;
  95. }
  96. /// InsertNewDef - Insert an empty PHI or IMPLICIT_DEF instruction which define
  97. /// a value of the given register class at the start of the specified basic
  98. /// block. It returns the virtual register defined by the instruction.
  99. static
  100. MachineInstrBuilder InsertNewDef(unsigned Opcode,
  101. MachineBasicBlock *BB, MachineBasicBlock::iterator I,
  102. const TargetRegisterClass *RC,
  103. MachineRegisterInfo *MRI,
  104. const TargetInstrInfo *TII) {
  105. Register NewVR = MRI->createVirtualRegister(RC);
  106. return BuildMI(*BB, I, DebugLoc(), TII->get(Opcode), NewVR);
  107. }
  108. /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
  109. /// is live in the middle of the specified block.
  110. ///
  111. /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
  112. /// important case: if there is a definition of the rewritten value after the
  113. /// 'use' in BB. Consider code like this:
  114. ///
  115. /// X1 = ...
  116. /// SomeBB:
  117. /// use(X)
  118. /// X2 = ...
  119. /// br Cond, SomeBB, OutBB
  120. ///
  121. /// In this case, there are two values (X1 and X2) added to the AvailableVals
  122. /// set by the client of the rewriter, and those values are both live out of
  123. /// their respective blocks. However, the use of X happens in the *middle* of
  124. /// a block. Because of this, we need to insert a new PHI node in SomeBB to
  125. /// merge the appropriate values, and this value isn't live out of the block.
  126. unsigned MachineSSAUpdater::GetValueInMiddleOfBlock(MachineBasicBlock *BB) {
  127. // If there is no definition of the renamed variable in this block, just use
  128. // GetValueAtEndOfBlock to do our work.
  129. if (!HasValueForBlock(BB))
  130. return GetValueAtEndOfBlockInternal(BB);
  131. // If there are no predecessors, just return undef.
  132. if (BB->pred_empty()) {
  133. // Insert an implicit_def to represent an undef value.
  134. MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
  135. BB, BB->getFirstTerminator(),
  136. VRC, MRI, TII);
  137. return NewDef->getOperand(0).getReg();
  138. }
  139. // Otherwise, we have the hard case. Get the live-in values for each
  140. // predecessor.
  141. SmallVector<std::pair<MachineBasicBlock*, unsigned>, 8> PredValues;
  142. unsigned SingularValue = 0;
  143. bool isFirstPred = true;
  144. for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
  145. E = BB->pred_end(); PI != E; ++PI) {
  146. MachineBasicBlock *PredBB = *PI;
  147. unsigned PredVal = GetValueAtEndOfBlockInternal(PredBB);
  148. PredValues.push_back(std::make_pair(PredBB, PredVal));
  149. // Compute SingularValue.
  150. if (isFirstPred) {
  151. SingularValue = PredVal;
  152. isFirstPred = false;
  153. } else if (PredVal != SingularValue)
  154. SingularValue = 0;
  155. }
  156. // Otherwise, if all the merged values are the same, just use it.
  157. if (SingularValue != 0)
  158. return SingularValue;
  159. // If an identical PHI is already in BB, just reuse it.
  160. unsigned DupPHI = LookForIdenticalPHI(BB, PredValues);
  161. if (DupPHI)
  162. return DupPHI;
  163. // Otherwise, we do need a PHI: insert one now.
  164. MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
  165. MachineInstrBuilder InsertedPHI = InsertNewDef(TargetOpcode::PHI, BB,
  166. Loc, VRC, MRI, TII);
  167. // Fill in all the predecessors of the PHI.
  168. for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
  169. InsertedPHI.addReg(PredValues[i].second).addMBB(PredValues[i].first);
  170. // See if the PHI node can be merged to a single value. This can happen in
  171. // loop cases when we get a PHI of itself and one other value.
  172. if (unsigned ConstVal = InsertedPHI->isConstantValuePHI()) {
  173. InsertedPHI->eraseFromParent();
  174. return ConstVal;
  175. }
  176. // If the client wants to know about all new instructions, tell it.
  177. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
  178. LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
  179. return InsertedPHI->getOperand(0).getReg();
  180. }
  181. static
  182. MachineBasicBlock *findCorrespondingPred(const MachineInstr *MI,
  183. MachineOperand *U) {
  184. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  185. if (&MI->getOperand(i) == U)
  186. return MI->getOperand(i+1).getMBB();
  187. }
  188. llvm_unreachable("MachineOperand::getParent() failure?");
  189. }
  190. /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
  191. /// which use their value in the corresponding predecessor.
  192. void MachineSSAUpdater::RewriteUse(MachineOperand &U) {
  193. MachineInstr *UseMI = U.getParent();
  194. unsigned NewVR = 0;
  195. if (UseMI->isPHI()) {
  196. MachineBasicBlock *SourceBB = findCorrespondingPred(UseMI, &U);
  197. NewVR = GetValueAtEndOfBlockInternal(SourceBB);
  198. } else {
  199. NewVR = GetValueInMiddleOfBlock(UseMI->getParent());
  200. }
  201. U.setReg(NewVR);
  202. }
  203. /// SSAUpdaterTraits<MachineSSAUpdater> - Traits for the SSAUpdaterImpl
  204. /// template, specialized for MachineSSAUpdater.
  205. namespace llvm {
  206. template<>
  207. class SSAUpdaterTraits<MachineSSAUpdater> {
  208. public:
  209. using BlkT = MachineBasicBlock;
  210. using ValT = unsigned;
  211. using PhiT = MachineInstr;
  212. using BlkSucc_iterator = MachineBasicBlock::succ_iterator;
  213. static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
  214. static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
  215. /// Iterator for PHI operands.
  216. class PHI_iterator {
  217. private:
  218. MachineInstr *PHI;
  219. unsigned idx;
  220. public:
  221. explicit PHI_iterator(MachineInstr *P) // begin iterator
  222. : PHI(P), idx(1) {}
  223. PHI_iterator(MachineInstr *P, bool) // end iterator
  224. : PHI(P), idx(PHI->getNumOperands()) {}
  225. PHI_iterator &operator++() { idx += 2; return *this; }
  226. bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
  227. bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
  228. unsigned getIncomingValue() { return PHI->getOperand(idx).getReg(); }
  229. MachineBasicBlock *getIncomingBlock() {
  230. return PHI->getOperand(idx+1).getMBB();
  231. }
  232. };
  233. static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
  234. static inline PHI_iterator PHI_end(PhiT *PHI) {
  235. return PHI_iterator(PHI, true);
  236. }
  237. /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
  238. /// vector.
  239. static void FindPredecessorBlocks(MachineBasicBlock *BB,
  240. SmallVectorImpl<MachineBasicBlock*> *Preds){
  241. for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
  242. E = BB->pred_end(); PI != E; ++PI)
  243. Preds->push_back(*PI);
  244. }
  245. /// GetUndefVal - Create an IMPLICIT_DEF instruction with a new register.
  246. /// Add it into the specified block and return the register.
  247. static unsigned GetUndefVal(MachineBasicBlock *BB,
  248. MachineSSAUpdater *Updater) {
  249. // Insert an implicit_def to represent an undef value.
  250. MachineInstr *NewDef = InsertNewDef(TargetOpcode::IMPLICIT_DEF,
  251. BB, BB->getFirstTerminator(),
  252. Updater->VRC, Updater->MRI,
  253. Updater->TII);
  254. return NewDef->getOperand(0).getReg();
  255. }
  256. /// CreateEmptyPHI - Create a PHI instruction that defines a new register.
  257. /// Add it into the specified block and return the register.
  258. static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
  259. MachineSSAUpdater *Updater) {
  260. MachineBasicBlock::iterator Loc = BB->empty() ? BB->end() : BB->begin();
  261. MachineInstr *PHI = InsertNewDef(TargetOpcode::PHI, BB, Loc,
  262. Updater->VRC, Updater->MRI,
  263. Updater->TII);
  264. return PHI->getOperand(0).getReg();
  265. }
  266. /// AddPHIOperand - Add the specified value as an operand of the PHI for
  267. /// the specified predecessor block.
  268. static void AddPHIOperand(MachineInstr *PHI, unsigned Val,
  269. MachineBasicBlock *Pred) {
  270. MachineInstrBuilder(*Pred->getParent(), PHI).addReg(Val).addMBB(Pred);
  271. }
  272. /// InstrIsPHI - Check if an instruction is a PHI.
  273. static MachineInstr *InstrIsPHI(MachineInstr *I) {
  274. if (I && I->isPHI())
  275. return I;
  276. return nullptr;
  277. }
  278. /// ValueIsPHI - Check if the instruction that defines the specified register
  279. /// is a PHI instruction.
  280. static MachineInstr *ValueIsPHI(unsigned Val, MachineSSAUpdater *Updater) {
  281. return InstrIsPHI(Updater->MRI->getVRegDef(Val));
  282. }
  283. /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
  284. /// operands, i.e., it was just added.
  285. static MachineInstr *ValueIsNewPHI(unsigned Val, MachineSSAUpdater *Updater) {
  286. MachineInstr *PHI = ValueIsPHI(Val, Updater);
  287. if (PHI && PHI->getNumOperands() <= 1)
  288. return PHI;
  289. return nullptr;
  290. }
  291. /// GetPHIValue - For the specified PHI instruction, return the register
  292. /// that it defines.
  293. static unsigned GetPHIValue(MachineInstr *PHI) {
  294. return PHI->getOperand(0).getReg();
  295. }
  296. };
  297. } // end namespace llvm
  298. /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
  299. /// for the specified BB and if so, return it. If not, construct SSA form by
  300. /// first calculating the required placement of PHIs and then inserting new
  301. /// PHIs where needed.
  302. unsigned MachineSSAUpdater::GetValueAtEndOfBlockInternal(MachineBasicBlock *BB){
  303. AvailableValsTy &AvailableVals = getAvailableVals(AV);
  304. if (unsigned V = AvailableVals[BB])
  305. return V;
  306. SSAUpdaterImpl<MachineSSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
  307. return Impl.GetValue(BB);
  308. }