SSAUpdater.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the SSAUpdater class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/SSAUpdater.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/TinyPtrVector.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. #include "llvm/IR/CFG.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  25. #include "llvm/Transforms/Utils/Local.h"
  26. #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
  27. using namespace llvm;
  28. #define DEBUG_TYPE "ssaupdater"
  29. typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
  30. static AvailableValsTy &getAvailableVals(void *AV) {
  31. return *static_cast<AvailableValsTy*>(AV);
  32. }
  33. SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
  34. : AV(nullptr), ProtoType(nullptr), ProtoName(), InsertedPHIs(NewPHI) {}
  35. SSAUpdater::~SSAUpdater() {
  36. delete static_cast<AvailableValsTy*>(AV);
  37. }
  38. void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
  39. if (!AV)
  40. AV = new AvailableValsTy();
  41. else
  42. getAvailableVals(AV).clear();
  43. ProtoType = Ty;
  44. ProtoName = Name;
  45. }
  46. bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
  47. return getAvailableVals(AV).count(BB);
  48. }
  49. void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
  50. assert(ProtoType && "Need to initialize SSAUpdater");
  51. assert(ProtoType == V->getType() &&
  52. "All rewritten values must have the same type");
  53. getAvailableVals(AV)[BB] = V;
  54. }
  55. static bool IsEquivalentPHI(PHINode *PHI,
  56. SmallDenseMap<BasicBlock*, Value*, 8> &ValueMapping) {
  57. unsigned PHINumValues = PHI->getNumIncomingValues();
  58. if (PHINumValues != ValueMapping.size())
  59. return false;
  60. // Scan the phi to see if it matches.
  61. for (unsigned i = 0, e = PHINumValues; i != e; ++i)
  62. if (ValueMapping[PHI->getIncomingBlock(i)] !=
  63. PHI->getIncomingValue(i)) {
  64. return false;
  65. }
  66. return true;
  67. }
  68. Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
  69. Value *Res = GetValueAtEndOfBlockInternal(BB);
  70. return Res;
  71. }
  72. Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
  73. // If there is no definition of the renamed variable in this block, just use
  74. // GetValueAtEndOfBlock to do our work.
  75. if (!HasValueForBlock(BB))
  76. return GetValueAtEndOfBlock(BB);
  77. // Otherwise, we have the hard case. Get the live-in values for each
  78. // predecessor.
  79. SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
  80. Value *SingularValue = nullptr;
  81. // We can get our predecessor info by walking the pred_iterator list, but it
  82. // is relatively slow. If we already have PHI nodes in this block, walk one
  83. // of them to get the predecessor list instead.
  84. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
  85. for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
  86. BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
  87. Value *PredVal = GetValueAtEndOfBlock(PredBB);
  88. PredValues.push_back(std::make_pair(PredBB, PredVal));
  89. // Compute SingularValue.
  90. if (i == 0)
  91. SingularValue = PredVal;
  92. else if (PredVal != SingularValue)
  93. SingularValue = nullptr;
  94. }
  95. } else {
  96. bool isFirstPred = true;
  97. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  98. BasicBlock *PredBB = *PI;
  99. Value *PredVal = GetValueAtEndOfBlock(PredBB);
  100. PredValues.push_back(std::make_pair(PredBB, PredVal));
  101. // Compute SingularValue.
  102. if (isFirstPred) {
  103. SingularValue = PredVal;
  104. isFirstPred = false;
  105. } else if (PredVal != SingularValue)
  106. SingularValue = nullptr;
  107. }
  108. }
  109. // If there are no predecessors, just return undef.
  110. if (PredValues.empty())
  111. return UndefValue::get(ProtoType);
  112. // Otherwise, if all the merged values are the same, just use it.
  113. if (SingularValue)
  114. return SingularValue;
  115. // Otherwise, we do need a PHI: check to see if we already have one available
  116. // in this block that produces the right value.
  117. if (isa<PHINode>(BB->begin())) {
  118. SmallDenseMap<BasicBlock*, Value*, 8> ValueMapping(PredValues.begin(),
  119. PredValues.end());
  120. PHINode *SomePHI;
  121. for (BasicBlock::iterator It = BB->begin();
  122. (SomePHI = dyn_cast<PHINode>(It)); ++It) {
  123. if (IsEquivalentPHI(SomePHI, ValueMapping))
  124. return SomePHI;
  125. }
  126. }
  127. // Ok, we have no way out, insert a new one now.
  128. PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
  129. ProtoName, &BB->front());
  130. // Fill in all the predecessors of the PHI.
  131. for (const auto &PredValue : PredValues)
  132. InsertedPHI->addIncoming(PredValue.second, PredValue.first);
  133. // See if the PHI node can be merged to a single value. This can happen in
  134. // loop cases when we get a PHI of itself and one other value.
  135. if (Value *V =
  136. SimplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
  137. InsertedPHI->eraseFromParent();
  138. return V;
  139. }
  140. // Set the DebugLoc of the inserted PHI, if available.
  141. DebugLoc DL;
  142. if (const Instruction *I = BB->getFirstNonPHI())
  143. DL = I->getDebugLoc();
  144. InsertedPHI->setDebugLoc(DL);
  145. // If the client wants to know about all new instructions, tell it.
  146. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
  147. DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
  148. return InsertedPHI;
  149. }
  150. void SSAUpdater::RewriteUse(Use &U) {
  151. Instruction *User = cast<Instruction>(U.getUser());
  152. Value *V;
  153. if (PHINode *UserPN = dyn_cast<PHINode>(User))
  154. V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
  155. else
  156. V = GetValueInMiddleOfBlock(User->getParent());
  157. // Notify that users of the existing value that it is being replaced.
  158. Value *OldVal = U.get();
  159. if (OldVal != V && OldVal->hasValueHandle())
  160. ValueHandleBase::ValueIsRAUWd(OldVal, V);
  161. U.set(V);
  162. }
  163. void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
  164. Instruction *User = cast<Instruction>(U.getUser());
  165. Value *V;
  166. if (PHINode *UserPN = dyn_cast<PHINode>(User))
  167. V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
  168. else
  169. V = GetValueAtEndOfBlock(User->getParent());
  170. U.set(V);
  171. }
  172. namespace llvm {
  173. template<>
  174. class SSAUpdaterTraits<SSAUpdater> {
  175. public:
  176. typedef BasicBlock BlkT;
  177. typedef Value *ValT;
  178. typedef PHINode PhiT;
  179. typedef succ_iterator BlkSucc_iterator;
  180. static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
  181. static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
  182. class PHI_iterator {
  183. private:
  184. PHINode *PHI;
  185. unsigned idx;
  186. public:
  187. explicit PHI_iterator(PHINode *P) // begin iterator
  188. : PHI(P), idx(0) {}
  189. PHI_iterator(PHINode *P, bool) // end iterator
  190. : PHI(P), idx(PHI->getNumIncomingValues()) {}
  191. PHI_iterator &operator++() { ++idx; return *this; }
  192. bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
  193. bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
  194. Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
  195. BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
  196. };
  197. static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
  198. static PHI_iterator PHI_end(PhiT *PHI) {
  199. return PHI_iterator(PHI, true);
  200. }
  201. /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
  202. /// vector, set Info->NumPreds, and allocate space in Info->Preds.
  203. static void FindPredecessorBlocks(BasicBlock *BB,
  204. SmallVectorImpl<BasicBlock*> *Preds) {
  205. // We can get our predecessor info by walking the pred_iterator list,
  206. // but it is relatively slow. If we already have PHI nodes in this
  207. // block, walk one of them to get the predecessor list instead.
  208. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
  209. Preds->append(SomePhi->block_begin(), SomePhi->block_end());
  210. } else {
  211. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  212. Preds->push_back(*PI);
  213. }
  214. }
  215. /// GetUndefVal - Get an undefined value of the same type as the value
  216. /// being handled.
  217. static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
  218. return UndefValue::get(Updater->ProtoType);
  219. }
  220. /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
  221. /// Reserve space for the operands but do not fill them in yet.
  222. static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
  223. SSAUpdater *Updater) {
  224. PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
  225. Updater->ProtoName, &BB->front());
  226. return PHI;
  227. }
  228. /// AddPHIOperand - Add the specified value as an operand of the PHI for
  229. /// the specified predecessor block.
  230. static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
  231. PHI->addIncoming(Val, Pred);
  232. }
  233. /// InstrIsPHI - Check if an instruction is a PHI.
  234. ///
  235. static PHINode *InstrIsPHI(Instruction *I) {
  236. return dyn_cast<PHINode>(I);
  237. }
  238. /// ValueIsPHI - Check if a value is a PHI.
  239. ///
  240. static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
  241. return dyn_cast<PHINode>(Val);
  242. }
  243. /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
  244. /// operands, i.e., it was just added.
  245. static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
  246. PHINode *PHI = ValueIsPHI(Val, Updater);
  247. if (PHI && PHI->getNumIncomingValues() == 0)
  248. return PHI;
  249. return nullptr;
  250. }
  251. /// GetPHIValue - For the specified PHI instruction, return the value
  252. /// that it defines.
  253. static Value *GetPHIValue(PHINode *PHI) {
  254. return PHI;
  255. }
  256. };
  257. } // End llvm namespace
  258. /// Check to see if AvailableVals has an entry for the specified BB and if so,
  259. /// return it. If not, construct SSA form by first calculating the required
  260. /// placement of PHIs and then inserting new PHIs where needed.
  261. Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
  262. AvailableValsTy &AvailableVals = getAvailableVals(AV);
  263. if (Value *V = AvailableVals[BB])
  264. return V;
  265. SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
  266. return Impl.GetValue(BB);
  267. }
  268. //===----------------------------------------------------------------------===//
  269. // LoadAndStorePromoter Implementation
  270. //===----------------------------------------------------------------------===//
  271. LoadAndStorePromoter::
  272. LoadAndStorePromoter(ArrayRef<const Instruction*> Insts,
  273. SSAUpdater &S, StringRef BaseName) : SSA(S) {
  274. if (Insts.empty()) return;
  275. const Value *SomeVal;
  276. if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
  277. SomeVal = LI;
  278. else
  279. SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
  280. if (BaseName.empty())
  281. BaseName = SomeVal->getName();
  282. SSA.Initialize(SomeVal->getType(), BaseName);
  283. }
  284. void LoadAndStorePromoter::
  285. run(const SmallVectorImpl<Instruction*> &Insts) const {
  286. // First step: bucket up uses of the alloca by the block they occur in.
  287. // This is important because we have to handle multiple defs/uses in a block
  288. // ourselves: SSAUpdater is purely for cross-block references.
  289. DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock;
  290. for (Instruction *User : Insts)
  291. UsesByBlock[User->getParent()].push_back(User);
  292. // Okay, now we can iterate over all the blocks in the function with uses,
  293. // processing them. Keep track of which loads are loading a live-in value.
  294. // Walk the uses in the use-list order to be determinstic.
  295. SmallVector<LoadInst*, 32> LiveInLoads;
  296. DenseMap<Value*, Value*> ReplacedLoads;
  297. for (Instruction *User : Insts) {
  298. BasicBlock *BB = User->getParent();
  299. TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB];
  300. // If this block has already been processed, ignore this repeat use.
  301. if (BlockUses.empty()) continue;
  302. // Okay, this is the first use in the block. If this block just has a
  303. // single user in it, we can rewrite it trivially.
  304. if (BlockUses.size() == 1) {
  305. // If it is a store, it is a trivial def of the value in the block.
  306. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  307. updateDebugInfo(SI);
  308. SSA.AddAvailableValue(BB, SI->getOperand(0));
  309. } else
  310. // Otherwise it is a load, queue it to rewrite as a live-in load.
  311. LiveInLoads.push_back(cast<LoadInst>(User));
  312. BlockUses.clear();
  313. continue;
  314. }
  315. // Otherwise, check to see if this block is all loads.
  316. bool HasStore = false;
  317. for (Instruction *I : BlockUses) {
  318. if (isa<StoreInst>(I)) {
  319. HasStore = true;
  320. break;
  321. }
  322. }
  323. // If so, we can queue them all as live in loads. We don't have an
  324. // efficient way to tell which on is first in the block and don't want to
  325. // scan large blocks, so just add all loads as live ins.
  326. if (!HasStore) {
  327. for (Instruction *I : BlockUses)
  328. LiveInLoads.push_back(cast<LoadInst>(I));
  329. BlockUses.clear();
  330. continue;
  331. }
  332. // Otherwise, we have mixed loads and stores (or just a bunch of stores).
  333. // Since SSAUpdater is purely for cross-block values, we need to determine
  334. // the order of these instructions in the block. If the first use in the
  335. // block is a load, then it uses the live in value. The last store defines
  336. // the live out value. We handle this by doing a linear scan of the block.
  337. Value *StoredValue = nullptr;
  338. for (Instruction &I : *BB) {
  339. if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
  340. // If this is a load from an unrelated pointer, ignore it.
  341. if (!isInstInList(L, Insts)) continue;
  342. // If we haven't seen a store yet, this is a live in use, otherwise
  343. // use the stored value.
  344. if (StoredValue) {
  345. replaceLoadWithValue(L, StoredValue);
  346. L->replaceAllUsesWith(StoredValue);
  347. ReplacedLoads[L] = StoredValue;
  348. } else {
  349. LiveInLoads.push_back(L);
  350. }
  351. continue;
  352. }
  353. if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  354. // If this is a store to an unrelated pointer, ignore it.
  355. if (!isInstInList(SI, Insts)) continue;
  356. updateDebugInfo(SI);
  357. // Remember that this is the active value in the block.
  358. StoredValue = SI->getOperand(0);
  359. }
  360. }
  361. // The last stored value that happened is the live-out for the block.
  362. assert(StoredValue && "Already checked that there is a store in block");
  363. SSA.AddAvailableValue(BB, StoredValue);
  364. BlockUses.clear();
  365. }
  366. // Okay, now we rewrite all loads that use live-in values in the loop,
  367. // inserting PHI nodes as necessary.
  368. for (LoadInst *ALoad : LiveInLoads) {
  369. Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
  370. replaceLoadWithValue(ALoad, NewVal);
  371. // Avoid assertions in unreachable code.
  372. if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
  373. ALoad->replaceAllUsesWith(NewVal);
  374. ReplacedLoads[ALoad] = NewVal;
  375. }
  376. // Allow the client to do stuff before we start nuking things.
  377. doExtraRewritesBeforeFinalDeletion();
  378. // Now that everything is rewritten, delete the old instructions from the
  379. // function. They should all be dead now.
  380. for (Instruction *User : Insts) {
  381. // If this is a load that still has uses, then the load must have been added
  382. // as a live value in the SSAUpdate data structure for a block (e.g. because
  383. // the loaded value was stored later). In this case, we need to recursively
  384. // propagate the updates until we get to the real value.
  385. if (!User->use_empty()) {
  386. Value *NewVal = ReplacedLoads[User];
  387. assert(NewVal && "not a replaced load?");
  388. // Propagate down to the ultimate replacee. The intermediately loads
  389. // could theoretically already have been deleted, so we don't want to
  390. // dereference the Value*'s.
  391. DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
  392. while (RLI != ReplacedLoads.end()) {
  393. NewVal = RLI->second;
  394. RLI = ReplacedLoads.find(NewVal);
  395. }
  396. replaceLoadWithValue(cast<LoadInst>(User), NewVal);
  397. User->replaceAllUsesWith(NewVal);
  398. }
  399. instructionDeleted(User);
  400. User->eraseFromParent();
  401. }
  402. }
  403. bool
  404. LoadAndStorePromoter::isInstInList(Instruction *I,
  405. const SmallVectorImpl<Instruction*> &Insts)
  406. const {
  407. return std::find(Insts.begin(), Insts.end(), I) != Insts.end();
  408. }