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/Statistic.h"
35 #include "Support/CommandLine.h"
36 #include "llvm/Assembly/Writer.h"
40 cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
41 cl::desc("Disable memory promotion in LICM pass"));
43 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
44 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
45 Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
47 struct LICM : public FunctionPass, public InstVisitor<LICM> {
48 virtual bool runOnFunction(Function &F);
50 /// This transformation requires natural loop information & requires that
51 /// loop preheaders be inserted into the CFG...
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequiredID(LoopPreheadersID);
56 AU.addRequired<LoopInfo>();
57 AU.addRequired<DominatorTree>();
58 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
59 AU.addRequired<AliasAnalysis>();
63 LoopInfo *LI; // Current LoopInfo
64 AliasAnalysis *AA; // Current AliasAnalysis information
65 bool Changed; // Set to true when we change anything.
66 BasicBlock *Preheader; // The preheader block of the current loop...
67 Loop *CurLoop; // The current loop we are working on...
68 AliasSetTracker *CurAST; // AliasSet information for the current loop...
70 /// visitLoop - Hoist expressions out of the specified loop...
72 void visitLoop(Loop *L, AliasSetTracker &AST);
74 /// HoistRegion - Walk the specified region of the CFG (defined by all
75 /// blocks dominated by the specified block, and that are in the current
76 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
77 /// visit defintions before uses, allowing us to hoist a loop body in one
78 /// pass without iteration.
80 void HoistRegion(DominatorTree::Node *N);
82 /// inSubLoop - Little predicate that returns true if the specified basic
83 /// block is in a subloop of the current one, not the current one itself.
85 bool inSubLoop(BasicBlock *BB) {
86 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
87 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
88 if (CurLoop->getSubLoops()[i]->contains(BB))
89 return true; // A subloop actually contains this block!
93 /// hoist - When an instruction is found to only use loop invariant operands
94 /// that is safe to hoist, this instruction is called to do the dirty work.
96 void hoist(Instruction &I);
98 /// pointerInvalidatedByLoop - Return true if the body of this loop may
99 /// store into the memory location pointed to by V.
101 bool pointerInvalidatedByLoop(Value *V) {
102 // Check to see if any of the basic blocks in CurLoop invalidate *V.
103 return CurAST->getAliasSetForPointer(V, 0).isMod();
106 /// isLoopInvariant - Return true if the specified value is loop invariant
108 inline bool isLoopInvariant(Value *V) {
109 if (Instruction *I = dyn_cast<Instruction>(V))
110 return !CurLoop->contains(I->getParent());
111 return true; // All non-instructions are loop invariant
114 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
115 /// to scalars as we can.
117 void PromoteValuesInLoop();
119 /// findPromotableValuesInLoop - Check the current loop for stores to
120 /// definate pointers, which are not loaded and stored through may aliases.
121 /// If these are found, create an alloca for the value, add it to the
122 /// PromotedValues list, and keep track of the mapping from value to
125 void findPromotableValuesInLoop(
126 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
127 std::map<Value*, AllocaInst*> &Val2AlMap);
130 /// Instruction visitation handlers... these basically control whether or
131 /// not the specified instruction types are hoisted.
133 friend class InstVisitor<LICM>;
134 void visitBinaryOperator(Instruction &I) {
135 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
138 void visitCastInst(CastInst &CI) {
139 Instruction &I = (Instruction&)CI;
140 if (isLoopInvariant(I.getOperand(0))) hoist(I);
142 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
144 void visitLoadInst(LoadInst &LI);
146 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
147 Instruction &I = (Instruction&)GEPI;
148 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
149 if (!isLoopInvariant(I.getOperand(i))) return;
154 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
157 Pass *createLICMPass() { return new LICM(); }
159 /// runOnFunction - For LICM, this simply traverses the loop structure of the
160 /// function, hoisting expressions out of loops if possible.
162 bool LICM::runOnFunction(Function &) {
165 // Get our Loop and Alias Analysis information...
166 LI = &getAnalysis<LoopInfo>();
167 AA = &getAnalysis<AliasAnalysis>();
169 // Hoist expressions out of all of the top-level loops.
170 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
171 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
172 E = TopLevelLoops.end(); I != E; ++I) {
173 AliasSetTracker AST(*AA);
174 LICM::visitLoop(*I, AST);
180 /// visitLoop - Hoist expressions out of the specified loop...
182 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
183 // Recurse through all subloops before we process this loop...
184 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
185 E = L->getSubLoops().end(); I != E; ++I) {
186 AliasSetTracker SubAST(*AA);
187 LICM::visitLoop(*I, SubAST);
189 // Incorporate information about the subloops into this loop...
195 // Get the preheader block to move instructions into...
196 Preheader = L->getLoopPreheader();
197 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
199 // Loop over the body of this loop, looking for calls, invokes, and stores.
200 // Because subloops have already been incorporated into AST, we skip blocks in
203 const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
204 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
205 E = LoopBBs.end(); I != E; ++I)
206 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
207 AST.add(**I); // Incorporate the specified basic block
209 // We want to visit all of the instructions in this loop... that are not parts
210 // of our subloops (they have already had their invariants hoisted out of
211 // their loop, into this loop, so there is no need to process the BODIES of
214 // Traverse the body of the loop in depth first order on the dominator tree so
215 // that we are guaranteed to see definitions before we see uses. This allows
216 // us to perform the LICM transformation in one pass, without iteration.
218 HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
220 // Now that all loop invariants have been removed from the loop, promote any
221 // memory references to scalars that we can...
222 if (!DisablePromotion)
223 PromoteValuesInLoop();
225 // Clear out loops state information for the next iteration
230 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
231 /// dominated by the specified block, and that are in the current loop) in depth
232 /// first order w.r.t the DominatorTree. This allows us to visit defintions
233 /// before uses, allowing us to hoist a loop body in one pass without iteration.
235 void LICM::HoistRegion(DominatorTree::Node *N) {
236 assert(N != 0 && "Null dominator tree node?");
238 // If this subregion is not in the top level loop at all, exit.
239 if (!CurLoop->contains(N->getNode())) return;
241 // Only need to hoist the contents of this block if it is not part of a
242 // subloop (which would already have been hoisted)
243 if (!inSubLoop(N->getNode()))
244 visit(*N->getNode());
246 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
247 for (unsigned i = 0, e = Children.size(); i != e; ++i)
248 HoistRegion(Children[i]);
252 /// hoist - When an instruction is found to only use loop invariant operands
253 /// that is safe to hoist, this instruction is called to do the dirty work.
255 void LICM::hoist(Instruction &Inst) {
256 DEBUG(std::cerr << "LICM hoisting to";
257 WriteAsOperand(std::cerr, Preheader, false);
258 std::cerr << ": " << Inst);
260 // Remove the instruction from its current basic block... but don't delete the
262 Inst.getParent()->getInstList().remove(&Inst);
264 // Insert the new node in Preheader, before the terminator.
265 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
272 void LICM::visitLoadInst(LoadInst &LI) {
273 if (isLoopInvariant(LI.getOperand(0)) &&
274 !pointerInvalidatedByLoop(LI.getOperand(0))) {
280 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
281 /// stores out of the loop and moving loads to before the loop. We do this by
282 /// looping over the stores in the loop, looking for stores to Must pointers
283 /// which are loop invariant. We promote these memory locations to use allocas
284 /// instead. These allocas can easily be raised to register values by the
285 /// PromoteMem2Reg functionality.
287 void LICM::PromoteValuesInLoop() {
288 // PromotedValues - List of values that are promoted out of the loop. Each
289 // value has an alloca instruction for it, and a cannonical version of the
291 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
292 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
294 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
295 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
298 NumPromoted += PromotedValues.size();
300 // Emit a copy from the value into the alloca'd value in the loop preheader
301 TerminatorInst *LoopPredInst = Preheader->getTerminator();
302 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
303 // Load from the memory we are promoting...
304 LoadInst *LI = new LoadInst(PromotedValues[i].second,
305 PromotedValues[i].second->getName()+".promoted",
307 // Store into the temporary alloca...
308 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
311 // Scan the basic blocks in the loop, replacing uses of our pointers with
312 // uses of the allocas in question. If we find a branch that exits the
313 // loop, make sure to put reload code into all of the successors of the
316 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
317 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
318 E = LoopBBs.end(); I != E; ++I) {
319 // Rewrite all loads and stores in the block of the pointer...
320 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
322 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
323 std::map<Value*, AllocaInst*>::iterator
324 I = ValueToAllocaMap.find(L->getOperand(0));
325 if (I != ValueToAllocaMap.end())
326 L->setOperand(0, I->second); // Rewrite load instruction...
327 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
328 std::map<Value*, AllocaInst*>::iterator
329 I = ValueToAllocaMap.find(S->getOperand(1));
330 if (I != ValueToAllocaMap.end())
331 S->setOperand(1, I->second); // Rewrite store instruction...
335 // Check to see if any successors of this block are outside of the loop.
336 // If so, we need to copy the value from the alloca back into the memory
339 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
340 if (!CurLoop->contains(*SI)) {
341 // Copy all of the allocas into their memory locations...
342 BasicBlock::iterator BI = (*SI)->begin();
343 while (isa<PHINode>(*BI))
344 ++BI; // Skip over all of the phi nodes in the block...
345 Instruction *InsertPos = BI;
346 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
347 // Load from the alloca...
348 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
349 // Store into the memory we promoted...
350 new StoreInst(LI, PromotedValues[i].second, InsertPos);
355 // Now that we have done the deed, use the mem2reg functionality to promote
356 // all of the new allocas we just created into real SSA registers...
358 std::vector<AllocaInst*> PromotedAllocas;
359 PromotedAllocas.reserve(PromotedValues.size());
360 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
361 PromotedAllocas.push_back(PromotedValues[i].first);
362 PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>(),
363 AA->getTargetData());
366 /// findPromotableValuesInLoop - Check the current loop for stores to definate
367 /// pointers, which are not loaded and stored through may aliases. If these are
368 /// found, create an alloca for the value, add it to the PromotedValues list,
369 /// and keep track of the mapping from value to alloca...
371 void LICM::findPromotableValuesInLoop(
372 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
373 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
374 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
376 // Loop over all of the alias sets in the tracker object...
377 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
380 // We can promote this alias set if it has a store, if it is a "Must" alias
381 // set, and if the pointer is loop invariant.
382 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
383 isLoopInvariant(AS.begin()->first)) {
384 assert(AS.begin() != AS.end() &&
385 "Must alias set should have at least one pointer element in it!");
386 Value *V = AS.begin()->first;
388 // Check that all of the pointers in the alias set have the same type. We
389 // cannot (yet) promote a memory location that is loaded and stored in
391 bool PointerOk = true;
392 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
393 if (V->getType() != I->first->getType()) {
399 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
400 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
401 PromotedValues.push_back(std::make_pair(AI, V));
403 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
404 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
406 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");