MachineSSAUpdater.cpp 13 KB

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