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/AliasSetTracker.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Support/InstVisitor.h"
33 #include "llvm/Support/CFG.h"
34 #include "Support/CommandLine.h"
35 #include "Support/Debug.h"
36 #include "Support/Statistic.h"
37 #include "llvm/Assembly/Writer.h"
41 cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
42 cl::desc("Disable memory promotion in LICM pass"));
44 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
45 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
46 Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
48 struct LICM : public FunctionPass, public InstVisitor<LICM> {
49 virtual bool runOnFunction(Function &F);
51 /// This transformation requires natural loop information & requires that
52 /// loop preheaders be inserted into the CFG...
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequiredID(LoopPreheadersID);
57 AU.addRequired<LoopInfo>();
58 AU.addRequired<DominatorTree>();
59 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
60 AU.addRequired<AliasAnalysis>();
64 LoopInfo *LI; // Current LoopInfo
65 AliasAnalysis *AA; // Current AliasAnalysis information
66 DominanceFrontier *DF; // Current Dominance Frontier
67 bool Changed; // Set to true when we change anything.
68 BasicBlock *Preheader; // The preheader block of the current loop...
69 Loop *CurLoop; // The current loop we are working on...
70 AliasSetTracker *CurAST; // AliasSet information for the current loop...
71 DominatorTree *DT; // Dominator Tree for the current Loop...
73 /// visitLoop - Hoist expressions out of the specified loop...
75 void visitLoop(Loop *L, AliasSetTracker &AST);
77 /// HoistRegion - Walk the specified region of the CFG (defined by all
78 /// blocks dominated by the specified block, and that are in the current
79 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
80 /// visit defintions before uses, allowing us to hoist a loop body in one
81 /// pass without iteration.
83 void HoistRegion(DominatorTree::Node *N);
85 /// inSubLoop - Little predicate that returns true if the specified basic
86 /// block is in a subloop of the current one, not the current one itself.
88 bool inSubLoop(BasicBlock *BB) {
89 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
90 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
91 if (CurLoop->getSubLoops()[i]->contains(BB))
92 return true; // A subloop actually contains this block!
96 /// hoist - When an instruction is found to only use loop invariant operands
97 /// that is safe to hoist, this instruction is called to do the dirty work.
99 void hoist(Instruction &I);
101 /// SafeToHoist - Only hoist an instruction if it is not a trapping instruction
102 /// or if it is a trapping instruction and is guaranteed to execute
104 bool SafeToHoist(Instruction &I);
106 /// pointerInvalidatedByLoop - Return true if the body of this loop may
107 /// store into the memory location pointed to by V.
109 bool pointerInvalidatedByLoop(Value *V) {
110 // Check to see if any of the basic blocks in CurLoop invalidate *V.
111 return CurAST->getAliasSetForPointer(V, 0).isMod();
114 /// isLoopInvariant - Return true if the specified value is loop invariant
116 inline bool isLoopInvariant(Value *V) {
117 if (Instruction *I = dyn_cast<Instruction>(V))
118 return !CurLoop->contains(I->getParent());
119 return true; // All non-instructions are loop invariant
122 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
123 /// to scalars as we can.
125 void PromoteValuesInLoop();
127 /// findPromotableValuesInLoop - Check the current loop for stores to
128 /// definite pointers, which are not loaded and stored through may aliases.
129 /// If these are found, create an alloca for the value, add it to the
130 /// PromotedValues list, and keep track of the mapping from value to
133 void findPromotableValuesInLoop(
134 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
135 std::map<Value*, AllocaInst*> &Val2AlMap);
138 /// Instruction visitation handlers... these basically control whether or
139 /// not the specified instruction types are hoisted.
141 friend class InstVisitor<LICM>;
142 void visitBinaryOperator(Instruction &I) {
143 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)) && SafeToHoist(I))
146 void visitCastInst(CastInst &CI) {
147 Instruction &I = (Instruction&)CI;
148 if (isLoopInvariant(I.getOperand(0)) && SafeToHoist(CI)) hoist(I);
150 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
152 void visitLoadInst(LoadInst &LI);
154 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
155 Instruction &I = (Instruction&)GEPI;
156 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
157 if (!isLoopInvariant(I.getOperand(i))) return;
158 if(SafeToHoist(GEPI))
163 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
166 Pass *createLICMPass() { return new LICM(); }
168 /// runOnFunction - For LICM, this simply traverses the loop structure of the
169 /// function, hoisting expressions out of loops if possible.
171 bool LICM::runOnFunction(Function &) {
174 // Get our Loop and Alias Analysis information...
175 LI = &getAnalysis<LoopInfo>();
176 AA = &getAnalysis<AliasAnalysis>();
177 DF = &getAnalysis<DominanceFrontier>();
178 DT = &getAnalysis<DominatorTree>();
180 // Hoist expressions out of all of the top-level loops.
181 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
182 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
183 E = TopLevelLoops.end(); I != E; ++I) {
184 AliasSetTracker AST(*AA);
185 LICM::visitLoop(*I, AST);
191 /// visitLoop - Hoist expressions out of the specified loop...
193 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
194 // Recurse through all subloops before we process this loop...
195 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
196 E = L->getSubLoops().end(); I != E; ++I) {
197 AliasSetTracker SubAST(*AA);
198 LICM::visitLoop(*I, SubAST);
200 // Incorporate information about the subloops into this loop...
206 // Get the preheader block to move instructions into...
207 Preheader = L->getLoopPreheader();
208 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
210 // Loop over the body of this loop, looking for calls, invokes, and stores.
211 // Because subloops have already been incorporated into AST, we skip blocks in
214 const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
215 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
216 E = LoopBBs.end(); I != E; ++I)
217 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
218 AST.add(**I); // Incorporate the specified basic block
220 // We want to visit all of the instructions in this loop... that are not parts
221 // of our subloops (they have already had their invariants hoisted out of
222 // their loop, into this loop, so there is no need to process the BODIES of
225 // Traverse the body of the loop in depth first order on the dominator tree so
226 // that we are guaranteed to see definitions before we see uses. This allows
227 // us to perform the LICM transformation in one pass, without iteration.
229 HoistRegion(DT->getNode(L->getHeader()));
231 // Now that all loop invariants have been removed from the loop, promote any
232 // memory references to scalars that we can...
233 if (!DisablePromotion)
234 PromoteValuesInLoop();
236 // Clear out loops state information for the next iteration
241 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
242 /// dominated by the specified block, and that are in the current loop) in depth
243 /// first order w.r.t the DominatorTree. This allows us to visit defintions
244 /// before uses, allowing us to hoist a loop body in one pass without iteration.
246 void LICM::HoistRegion(DominatorTree::Node *N) {
247 assert(N != 0 && "Null dominator tree node?");
249 // If this subregion is not in the top level loop at all, exit.
250 if (!CurLoop->contains(N->getBlock())) return;
252 // Only need to hoist the contents of this block if it is not part of a
253 // subloop (which would already have been hoisted)
254 if (!inSubLoop(N->getBlock()))
255 visit(*N->getBlock());
257 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
258 for (unsigned i = 0, e = Children.size(); i != e; ++i)
259 HoistRegion(Children[i]);
263 /// hoist - When an instruction is found to only use loop invariant operands
264 /// that is safe to hoist, this instruction is called to do the dirty work.
266 void LICM::hoist(Instruction &Inst) {
267 DEBUG(std::cerr << "LICM hoisting to";
268 WriteAsOperand(std::cerr, Preheader, false);
269 std::cerr << ": " << Inst);
271 // Remove the instruction from its current basic block... but don't delete the
273 Inst.getParent()->getInstList().remove(&Inst);
275 // Insert the new node in Preheader, before the terminator.
276 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
282 /// SafeToHoist - Only hoist an instruction if it is not a trapping instruction
283 /// or if it is a trapping instruction and is guaranteed to execute
285 bool LICM::SafeToHoist(Instruction &Inst) {
287 //If it is a trapping instruction, then check if its guaranteed to execute.
288 if(Inst.isTrapping()) {
290 //Get the instruction's basic block.
291 BasicBlock *InstBB = Inst.getParent();
293 //Get the Dominator Tree Node for the instruction's basic block/
294 DominatorTree::Node *InstDTNode = DT->getNode(InstBB);
296 //Get the exit blocks for the current loop.
297 const std::vector<BasicBlock* > &ExitBlocks = CurLoop->getExitBlocks();
299 //For each exit block, get the DT node and walk up the DT until
300 //the instruction's basic block is found or we exit the loop.
301 for(unsigned i=0; i < ExitBlocks.size(); ++i) {
302 DominatorTree::Node *IDom = DT->getNode(ExitBlocks[i]);
304 while(IDom != InstDTNode) {
306 //Get next Immediate Dominator.
307 IDom = IDom->getIDom();
309 //See if we exited the loop.
310 if(!CurLoop->contains(IDom->getBlock()))
320 void LICM::visitLoadInst(LoadInst &LI) {
321 if (isLoopInvariant(LI.getOperand(0)) && !LI.isVolatile() &&
322 !pointerInvalidatedByLoop(LI.getOperand(0)) && SafeToHoist(LI)) {
328 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
329 /// stores out of the loop and moving loads to before the loop. We do this by
330 /// looping over the stores in the loop, looking for stores to Must pointers
331 /// which are loop invariant. We promote these memory locations to use allocas
332 /// instead. These allocas can easily be raised to register values by the
333 /// PromoteMem2Reg functionality.
335 void LICM::PromoteValuesInLoop() {
336 // PromotedValues - List of values that are promoted out of the loop. Each
337 // value has an alloca instruction for it, and a canonical version of the
339 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
340 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
342 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
343 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
346 NumPromoted += PromotedValues.size();
348 // Emit a copy from the value into the alloca'd value in the loop preheader
349 TerminatorInst *LoopPredInst = Preheader->getTerminator();
350 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
351 // Load from the memory we are promoting...
352 LoadInst *LI = new LoadInst(PromotedValues[i].second,
353 PromotedValues[i].second->getName()+".promoted",
355 // Store into the temporary alloca...
356 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
359 // Scan the basic blocks in the loop, replacing uses of our pointers with
360 // uses of the allocas in question. If we find a branch that exits the
361 // loop, make sure to put reload code into all of the successors of the
364 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
365 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
366 E = LoopBBs.end(); I != E; ++I) {
367 // Rewrite all loads and stores in the block of the pointer...
368 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
370 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
371 std::map<Value*, AllocaInst*>::iterator
372 I = ValueToAllocaMap.find(L->getOperand(0));
373 if (I != ValueToAllocaMap.end())
374 L->setOperand(0, I->second); // Rewrite load instruction...
375 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
376 std::map<Value*, AllocaInst*>::iterator
377 I = ValueToAllocaMap.find(S->getOperand(1));
378 if (I != ValueToAllocaMap.end())
379 S->setOperand(1, I->second); // Rewrite store instruction...
383 // Check to see if any successors of this block are outside of the loop.
384 // If so, we need to copy the value from the alloca back into the memory
387 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
388 if (!CurLoop->contains(*SI)) {
389 // Copy all of the allocas into their memory locations...
390 BasicBlock::iterator BI = (*SI)->begin();
391 while (isa<PHINode>(*BI))
392 ++BI; // Skip over all of the phi nodes in the block...
393 Instruction *InsertPos = BI;
394 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
395 // Load from the alloca...
396 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
397 // Store into the memory we promoted...
398 new StoreInst(LI, PromotedValues[i].second, InsertPos);
403 // Now that we have done the deed, use the mem2reg functionality to promote
404 // all of the new allocas we just created into real SSA registers...
406 std::vector<AllocaInst*> PromotedAllocas;
407 PromotedAllocas.reserve(PromotedValues.size());
408 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
409 PromotedAllocas.push_back(PromotedValues[i].first);
410 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData());
413 /// findPromotableValuesInLoop - Check the current loop for stores to definite
414 /// pointers, which are not loaded and stored through may aliases. If these are
415 /// found, create an alloca for the value, add it to the PromotedValues list,
416 /// and keep track of the mapping from value to alloca...
418 void LICM::findPromotableValuesInLoop(
419 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
420 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
421 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
423 // Loop over all of the alias sets in the tracker object...
424 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
427 // We can promote this alias set if it has a store, if it is a "Must" alias
428 // set, and if the pointer is loop invariant.
429 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
430 isLoopInvariant(AS.begin()->first)) {
431 assert(AS.begin() != AS.end() &&
432 "Must alias set should have at least one pointer element in it!");
433 Value *V = AS.begin()->first;
435 // Check that all of the pointers in the alias set have the same type. We
436 // cannot (yet) promote a memory location that is loaded and stored in
438 bool PointerOk = true;
439 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
440 if (V->getType() != I->first->getType()) {
446 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
447 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
448 PromotedValues.push_back(std::make_pair(AI, V));
450 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
451 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
453 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");