SSAUpdater.cpp 16 KB

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