blob: 27b0f2e89f9428187c7ed47b1f6cd5c660d927ce [file] [log] [blame]
Chris Lattnere0e734e2002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere0e734e2002-05-10 22:44:58 +00009//
Chris Lattner92094b42003-12-09 17:18:00 +000010// This pass performs loop invariant code motion, attempting to remove as much
11// code from the body of a loop as possible. It does this by either hoisting
12// code into the preheader block, or by sinking code to the exit blocks if it is
13// safe. This pass also promotes must-aliased memory locations in the loop to
Chris Lattnere4365b22003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattner92094b42003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner2e6e7412003-02-24 03:52:32 +000017//
Chris Lattner2741c972004-05-23 21:20:19 +000018// 1. Moving loop invariant loads and calls out of loops. If we can determine
19// that a load or call inside of a loop never aliases anything stored to,
20// we can hoist it or sink it like any other instruction.
Chris Lattner2e6e7412003-02-24 03:52:32 +000021// 2. Scalar Promotion of Memory - If there is a store instruction inside of
22// the loop, we try to move the store to happen AFTER the loop instead of
23// inside of the loop. This can only happen if a few conditions are true:
24// A. The pointer stored through is loop invariant
25// B. There are no stores or loads in the loop which _may_ alias the
26// pointer. There are no calls in the loop which mod/ref the pointer.
27// If these conditions are true, we can promote the loads and stores in the
28// loop of the pointer to use a temporary alloca'd variable. We then use
29// the mem2reg functionality to construct the appropriate SSA form for the
30// variable.
Chris Lattnere0e734e2002-05-10 22:44:58 +000031//
Chris Lattnere0e734e2002-05-10 22:44:58 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1f309c12005-03-23 21:00:12 +000034#define DEBUG_TYPE "licm"
Chris Lattnere0e734e2002-05-10 22:44:58 +000035#include "llvm/Transforms/Scalar.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Constants.h"
Chris Lattner2741c972004-05-23 21:20:19 +000037#include "llvm/DerivedTypes.h"
38#include "llvm/Instructions.h"
39#include "llvm/Target/TargetData.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000040#include "llvm/Analysis/LoopInfo.h"
Devang Patel54959d62007-03-07 04:41:30 +000041#include "llvm/Analysis/LoopPass.h"
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000042#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0252e492003-03-03 23:32:45 +000043#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner952eaee2002-09-29 21:46:09 +000044#include "llvm/Analysis/Dominators.h"
Chris Lattner2741c972004-05-23 21:20:19 +000045#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000046#include "llvm/Support/CFG.h"
47#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000048#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/ADT/Statistic.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000051#include <algorithm>
Chris Lattner92094b42003-12-09 17:18:00 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Chris Lattner0e5f4992006-12-19 21:40:18 +000054STATISTIC(NumSunk , "Number of instructions sunk out of loop");
55STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
56STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
57STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
58STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
59
Chris Lattnere0e734e2002-05-10 22:44:58 +000060namespace {
Chris Lattner4a650af2003-10-13 05:04:27 +000061 cl::opt<bool>
62 DisablePromotion("disable-licm-promotion", cl::Hidden,
63 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner2e6e7412003-02-24 03:52:32 +000064
Devang Patel54959d62007-03-07 04:41:30 +000065 struct VISIBILITY_HIDDEN LICM : public LoopPass {
Devang Patel19974732007-05-03 01:11:54 +000066 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000067 LICM() : LoopPass((intptr_t)&ID) {}
68
Devang Patel54959d62007-03-07 04:41:30 +000069 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnere0e734e2002-05-10 22:44:58 +000070
Chris Lattner94170592002-09-26 16:52:07 +000071 /// This transformation requires natural loop information & requires that
72 /// loop preheaders be inserted into the CFG...
73 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +000074 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000075 AU.setPreservesCFG();
Chris Lattner98bf4362003-10-12 21:52:28 +000076 AU.addRequiredID(LoopSimplifyID);
Chris Lattner5f0eb8d2002-08-08 19:01:30 +000077 AU.addRequired<LoopInfo>();
Owen Anderson3a2b58f2007-04-24 06:40:39 +000078 AU.addRequired<DominatorTree>();
Owen Anderson325171e2007-04-18 05:43:13 +000079 AU.addRequired<ETForest>();
Chris Lattner0252e492003-03-03 23:32:45 +000080 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000081 AU.addRequired<AliasAnalysis>();
Chris Lattnere0e734e2002-05-10 22:44:58 +000082 }
83
Dan Gohman747603e2007-04-17 18:21:36 +000084 bool doFinalization() {
Devang Patel54959d62007-03-07 04:41:30 +000085 LoopToAliasMap.clear();
86 return false;
87 }
88
Chris Lattnere0e734e2002-05-10 22:44:58 +000089 private:
Chris Lattner92094b42003-12-09 17:18:00 +000090 // Various analyses that we use...
Chris Lattner2e6e7412003-02-24 03:52:32 +000091 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattner92094b42003-12-09 17:18:00 +000092 LoopInfo *LI; // Current LoopInfo
Owen Anderson3a2b58f2007-04-24 06:40:39 +000093 ETForest *ET; // ETForest for the current loop..
94 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattner43f820d2003-10-05 21:20:13 +000095 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattner92094b42003-12-09 17:18:00 +000096
97 // State that is updated as we process loops
Chris Lattner2e6e7412003-02-24 03:52:32 +000098 bool Changed; // Set to true when we change anything.
99 BasicBlock *Preheader; // The preheader block of the current loop...
100 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0252e492003-03-03 23:32:45 +0000101 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel54959d62007-03-07 04:41:30 +0000102 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000103
Chris Lattnere4365b22003-12-19 07:22:45 +0000104 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
105 /// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000106 /// reverse depth first order w.r.t the DominatorTree. This allows us to
Chris Lattnere4365b22003-12-19 07:22:45 +0000107 /// visit uses before definitions, allowing us to sink a loop body in one
108 /// pass without iteration.
109 ///
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000110 void SinkRegion(DominatorTree::Node *N);
Chris Lattnere4365b22003-12-19 07:22:45 +0000111
Chris Lattner952eaee2002-09-29 21:46:09 +0000112 /// HoistRegion - Walk the specified region of the CFG (defined by all
113 /// blocks dominated by the specified block, and that are in the current
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000114 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000115 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner952eaee2002-09-29 21:46:09 +0000116 /// pass without iteration.
117 ///
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000118 void HoistRegion(DominatorTree::Node *N);
Chris Lattner952eaee2002-09-29 21:46:09 +0000119
Chris Lattnerb4613732002-09-29 22:26:07 +0000120 /// inSubLoop - Little predicate that returns true if the specified basic
121 /// block is in a subloop of the current one, not the current one itself.
Chris Lattner94170592002-09-26 16:52:07 +0000122 ///
Chris Lattnerb4613732002-09-29 22:26:07 +0000123 bool inSubLoop(BasicBlock *BB) {
124 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner329c1c62004-01-08 00:09:44 +0000125 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
126 if ((*I)->contains(BB))
Chris Lattnerb4613732002-09-29 22:26:07 +0000127 return true; // A subloop actually contains this block!
128 return false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000129 }
130
Chris Lattnera2706512003-12-10 06:41:05 +0000131 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
132 /// specified exit block of the loop is dominated by the specified block
133 /// that is in the body of the loop. We use these constraints to
134 /// dramatically limit the amount of the dominator tree that needs to be
135 /// searched.
136 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
137 BasicBlock *BlockInLoop) const {
138 // If the block in the loop is the loop header, it must be dominated!
139 BasicBlock *LoopHeader = CurLoop->getHeader();
140 if (BlockInLoop == LoopHeader)
141 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000142
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000143 DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
144 DominatorTree::Node *IDom = DT->getNode(ExitBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000145
Chris Lattnera2706512003-12-10 06:41:05 +0000146 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner2741c972004-05-23 21:20:19 +0000147 // least_ its immediate dominator.
Chris Lattnera2706512003-12-10 06:41:05 +0000148 do {
149 // Get next Immediate Dominator.
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000150 IDom = IDom->getIDom();
Misha Brukmanfd939082005-04-21 23:48:37 +0000151
Chris Lattnera2706512003-12-10 06:41:05 +0000152 // If we have got to the header of the loop, then the instructions block
153 // did not dominate the exit node, so we can't hoist it.
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000154 if (IDom->getBlock() == LoopHeader)
Chris Lattnera2706512003-12-10 06:41:05 +0000155 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000156
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000157 } while (IDom != BlockInLoopNode);
Chris Lattnera2706512003-12-10 06:41:05 +0000158
159 return true;
160 }
161
162 /// sink - When an instruction is found to only be used outside of the loop,
163 /// this function moves it to the exit blocks and patches up SSA form as
164 /// needed.
165 ///
166 void sink(Instruction &I);
167
Chris Lattner94170592002-09-26 16:52:07 +0000168 /// hoist - When an instruction is found to only use loop invariant operands
169 /// that is safe to hoist, this instruction is called to do the dirty work.
170 ///
Chris Lattner7e708292002-06-25 16:13:24 +0000171 void hoist(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000172
Chris Lattnera2706512003-12-10 06:41:05 +0000173 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
174 /// is not a trapping instruction or if it is a trapping instruction and is
175 /// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000176 ///
Chris Lattnera2706512003-12-10 06:41:05 +0000177 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner9966c032003-08-05 18:45:46 +0000178
Chris Lattner94170592002-09-26 16:52:07 +0000179 /// pointerInvalidatedByLoop - Return true if the body of this loop may
180 /// store into the memory location pointed to by V.
Misha Brukmanfd939082005-04-21 23:48:37 +0000181 ///
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000182 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0252e492003-03-03 23:32:45 +0000183 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000184 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000185 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000186
Chris Lattnera2706512003-12-10 06:41:05 +0000187 bool canSinkOrHoistInst(Instruction &I);
188 bool isLoopInvariantInst(Instruction &I);
189 bool isNotUsedInLoop(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000190
Chris Lattner2e6e7412003-02-24 03:52:32 +0000191 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
192 /// to scalars as we can.
193 ///
194 void PromoteValuesInLoop();
195
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000196 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman352361b2003-09-11 15:32:37 +0000197 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000198 /// If these are found, create an alloca for the value, add it to the
199 /// PromotedValues list, and keep track of the mapping from value to
200 /// alloca...
201 ///
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000202 void FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000203 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
204 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000205 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000206
Devang Patel19974732007-05-03 01:11:54 +0000207 char LICM::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000208 RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattnere0e734e2002-05-10 22:44:58 +0000209}
210
Devang Patel54959d62007-03-07 04:41:30 +0000211LoopPass *llvm::createLICMPass() { return new LICM(); }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000212
Devang Patel54959d62007-03-07 04:41:30 +0000213/// Hoist expressions out of the specified loop...
Chris Lattner94170592002-09-26 16:52:07 +0000214///
Devang Patel54959d62007-03-07 04:41:30 +0000215bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000216 Changed = false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000217
Chris Lattner2e6e7412003-02-24 03:52:32 +0000218 // Get our Loop and Alias Analysis information...
219 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000220 AA = &getAnalysis<AliasAnalysis>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000221 DF = &getAnalysis<DominanceFrontier>();
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000222 DT = &getAnalysis<DominatorTree>();
Owen Anderson325171e2007-04-18 05:43:13 +0000223 ET = &getAnalysis<ETForest>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000224
Devang Patel54959d62007-03-07 04:41:30 +0000225 CurAST = new AliasSetTracker(*AA);
226 // Collect Alias info frmo subloops
227 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
228 LoopItr != LoopItrE; ++LoopItr) {
229 Loop *InnerL = *LoopItr;
230 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
231 assert (InnerAST && "Where is my AST?");
232
233 // What if InnerLoop was modified by other passes ?
234 CurAST->add(*InnerAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000235 }
Devang Patel54959d62007-03-07 04:41:30 +0000236
Chris Lattnere0e734e2002-05-10 22:44:58 +0000237 CurLoop = L;
238
Chris Lattner99a57212002-09-26 19:40:25 +0000239 // Get the preheader block to move instructions into...
240 Preheader = L->getLoopPreheader();
241 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
242
Chris Lattner2e6e7412003-02-24 03:52:32 +0000243 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0252e492003-03-03 23:32:45 +0000244 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner2e6e7412003-02-24 03:52:32 +0000245 // subloops.
246 //
Chris Lattnera2706512003-12-10 06:41:05 +0000247 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
248 E = L->getBlocks().end(); I != E; ++I)
Chris Lattner2e6e7412003-02-24 03:52:32 +0000249 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
Chris Lattnere34e9a22007-04-14 23:32:02 +0000250 CurAST->add(**I); // Incorporate the specified basic block
Chris Lattner2e6e7412003-02-24 03:52:32 +0000251
Chris Lattnere0e734e2002-05-10 22:44:58 +0000252 // We want to visit all of the instructions in this loop... that are not parts
253 // of our subloops (they have already had their invariants hoisted out of
254 // their loop, into this loop, so there is no need to process the BODIES of
255 // the subloops).
256 //
Chris Lattner952eaee2002-09-29 21:46:09 +0000257 // Traverse the body of the loop in depth first order on the dominator tree so
258 // that we are guaranteed to see definitions before we see uses. This allows
Chris Lattnere4365b22003-12-19 07:22:45 +0000259 // us to sink instructions in one pass, without iteration. AFter sinking
260 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner952eaee2002-09-29 21:46:09 +0000261 //
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000262 SinkRegion(DT->getNode(L->getHeader()));
263 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattnere0e734e2002-05-10 22:44:58 +0000264
Chris Lattner2e6e7412003-02-24 03:52:32 +0000265 // Now that all loop invariants have been removed from the loop, promote any
266 // memory references to scalars that we can...
267 if (!DisablePromotion)
268 PromoteValuesInLoop();
269
Chris Lattnere0e734e2002-05-10 22:44:58 +0000270 // Clear out loops state information for the next iteration
271 CurLoop = 0;
Chris Lattner99a57212002-09-26 19:40:25 +0000272 Preheader = 0;
Devang Patel54959d62007-03-07 04:41:30 +0000273
274 LoopToAliasMap[L] = CurAST;
275 return Changed;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000276}
277
Chris Lattnere4365b22003-12-19 07:22:45 +0000278/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
279/// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000280/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
Chris Lattnere4365b22003-12-19 07:22:45 +0000281/// uses before definitions, allowing us to sink a loop body in one pass without
282/// iteration.
283///
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000284void LICM::SinkRegion(DominatorTree::Node *N) {
285 assert(N != 0 && "Null dominator tree node?");
286 BasicBlock *BB = N->getBlock();
Chris Lattnere4365b22003-12-19 07:22:45 +0000287
288 // If this subregion is not in the top level loop at all, exit.
289 if (!CurLoop->contains(BB)) return;
290
291 // We are processing blocks in reverse dfo, so process children first...
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000292 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
Chris Lattnere4365b22003-12-19 07:22:45 +0000293 for (unsigned i = 0, e = Children.size(); i != e; ++i)
294 SinkRegion(Children[i]);
295
296 // Only need to process the contents of this block if it is not part of a
297 // subloop (which would already have been processed).
298 if (inSubLoop(BB)) return;
299
Chris Lattnera3df8a92003-12-19 08:18:16 +0000300 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
301 Instruction &I = *--II;
Misha Brukmanfd939082005-04-21 23:48:37 +0000302
Chris Lattnere4365b22003-12-19 07:22:45 +0000303 // Check to see if we can sink this instruction to the exit blocks
304 // of the loop. We can do this if the all users of the instruction are
305 // outside of the loop. In this case, it doesn't even matter if the
306 // operands of the instruction are loop invariant.
307 //
Chris Lattner70ac2dc2005-03-25 00:22:36 +0000308 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattnera3df8a92003-12-19 08:18:16 +0000309 ++II;
Chris Lattnere4365b22003-12-19 07:22:45 +0000310 sink(I);
Chris Lattnera3df8a92003-12-19 08:18:16 +0000311 }
Chris Lattnere4365b22003-12-19 07:22:45 +0000312 }
313}
314
315
Chris Lattner952eaee2002-09-29 21:46:09 +0000316/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
317/// dominated by the specified block, and that are in the current loop) in depth
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000318/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner952eaee2002-09-29 21:46:09 +0000319/// before uses, allowing us to hoist a loop body in one pass without iteration.
320///
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000321void LICM::HoistRegion(DominatorTree::Node *N) {
322 assert(N != 0 && "Null dominator tree node?");
323 BasicBlock *BB = N->getBlock();
Chris Lattner952eaee2002-09-29 21:46:09 +0000324
Chris Lattnerb4613732002-09-29 22:26:07 +0000325 // If this subregion is not in the top level loop at all, exit.
Chris Lattnered6dfc22003-12-09 19:32:44 +0000326 if (!CurLoop->contains(BB)) return;
Chris Lattner952eaee2002-09-29 21:46:09 +0000327
Chris Lattnera2706512003-12-10 06:41:05 +0000328 // Only need to process the contents of this block if it is not part of a
329 // subloop (which would already have been processed).
Chris Lattnered6dfc22003-12-09 19:32:44 +0000330 if (!inSubLoop(BB))
Chris Lattnera2706512003-12-10 06:41:05 +0000331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
332 Instruction &I = *II++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000333
Chris Lattnere4365b22003-12-19 07:22:45 +0000334 // Try hoisting the instruction out to the preheader. We can only do this
335 // if all of the operands of the instruction are loop invariant and if it
336 // is safe to hoist the instruction.
337 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000338 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattnere4365b22003-12-19 07:22:45 +0000339 isSafeToExecuteUnconditionally(I))
Chris Lattner3c80a512006-06-26 19:10:05 +0000340 hoist(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000341 }
Chris Lattner952eaee2002-09-29 21:46:09 +0000342
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000343 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
Chris Lattner952eaee2002-09-29 21:46:09 +0000344 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner56b7ee22004-06-19 20:23:35 +0000345 HoistRegion(Children[i]);
Chris Lattner952eaee2002-09-29 21:46:09 +0000346}
347
Chris Lattnera2706512003-12-10 06:41:05 +0000348/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
349/// instruction.
350///
351bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattnered6dfc22003-12-09 19:32:44 +0000352 // Loads have extra constraints we have to verify before we can hoist them.
353 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
354 if (LI->isVolatile())
355 return false; // Don't hoist volatile loads!
356
357 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000358 unsigned Size = 0;
359 if (LI->getType()->isSized())
360 Size = AA->getTargetData().getTypeSize(LI->getType());
361 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner118dd0c2004-03-15 04:11:30 +0000362 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
363 // Handle obvious cases efficiently.
364 if (Function *Callee = CI->getCalledFunction()) {
Chris Lattner68a9d3e2004-12-15 07:22:25 +0000365 AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
366 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
Chris Lattner118dd0c2004-03-15 04:11:30 +0000367 return true;
Chris Lattner68a9d3e2004-12-15 07:22:25 +0000368 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
Chris Lattner118dd0c2004-03-15 04:11:30 +0000369 // If this call only reads from memory and there are no writes to memory
370 // in the loop, we can hoist or sink the call as appropriate.
371 bool FoundMod = false;
372 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
373 I != E; ++I) {
374 AliasSet &AS = *I;
375 if (!AS.isForwardingAliasSet() && AS.isMod()) {
376 FoundMod = true;
377 break;
378 }
379 }
380 if (!FoundMod) return true;
381 }
382 }
383
384 // FIXME: This should use mod/ref information to see if we can hoist or sink
385 // the call.
Misha Brukmanfd939082005-04-21 23:48:37 +0000386
Chris Lattner118dd0c2004-03-15 04:11:30 +0000387 return false;
Chris Lattnered6dfc22003-12-09 19:32:44 +0000388 }
389
Reid Spencer3da59db2006-11-27 01:05:10 +0000390 // Otherwise these instructions are hoistable/sinkable
Reid Spencer832254e2007-02-02 02:16:23 +0000391 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +0000392 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000393}
394
395/// isNotUsedInLoop - Return true if the only users of this instruction are
396/// outside of the loop. If this is true, we can sink the instruction to the
397/// exit blocks of the loop.
398///
399bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattnerea9403f2003-12-11 22:23:32 +0000400 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
401 Instruction *User = cast<Instruction>(*UI);
402 if (PHINode *PN = dyn_cast<PHINode>(User)) {
403 // PHI node uses occur in predecessor blocks!
404 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
405 if (PN->getIncomingValue(i) == &I)
406 if (CurLoop->contains(PN->getIncomingBlock(i)))
407 return false;
408 } else if (CurLoop->contains(User->getParent())) {
Chris Lattnera2706512003-12-10 06:41:05 +0000409 return false;
Chris Lattnerea9403f2003-12-11 22:23:32 +0000410 }
411 }
Chris Lattnera2706512003-12-10 06:41:05 +0000412 return true;
413}
414
415
416/// isLoopInvariantInst - Return true if all operands of this instruction are
417/// loop invariant. We also filter out non-hoistable instructions here just for
418/// efficiency.
419///
420bool LICM::isLoopInvariantInst(Instruction &I) {
421 // The instruction is loop invariant if all of its operands are loop-invariant
422 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3280f7b2004-04-18 22:46:08 +0000423 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattnera2706512003-12-10 06:41:05 +0000424 return false;
425
Chris Lattnered6dfc22003-12-09 19:32:44 +0000426 // If we got this far, the instruction is loop invariant!
427 return true;
428}
429
Chris Lattnera2706512003-12-10 06:41:05 +0000430/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattnera3df8a92003-12-19 08:18:16 +0000431/// this function moves it to the exit blocks and patches up SSA form as needed.
432/// This method is guaranteed to remove the original instruction from its
433/// position, and may either delete it or move it to outside of the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000434///
435void LICM::sink(Instruction &I) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000436 DOUT << "LICM sinking instruction: " << I;
Chris Lattnera2706512003-12-10 06:41:05 +0000437
Chris Lattner5fa802f2004-04-18 22:15:13 +0000438 std::vector<BasicBlock*> ExitBlocks;
439 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000440
441 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000442 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000443 ++NumSunk;
444 Changed = true;
445
Chris Lattnera2706512003-12-10 06:41:05 +0000446 // The case where there is only a single exit node of this loop is common
447 // enough that we handle it as a special (more efficient) case. It is more
448 // efficient to handle because there are no PHI nodes that need to be placed.
449 if (ExitBlocks.size() == 1) {
450 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
451 // Instruction is not used, just delete it.
Chris Lattner2741c972004-05-23 21:20:19 +0000452 CurAST->deleteValue(&I);
Chris Lattner92f73652006-09-12 19:17:09 +0000453 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
454 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000455 I.eraseFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000456 } else {
457 // Move the instruction to the start of the exit block, after any PHI
458 // nodes in it.
Chris Lattner3c80a512006-06-26 19:10:05 +0000459 I.removeFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000460
Chris Lattnera2706512003-12-10 06:41:05 +0000461 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
462 while (isa<PHINode>(InsertPt)) ++InsertPt;
463 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
464 }
465 } else if (ExitBlocks.size() == 0) {
466 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner2741c972004-05-23 21:20:19 +0000467 CurAST->deleteValue(&I);
Chris Lattner92f73652006-09-12 19:17:09 +0000468 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
469 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000470 I.eraseFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000471 } else {
472 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
473 // do all of the hard work of inserting PHI nodes as necessary. We convert
474 // the value into a stack object to get it to do this.
475
476 // Firstly, we create a stack object to hold the value...
Chris Lattnereaa24302004-07-27 07:38:32 +0000477 AllocaInst *AI = 0;
Chris Lattnera2706512003-12-10 06:41:05 +0000478
Chris Lattnereaa24302004-07-27 07:38:32 +0000479 if (I.getType() != Type::VoidTy)
480 AI = new AllocaInst(I.getType(), 0, I.getName(),
Dan Gohmanecb7a772007-03-22 16:38:57 +0000481 I.getParent()->getParent()->getEntryBlock().begin());
Misha Brukmanfd939082005-04-21 23:48:37 +0000482
Chris Lattnera2706512003-12-10 06:41:05 +0000483 // Secondly, insert load instructions for each use of the instruction
484 // outside of the loop.
485 while (!I.use_empty()) {
486 Instruction *U = cast<Instruction>(I.use_back());
487
488 // If the user is a PHI Node, we actually have to insert load instructions
489 // in all predecessor blocks, not in the PHI block itself!
490 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
491 // Only insert into each predecessor once, so that we don't have
492 // different incoming values from the same block!
493 std::map<BasicBlock*, Value*> InsertedBlocks;
494 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
495 if (UPN->getIncomingValue(i) == &I) {
496 BasicBlock *Pred = UPN->getIncomingBlock(i);
497 Value *&PredVal = InsertedBlocks[Pred];
498 if (!PredVal) {
499 // Insert a new load instruction right before the terminator in
500 // the predecessor block.
501 PredVal = new LoadInst(AI, "", Pred->getTerminator());
502 }
503
504 UPN->setIncomingValue(i, PredVal);
505 }
506
507 } else {
508 LoadInst *L = new LoadInst(AI, "", U);
509 U->replaceUsesOfWith(&I, L);
510 }
511 }
512
513 // Thirdly, insert a copy of the instruction in each exit block of the loop
514 // that is dominated by the instruction, storing the result into the memory
515 // location. Be careful not to insert the instruction into any particular
516 // basic block more than once.
517 std::set<BasicBlock*> InsertedBlocks;
518 BasicBlock *InstOrigBB = I.getParent();
519
520 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
521 BasicBlock *ExitBlock = ExitBlocks[i];
522
523 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattnera2706512003-12-10 06:41:05 +0000524 // If we haven't already processed this exit block, do so now.
Chris Lattnere3cfe8d2003-12-10 16:58:24 +0000525 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattnera2706512003-12-10 06:41:05 +0000526 // Insert the code after the last PHI node...
527 BasicBlock::iterator InsertPt = ExitBlock->begin();
528 while (isa<PHINode>(InsertPt)) ++InsertPt;
Misha Brukmanfd939082005-04-21 23:48:37 +0000529
Chris Lattnera2706512003-12-10 06:41:05 +0000530 // If this is the first exit block processed, just move the original
531 // instruction, otherwise clone the original instruction and insert
532 // the copy.
533 Instruction *New;
Chris Lattner7d3ced92003-12-10 22:35:56 +0000534 if (InsertedBlocks.size() == 1) {
Chris Lattner3c80a512006-06-26 19:10:05 +0000535 I.removeFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000536 ExitBlock->getInstList().insert(InsertPt, &I);
537 New = &I;
538 } else {
539 New = I.clone();
Chris Lattner70ac2dc2005-03-25 00:22:36 +0000540 CurAST->copyValue(&I, New);
Chris Lattnereaa24302004-07-27 07:38:32 +0000541 if (!I.getName().empty())
542 New->setName(I.getName()+".le");
Chris Lattnera2706512003-12-10 06:41:05 +0000543 ExitBlock->getInstList().insert(InsertPt, New);
544 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000545
Chris Lattnera2706512003-12-10 06:41:05 +0000546 // Now that we have inserted the instruction, store it into the alloca
Chris Lattnereaa24302004-07-27 07:38:32 +0000547 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattnera2706512003-12-10 06:41:05 +0000548 }
549 }
550 }
Chris Lattnera3df8a92003-12-19 08:18:16 +0000551
552 // If the instruction doesn't dominate any exit blocks, it must be dead.
553 if (InsertedBlocks.empty()) {
Chris Lattner2741c972004-05-23 21:20:19 +0000554 CurAST->deleteValue(&I);
Chris Lattner3c80a512006-06-26 19:10:05 +0000555 I.eraseFromParent();
Chris Lattnera3df8a92003-12-19 08:18:16 +0000556 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000557
Chris Lattnera2706512003-12-10 06:41:05 +0000558 // Finally, promote the fine value to SSA form.
Chris Lattnereaa24302004-07-27 07:38:32 +0000559 if (AI) {
560 std::vector<AllocaInst*> Allocas;
561 Allocas.push_back(AI);
Devang Patel68c01b32007-04-25 18:32:35 +0000562 PromoteMemToReg(Allocas, *ET, *DF, CurAST);
Chris Lattnereaa24302004-07-27 07:38:32 +0000563 }
Chris Lattnera2706512003-12-10 06:41:05 +0000564 }
Chris Lattnera2706512003-12-10 06:41:05 +0000565}
Chris Lattner952eaee2002-09-29 21:46:09 +0000566
Chris Lattner94170592002-09-26 16:52:07 +0000567/// hoist - When an instruction is found to only use loop invariant operands
568/// that is safe to hoist, this instruction is called to do the dirty work.
569///
Chris Lattnera2706512003-12-10 06:41:05 +0000570void LICM::hoist(Instruction &I) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000571 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
Chris Lattnered6dfc22003-12-09 19:32:44 +0000572
Chris Lattner99a57212002-09-26 19:40:25 +0000573 // Remove the instruction from its current basic block... but don't delete the
574 // instruction.
Chris Lattner3c80a512006-06-26 19:10:05 +0000575 I.removeFromParent();
Chris Lattnere0e734e2002-05-10 22:44:58 +0000576
Chris Lattner9646e6b2002-09-26 16:38:03 +0000577 // Insert the new node in Preheader, before the terminator.
Chris Lattnera2706512003-12-10 06:41:05 +0000578 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000579
Chris Lattnera2706512003-12-10 06:41:05 +0000580 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000581 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner9646e6b2002-09-26 16:38:03 +0000582 ++NumHoisted;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000583 Changed = true;
584}
585
Chris Lattnera2706512003-12-10 06:41:05 +0000586/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
587/// not a trapping instruction or if it is a trapping instruction and is
588/// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000589///
Chris Lattnera2706512003-12-10 06:41:05 +0000590bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattner92094b42003-12-09 17:18:00 +0000591 // If it is not a trapping instruction, it is always safe to hoist.
592 if (!Inst.isTrapping()) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000593
Chris Lattner92094b42003-12-09 17:18:00 +0000594 // Otherwise we have to check to make sure that the instruction dominates all
595 // of the exit blocks. If it doesn't, then there is a path out of the loop
596 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner9966c032003-08-05 18:45:46 +0000597
Chris Lattner92094b42003-12-09 17:18:00 +0000598 // If the instruction is in the header block for the loop (which is very
599 // common), it is always guaranteed to dominate the exit blocks. Since this
600 // is a common case, and can save some work, check it now.
Chris Lattnera2706512003-12-10 06:41:05 +0000601 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattner92094b42003-12-09 17:18:00 +0000602 return true;
Tanya Lattner9966c032003-08-05 18:45:46 +0000603
Chris Lattner8a919392004-11-29 21:26:12 +0000604 // It's always safe to load from a global or alloca.
605 if (isa<LoadInst>(Inst))
606 if (isa<AllocationInst>(Inst.getOperand(0)) ||
607 isa<GlobalVariable>(Inst.getOperand(0)))
608 return true;
609
Chris Lattner92094b42003-12-09 17:18:00 +0000610 // Get the exit blocks for the current loop.
Chris Lattner5fa802f2004-04-18 22:15:13 +0000611 std::vector<BasicBlock*> ExitBlocks;
612 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner92094b42003-12-09 17:18:00 +0000613
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000614 // For each exit block, get the DT node and walk up the DT until the
Chris Lattner92094b42003-12-09 17:18:00 +0000615 // instruction's basic block is found or we exit the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000616 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
617 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
618 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000619
Tanya Lattner9966c032003-08-05 18:45:46 +0000620 return true;
621}
622
Chris Lattnereb53ae42002-09-26 16:19:31 +0000623
Chris Lattner2e6e7412003-02-24 03:52:32 +0000624/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
625/// stores out of the loop and moving loads to before the loop. We do this by
626/// looping over the stores in the loop, looking for stores to Must pointers
627/// which are loop invariant. We promote these memory locations to use allocas
628/// instead. These allocas can easily be raised to register values by the
629/// PromoteMem2Reg functionality.
630///
631void LICM::PromoteValuesInLoop() {
632 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner065a6162003-09-10 05:29:43 +0000633 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner2e6e7412003-02-24 03:52:32 +0000634 // pointer.
635 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
636 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
637
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000638 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
639 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000640
641 Changed = true;
642 NumPromoted += PromotedValues.size();
643
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000644 std::vector<Value*> PointerValueNumbers;
645
Chris Lattner2e6e7412003-02-24 03:52:32 +0000646 // Emit a copy from the value into the alloca'd value in the loop preheader
647 TerminatorInst *LoopPredInst = Preheader->getTerminator();
648 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000649 Value *Ptr = PromotedValues[i].second;
650
651 // If we are promoting a pointer value, update alias information for the
652 // inserted load.
653 Value *LoadValue = 0;
654 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
655 // Locate a load or store through the pointer, and assign the same value
656 // to LI as we are loading or storing. Since we know that the value is
657 // stored in this loop, this will always succeed.
658 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
659 UI != E; ++UI)
660 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
661 LoadValue = LI;
662 break;
663 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerbdacd872004-09-15 02:34:40 +0000664 if (SI->getOperand(1) == Ptr) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000665 LoadValue = SI->getOperand(0);
666 break;
667 }
668 }
669 assert(LoadValue && "No store through the pointer found!");
670 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
671 }
672
673 // Load from the memory we are promoting.
674 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
675
676 if (LoadValue) CurAST->copyValue(LoadValue, LI);
677
678 // Store into the temporary alloca.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000679 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
680 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000681
Chris Lattner2e6e7412003-02-24 03:52:32 +0000682 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattner0ed2da92003-12-10 15:56:24 +0000683 // uses of the allocas in question.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000684 //
685 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
686 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
687 E = LoopBBs.end(); I != E; ++I) {
688 // Rewrite all loads and stores in the block of the pointer...
689 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
690 II != E; ++II) {
Chris Lattnere408e252003-04-23 16:37:45 +0000691 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000692 std::map<Value*, AllocaInst*>::iterator
693 I = ValueToAllocaMap.find(L->getOperand(0));
694 if (I != ValueToAllocaMap.end())
695 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattnere408e252003-04-23 16:37:45 +0000696 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000697 std::map<Value*, AllocaInst*>::iterator
698 I = ValueToAllocaMap.find(S->getOperand(1));
699 if (I != ValueToAllocaMap.end())
700 S->setOperand(1, I->second); // Rewrite store instruction...
701 }
702 }
Chris Lattner2e6e7412003-02-24 03:52:32 +0000703 }
704
Chris Lattner0ed2da92003-12-10 15:56:24 +0000705 // Now that the body of the loop uses the allocas instead of the original
706 // memory locations, insert code to copy the alloca value back into the
707 // original memory location on all exits from the loop. Note that we only
708 // want to insert one copy of the code in each exit block, though the loop may
709 // exit to the same block more than once.
710 //
711 std::set<BasicBlock*> ProcessedBlocks;
712
Chris Lattner5fa802f2004-04-18 22:15:13 +0000713 std::vector<BasicBlock*> ExitBlocks;
714 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner0ed2da92003-12-10 15:56:24 +0000715 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattnerf594a032003-12-10 16:57:24 +0000716 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000717 // Copy all of the allocas into their memory locations.
Chris Lattner0ed2da92003-12-10 15:56:24 +0000718 BasicBlock::iterator BI = ExitBlocks[i]->begin();
719 while (isa<PHINode>(*BI))
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000720 ++BI; // Skip over all of the phi nodes in the block.
Chris Lattner0ed2da92003-12-10 15:56:24 +0000721 Instruction *InsertPos = BI;
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000722 unsigned PVN = 0;
Chris Lattner0ed2da92003-12-10 15:56:24 +0000723 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000724 // Load from the alloca.
Chris Lattner0ed2da92003-12-10 15:56:24 +0000725 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000726
727 // If this is a pointer type, update alias info appropriately.
728 if (isa<PointerType>(LI->getType()))
729 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
730
731 // Store into the memory we promoted.
Chris Lattner0ed2da92003-12-10 15:56:24 +0000732 new StoreInst(LI, PromotedValues[i].second, InsertPos);
733 }
734 }
735
Chris Lattner2e6e7412003-02-24 03:52:32 +0000736 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000737 // all of the new allocas we just created into real SSA registers.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000738 //
739 std::vector<AllocaInst*> PromotedAllocas;
740 PromotedAllocas.reserve(PromotedValues.size());
741 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
742 PromotedAllocas.push_back(PromotedValues[i].first);
Devang Patel68c01b32007-04-25 18:32:35 +0000743 PromoteMemToReg(PromotedAllocas, *ET, *DF, CurAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000744}
745
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000746/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Chris Lattner2e6e7412003-02-24 03:52:32 +0000747/// pointers, which are not loaded and stored through may aliases. If these are
748/// found, create an alloca for the value, add it to the PromotedValues list,
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000749/// and keep track of the mapping from value to alloca.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000750///
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000751void LICM::FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000752 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
753 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
754 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
755
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000756 // Loop over all of the alias sets in the tracker object.
Chris Lattner0252e492003-03-03 23:32:45 +0000757 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
758 I != E; ++I) {
759 AliasSet &AS = *I;
760 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000761 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner118dd0c2004-03-15 04:11:30 +0000762 // volatile loads or stores.
Chris Lattner0252e492003-03-03 23:32:45 +0000763 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
Chris Lattner3280f7b2004-04-18 22:46:08 +0000764 !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
Chris Lattner0252e492003-03-03 23:32:45 +0000765 assert(AS.begin() != AS.end() &&
766 "Must alias set should have at least one pointer element in it!");
767 Value *V = AS.begin()->first;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000768
Chris Lattner0252e492003-03-03 23:32:45 +0000769 // Check that all of the pointers in the alias set have the same type. We
770 // cannot (yet) promote a memory location that is loaded and stored in
771 // different sizes.
772 bool PointerOk = true;
773 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
774 if (V->getType() != I->first->getType()) {
775 PointerOk = false;
776 break;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000777 }
Chris Lattner0252e492003-03-03 23:32:45 +0000778
779 if (PointerOk) {
780 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
781 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
782 PromotedValues.push_back(std::make_pair(AI, V));
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000783
784 // Update the AST and alias analysis.
785 CurAST->copyValue(V, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000786
Chris Lattner0252e492003-03-03 23:32:45 +0000787 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
788 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
Misha Brukmanfd939082005-04-21 23:48:37 +0000789
Bill Wendlingb7427032006-11-26 09:46:52 +0000790 DOUT << "LICM: Promoting value: " << *V << "\n";
Chris Lattner2e6e7412003-02-24 03:52:32 +0000791 }
792 }
793 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000794}