1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // This pass is a simple loop invariant code motion pass. An interesting aspect
4 // of this pass is that it uses alias analysis for two purposes:
6 // 1. Moving loop invariant loads out of loops. If we can determine that a
7 // load inside of a loop never aliases anything stored to, we can hoist it
8 // like any other instruction.
9 // 2. Scalar Promotion of Memory - If there is a store instruction inside of
10 // the loop, we try to move the store to happen AFTER the loop instead of
11 // inside of the loop. This can only happen if a few conditions are true:
12 // A. The pointer stored through is loop invariant
13 // B. There are no stores or loads in the loop which _may_ alias the
14 // pointer. There are no calls in the loop which mod/ref the pointer.
15 // If these conditions are true, we can promote the loads and stores in the
16 // loop of the pointer to use a temporary alloca'd variable. We then use
17 // the mem2reg functionality to construct the appropriate SSA form for the
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
33 #include "Support/CommandLine.h"
34 #include "llvm/Assembly/Writer.h"
38 cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
39 cl::desc("Disable memory promotion in LICM pass"));
41 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
42 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
43 Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
45 /// LoopBodyInfo - We recursively traverse loops from most-deeply-nested to
46 /// least-deeply-nested. For all of the loops nested within the current one,
47 /// we keep track of information so that we don't have to repeat queries.
50 std::vector<CallInst*> Calls; // Call instructions in loop
51 std::vector<InvokeInst*> Invokes; // Invoke instructions in loop
53 // StoredPointers - Targets of store instructions...
54 std::set<Value*> StoredPointers;
56 // LoadedPointers - Source pointers for load instructions...
57 std::set<Value*> LoadedPointers;
60 PointerUnknown = 0, // Nothing is known about this pointer yet
61 PointerMustStore, // Memory is stored to ONLY through this pointer
62 PointerMayStore, // Memory is stored to through this or other pointers
63 PointerNoStore // Memory is not modified in this loop
66 // PointerIsModified - Keep track of information as we find out about it in
69 std::map<Value*, enum PointerClass> PointerIsModified;
71 /// CantModifyAnyPointers - Return true if no memory modifying instructions
72 /// occur in this loop. This is just a conservative approximation, because
73 /// a call may not actually store anything.
74 bool CantModifyAnyPointers() const {
75 return Calls.empty() && Invokes.empty() && StoredPointers.empty();
78 /// incorporate - Incorporate information about a subloop into the current
80 void incorporate(const LoopBodyInfo &OtherLBI);
81 void incorporate(BasicBlock &BB); // do the same for a basic block
83 PointerClass getPointerInfo(Value *V, AliasAnalysis &AA) {
84 PointerClass &VInfo = PointerIsModified[V];
85 if (VInfo == PointerUnknown)
86 VInfo = calculatePointerInfo(V, AA);
90 /// calculatePointerInfo - Calculate information about the specified
92 PointerClass calculatePointerInfo(Value *V, AliasAnalysis &AA) const;
96 /// incorporate - Incorporate information about a subloop into the current loop.
97 void LoopBodyInfo::incorporate(const LoopBodyInfo &OtherLBI) {
98 // Do not incorporate NonModifiedPointers (which is just a cache) because it
99 // is too much trouble to make sure it's still valid.
100 Calls.insert (Calls.end(), OtherLBI.Calls.begin(), OtherLBI.Calls.end());
101 Invokes.insert(Invokes.end(),OtherLBI.Invokes.begin(),OtherLBI.Invokes.end());
102 StoredPointers.insert(OtherLBI.StoredPointers.begin(),
103 OtherLBI.StoredPointers.end());
104 LoadedPointers.insert(OtherLBI.LoadedPointers.begin(),
105 OtherLBI.LoadedPointers.end());
108 void LoopBodyInfo::incorporate(BasicBlock &BB) {
109 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
110 if (CallInst *CI = dyn_cast<CallInst>(&*I))
112 else if (StoreInst *SI = dyn_cast<StoreInst>(&*I))
113 StoredPointers.insert(SI->getOperand(1));
114 else if (LoadInst *LI = dyn_cast<LoadInst>(&*I))
115 LoadedPointers.insert(LI->getOperand(0));
117 if (InvokeInst *II = dyn_cast<InvokeInst>(BB.getTerminator()))
118 Invokes.push_back(II);
122 // calculatePointerInfo - Calculate information about the specified pointer.
123 LoopBodyInfo::PointerClass LoopBodyInfo::calculatePointerInfo(Value *V,
124 AliasAnalysis &AA) const {
125 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
126 if (AA.getModRefInfo(Calls[i], V, ~0))
127 return PointerMayStore;
129 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
130 if (AA.getModRefInfo(Invokes[i], V, ~0))
131 return PointerMayStore;
133 PointerClass Result = PointerNoStore;
134 for (std::set<Value*>::const_iterator I = StoredPointers.begin(),
135 E = StoredPointers.end(); I != E; ++I)
136 if (AA.alias(V, ~0, *I, ~0))
138 Result = PointerMustStore; // If this is the only alias, return must
140 return PointerMayStore; // We have to return may
145 struct LICM : public FunctionPass, public InstVisitor<LICM> {
146 virtual bool runOnFunction(Function &F);
148 /// This transformation requires natural loop information & requires that
149 /// loop preheaders be inserted into the CFG...
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152 AU.setPreservesCFG();
153 AU.addRequiredID(LoopPreheadersID);
154 AU.addRequired<LoopInfo>();
155 AU.addRequired<DominatorTree>();
156 AU.addRequired<DominanceFrontier>();
157 AU.addRequired<AliasAnalysis>();
161 LoopInfo *LI; // Current LoopInfo
162 AliasAnalysis *AA; // Current AliasAnalysis information
163 bool Changed; // Set to true when we change anything.
164 BasicBlock *Preheader; // The preheader block of the current loop...
165 Loop *CurLoop; // The current loop we are working on...
166 LoopBodyInfo *CurLBI; // Information about the current loop...
168 /// visitLoop - Hoist expressions out of the specified loop...
170 void visitLoop(Loop *L, LoopBodyInfo &LBI);
172 /// HoistRegion - Walk the specified region of the CFG (defined by all
173 /// blocks dominated by the specified block, and that are in the current
174 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
175 /// visit defintions before uses, allowing us to hoist a loop body in one
176 /// pass without iteration.
178 void HoistRegion(DominatorTree::Node *N);
180 /// inSubLoop - Little predicate that returns true if the specified basic
181 /// block is in a subloop of the current one, not the current one itself.
183 bool inSubLoop(BasicBlock *BB) {
184 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
185 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
186 if (CurLoop->getSubLoops()[i]->contains(BB))
187 return true; // A subloop actually contains this block!
191 /// hoist - When an instruction is found to only use loop invariant operands
192 /// that is safe to hoist, this instruction is called to do the dirty work.
194 void hoist(Instruction &I);
196 /// pointerInvalidatedByLoop - Return true if the body of this loop may
197 /// store into the memory location pointed to by V.
199 bool pointerInvalidatedByLoop(Value *V) {
200 // Check to see if any of the basic blocks in CurLoop invalidate V.
201 return CurLBI->getPointerInfo(V, *AA) != LoopBodyInfo::PointerNoStore;
204 /// isLoopInvariant - Return true if the specified value is loop invariant
206 inline bool isLoopInvariant(Value *V) {
207 if (Instruction *I = dyn_cast<Instruction>(V))
208 return !CurLoop->contains(I->getParent());
209 return true; // All non-instructions are loop invariant
212 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
213 /// to scalars as we can.
215 void PromoteValuesInLoop();
217 /// findPromotableValuesInLoop - Check the current loop for stores to
218 /// definate pointers, which are not loaded and stored through may aliases.
219 /// If these are found, create an alloca for the value, add it to the
220 /// PromotedValues list, and keep track of the mapping from value to
223 void findPromotableValuesInLoop(
224 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
225 std::map<Value*, AllocaInst*> &Val2AlMap);
228 /// Instruction visitation handlers... these basically control whether or
229 /// not the specified instruction types are hoisted.
231 friend class InstVisitor<LICM>;
232 void visitBinaryOperator(Instruction &I) {
233 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
236 void visitCastInst(CastInst &CI) {
237 Instruction &I = (Instruction&)CI;
238 if (isLoopInvariant(I.getOperand(0))) hoist(I);
240 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
242 void visitLoadInst(LoadInst &LI);
244 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
245 Instruction &I = (Instruction&)GEPI;
246 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
247 if (!isLoopInvariant(I.getOperand(i))) return;
252 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
255 Pass *createLICMPass() { return new LICM(); }
257 /// runOnFunction - For LICM, this simply traverses the loop structure of the
258 /// function, hoisting expressions out of loops if possible.
260 bool LICM::runOnFunction(Function &) {
263 // Get our Loop and Alias Analysis information...
264 LI = &getAnalysis<LoopInfo>();
265 AA = &getAnalysis<AliasAnalysis>();
267 // Hoist expressions out of all of the top-level loops.
268 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
269 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
270 E = TopLevelLoops.end(); I != E; ++I) {
272 LICM::visitLoop(*I, LBI);
278 /// visitLoop - Hoist expressions out of the specified loop...
280 void LICM::visitLoop(Loop *L, LoopBodyInfo &LBI) {
281 // Recurse through all subloops before we process this loop...
282 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
283 E = L->getSubLoops().end(); I != E; ++I) {
285 LICM::visitLoop(*I, SubLBI);
287 // Incorporate information about the subloops into this loop...
288 LBI.incorporate(SubLBI);
293 // Get the preheader block to move instructions into...
294 Preheader = L->getLoopPreheader();
295 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
297 // Loop over the body of this loop, looking for calls, invokes, and stores.
298 // Because subloops have already been incorporated into LBI, we skip blocks in
301 const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
302 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
303 E = LoopBBs.end(); I != E; ++I)
304 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
305 LBI.incorporate(**I); // Incorporate the specified basic block
307 // We want to visit all of the instructions in this loop... that are not parts
308 // of our subloops (they have already had their invariants hoisted out of
309 // their loop, into this loop, so there is no need to process the BODIES of
312 // Traverse the body of the loop in depth first order on the dominator tree so
313 // that we are guaranteed to see definitions before we see uses. This allows
314 // us to perform the LICM transformation in one pass, without iteration.
316 HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
318 // Now that all loop invariants have been removed from the loop, promote any
319 // memory references to scalars that we can...
320 if (!DisablePromotion)
321 PromoteValuesInLoop();
323 // Clear out loops state information for the next iteration
328 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
329 /// dominated by the specified block, and that are in the current loop) in depth
330 /// first order w.r.t the DominatorTree. This allows us to visit defintions
331 /// before uses, allowing us to hoist a loop body in one pass without iteration.
333 void LICM::HoistRegion(DominatorTree::Node *N) {
334 assert(N != 0 && "Null dominator tree node?");
336 // If this subregion is not in the top level loop at all, exit.
337 if (!CurLoop->contains(N->getNode())) return;
339 // Only need to hoist the contents of this block if it is not part of a
340 // subloop (which would already have been hoisted)
341 if (!inSubLoop(N->getNode()))
342 visit(*N->getNode());
344 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
345 for (unsigned i = 0, e = Children.size(); i != e; ++i)
346 HoistRegion(Children[i]);
350 /// hoist - When an instruction is found to only use loop invariant operands
351 /// that is safe to hoist, this instruction is called to do the dirty work.
353 void LICM::hoist(Instruction &Inst) {
354 DEBUG(std::cerr << "LICM hoisting to";
355 WriteAsOperand(std::cerr, Preheader, false);
356 std::cerr << ": " << Inst);
358 // Remove the instruction from its current basic block... but don't delete the
360 Inst.getParent()->getInstList().remove(&Inst);
362 // Insert the new node in Preheader, before the terminator.
363 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
370 void LICM::visitLoadInst(LoadInst &LI) {
371 if (isLoopInvariant(LI.getOperand(0)) &&
372 !pointerInvalidatedByLoop(LI.getOperand(0))) {
378 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
379 /// stores out of the loop and moving loads to before the loop. We do this by
380 /// looping over the stores in the loop, looking for stores to Must pointers
381 /// which are loop invariant. We promote these memory locations to use allocas
382 /// instead. These allocas can easily be raised to register values by the
383 /// PromoteMem2Reg functionality.
385 void LICM::PromoteValuesInLoop() {
386 // PromotedValues - List of values that are promoted out of the loop. Each
387 // value has an alloca instruction for it, and a cannonical version of the
389 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
390 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
392 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
393 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
396 NumPromoted += PromotedValues.size();
398 // Emit a copy from the value into the alloca'd value in the loop preheader
399 TerminatorInst *LoopPredInst = Preheader->getTerminator();
400 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
401 // Load from the memory we are promoting...
402 LoadInst *LI = new LoadInst(PromotedValues[i].second,
403 PromotedValues[i].second->getName()+".promoted",
405 // Store into the temporary alloca...
406 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
409 // Scan the basic blocks in the loop, replacing uses of our pointers with
410 // uses of the allocas in question. If we find a branch that exits the
411 // loop, make sure to put reload code into all of the successors of the
414 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
415 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
416 E = LoopBBs.end(); I != E; ++I) {
417 // Rewrite all loads and stores in the block of the pointer...
418 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
420 if (LoadInst *L = dyn_cast<LoadInst>(&*II)) {
421 std::map<Value*, AllocaInst*>::iterator
422 I = ValueToAllocaMap.find(L->getOperand(0));
423 if (I != ValueToAllocaMap.end())
424 L->setOperand(0, I->second); // Rewrite load instruction...
425 } else if (StoreInst *S = dyn_cast<StoreInst>(&*II)) {
426 std::map<Value*, AllocaInst*>::iterator
427 I = ValueToAllocaMap.find(S->getOperand(1));
428 if (I != ValueToAllocaMap.end())
429 S->setOperand(1, I->second); // Rewrite store instruction...
433 // Check to see if any successors of this block are outside of the loop.
434 // If so, we need to copy the value from the alloca back into the memory
437 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
438 if (!CurLoop->contains(*SI)) {
439 // Copy all of the allocas into their memory locations...
440 Instruction *InsertPos = (*SI)->begin();
441 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
442 // Load from the alloca...
443 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
444 // Store into the memory we promoted...
445 new StoreInst(LI, PromotedValues[i].second, InsertPos);
450 // Now that we have done the deed, use the mem2reg functionality to promote
451 // all of the new allocas we just created into real SSA registers...
453 std::vector<AllocaInst*> PromotedAllocas;
454 PromotedAllocas.reserve(PromotedValues.size());
455 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
456 PromotedAllocas.push_back(PromotedValues[i].first);
457 PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>());
460 /// findPromotableValuesInLoop - Check the current loop for stores to definate
461 /// pointers, which are not loaded and stored through may aliases. If these are
462 /// found, create an alloca for the value, add it to the PromotedValues list,
463 /// and keep track of the mapping from value to alloca...
465 void LICM::findPromotableValuesInLoop(
466 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
467 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
468 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
470 for (std::set<Value*>::iterator I = CurLBI->StoredPointers.begin(),
471 E = CurLBI->StoredPointers.end(); I != E; ++I) {
473 if (isLoopInvariant(V) &&
474 CurLBI->getPointerInfo(V, *AA) == LoopBodyInfo::PointerMustStore) {
476 // Don't add a new entry for this stored pointer if it aliases something
477 // we have already processed.
478 std::map<Value*, AllocaInst*>::iterator V2AMI =
479 ValueToAllocaMap.lower_bound(V);
480 if (V2AMI == ValueToAllocaMap.end() || V2AMI->first != V) {
481 // Check to make sure that any loads in the loop are either NO or MUST
482 // aliases. We cannot rewrite loads that _might_ come from this memory
485 bool PointerOk = true;
486 for (std::set<Value*>::const_iterator I =CurLBI->LoadedPointers.begin(),
487 E = CurLBI->LoadedPointers.end(); I != E; ++I)
488 if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MayAlias) {
494 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
495 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
496 PromotedValues.push_back(std::make_pair(AI, V));
497 ValueToAllocaMap.insert(V2AMI, std::make_pair(V, AI));
499 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
501 // Loop over all of the loads and stores that alias this pointer,
502 // adding them to the Value2AllocaMap as well...
503 for (std::set<Value*>::const_iterator
504 I = CurLBI->LoadedPointers.begin(),
505 E = CurLBI->LoadedPointers.end(); I != E; ++I)
506 if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
507 ValueToAllocaMap[*I] = AI;
509 for (std::set<Value*>::const_iterator
510 I = CurLBI->StoredPointers.begin(),
511 E = CurLBI->StoredPointers.end(); I != E; ++I)
512 if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
513 ValueToAllocaMap[*I] = AI;