SSAUpdater.cpp 16 KB

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