blob: 639e958f04060c64fd98b0d6de581e75f506c353 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Torok Edwin9289ae82009-10-11 19:15:54 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner2741c972004-05-23 21:20:19 +000039#include "llvm/Instructions.h"
40#include "llvm/Target/TargetData.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000041#include "llvm/Analysis/LoopInfo.h"
Devang Patel54959d62007-03-07 04:41:30 +000042#include "llvm/Analysis/LoopPass.h"
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000043#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0252e492003-03-03 23:32:45 +000044#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner952eaee2002-09-29 21:46:09 +000045#include "llvm/Analysis/Dominators.h"
Devang Patel96b651c2007-07-30 20:19:59 +000046#include "llvm/Analysis/ScalarEvolution.h"
Chris Lattner2741c972004-05-23 21:20:19 +000047#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattnera6a36f52010-08-29 04:55:06 +000048#include "llvm/Transforms/Utils/SSAUpdater.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000049#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Support/CommandLine.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000051#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000054#include <algorithm>
Chris Lattner92094b42003-12-09 17:18:00 +000055using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000056
Chris Lattner0e5f4992006-12-19 21:40:18 +000057STATISTIC(NumSunk , "Number of instructions sunk out of loop");
58STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
59STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
60STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
61STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
62
Dan Gohman844731a2008-05-13 00:00:25 +000063static cl::opt<bool>
64DisablePromotion("disable-licm-promotion", cl::Hidden,
65 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner2e6e7412003-02-24 03:52:32 +000066
Dan Gohman844731a2008-05-13 00:00:25 +000067namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000068 struct LICM : public LoopPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000069 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000070 LICM() : LoopPass(ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000071
Devang Patel54959d62007-03-07 04:41:30 +000072 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattnere0e734e2002-05-10 22:44:58 +000073
Chris Lattner94170592002-09-26 16:52:07 +000074 /// This transformation requires natural loop information & requires that
75 /// loop preheaders be inserted into the CFG...
76 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +000077 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000078 AU.setPreservesCFG();
Owen Anderson3a2b58f2007-04-24 06:40:39 +000079 AU.addRequired<DominatorTree>();
Chris Lattner0252e492003-03-03 23:32:45 +000080 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Dan Gohman1e381fc2010-07-16 17:58:45 +000081 AU.addRequired<LoopInfo>();
82 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000083 AU.addRequired<AliasAnalysis>();
Devang Patel96b651c2007-07-30 20:19:59 +000084 AU.addPreserved<ScalarEvolution>();
85 AU.addPreserved<DominanceFrontier>();
Dan Gohman5c89b522009-09-08 15:45:00 +000086 AU.addPreservedID(LoopSimplifyID);
Chris Lattnere0e734e2002-05-10 22:44:58 +000087 }
88
Dan Gohman747603e2007-04-17 18:21:36 +000089 bool doFinalization() {
Anton Korobeynikovfd94dd52007-11-25 23:52:02 +000090 // Free the values stored in the map
91 for (std::map<Loop *, AliasSetTracker *>::iterator
92 I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
93 delete I->second;
94
Devang Patel54959d62007-03-07 04:41:30 +000095 LoopToAliasMap.clear();
96 return false;
97 }
98
Chris Lattnere0e734e2002-05-10 22:44:58 +000099 private:
Chris Lattner92094b42003-12-09 17:18:00 +0000100 // Various analyses that we use...
Chris Lattner2e6e7412003-02-24 03:52:32 +0000101 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattner92094b42003-12-09 17:18:00 +0000102 LoopInfo *LI; // Current LoopInfo
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000103 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattner43f820d2003-10-05 21:20:13 +0000104 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattner92094b42003-12-09 17:18:00 +0000105
106 // State that is updated as we process loops
Chris Lattner2e6e7412003-02-24 03:52:32 +0000107 bool Changed; // Set to true when we change anything.
108 BasicBlock *Preheader; // The preheader block of the current loop...
109 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0252e492003-03-03 23:32:45 +0000110 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel54959d62007-03-07 04:41:30 +0000111 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000112
Devang Patel91d22c82007-07-31 08:01:41 +0000113 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
114 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
115
116 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
117 /// set.
118 void deleteAnalysisValue(Value *V, Loop *L);
119
Chris Lattnere4365b22003-12-19 07:22:45 +0000120 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
121 /// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000122 /// reverse depth first order w.r.t the DominatorTree. This allows us to
Chris Lattnere4365b22003-12-19 07:22:45 +0000123 /// visit uses before definitions, allowing us to sink a loop body in one
124 /// pass without iteration.
125 ///
Devang Patel26042422007-06-04 00:32:22 +0000126 void SinkRegion(DomTreeNode *N);
Chris Lattnere4365b22003-12-19 07:22:45 +0000127
Chris Lattner952eaee2002-09-29 21:46:09 +0000128 /// HoistRegion - Walk the specified region of the CFG (defined by all
129 /// blocks dominated by the specified block, and that are in the current
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000130 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000131 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner952eaee2002-09-29 21:46:09 +0000132 /// pass without iteration.
133 ///
Devang Patel26042422007-06-04 00:32:22 +0000134 void HoistRegion(DomTreeNode *N);
Chris Lattner952eaee2002-09-29 21:46:09 +0000135
Chris Lattnerb4613732002-09-29 22:26:07 +0000136 /// inSubLoop - Little predicate that returns true if the specified basic
137 /// block is in a subloop of the current one, not the current one itself.
Chris Lattner94170592002-09-26 16:52:07 +0000138 ///
Chris Lattnerb4613732002-09-29 22:26:07 +0000139 bool inSubLoop(BasicBlock *BB) {
140 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner329c1c62004-01-08 00:09:44 +0000141 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
142 if ((*I)->contains(BB))
Chris Lattnerb4613732002-09-29 22:26:07 +0000143 return true; // A subloop actually contains this block!
144 return false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000145 }
146
Chris Lattnera2706512003-12-10 06:41:05 +0000147 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
148 /// specified exit block of the loop is dominated by the specified block
149 /// that is in the body of the loop. We use these constraints to
150 /// dramatically limit the amount of the dominator tree that needs to be
151 /// searched.
152 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
153 BasicBlock *BlockInLoop) const {
154 // If the block in the loop is the loop header, it must be dominated!
155 BasicBlock *LoopHeader = CurLoop->getHeader();
156 if (BlockInLoop == LoopHeader)
157 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000158
Devang Patel26042422007-06-04 00:32:22 +0000159 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
160 DomTreeNode *IDom = DT->getNode(ExitBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000161
Chris Lattnera2706512003-12-10 06:41:05 +0000162 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner2741c972004-05-23 21:20:19 +0000163 // least_ its immediate dominator.
Eric Christopher3472ae12009-12-10 00:25:41 +0000164 IDom = IDom->getIDom();
165
166 while (IDom && IDom != BlockInLoopNode) {
Chris Lattnera2706512003-12-10 06:41:05 +0000167 // If we have got to the header of the loop, then the instructions block
168 // did not dominate the exit node, so we can't hoist it.
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000169 if (IDom->getBlock() == LoopHeader)
Chris Lattnera2706512003-12-10 06:41:05 +0000170 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000171
Eric Christopher3472ae12009-12-10 00:25:41 +0000172 // Get next Immediate Dominator.
173 IDom = IDom->getIDom();
174 };
Chris Lattnera2706512003-12-10 06:41:05 +0000175
176 return true;
177 }
178
179 /// sink - When an instruction is found to only be used outside of the loop,
180 /// this function moves it to the exit blocks and patches up SSA form as
181 /// needed.
182 ///
183 void sink(Instruction &I);
184
Chris Lattner94170592002-09-26 16:52:07 +0000185 /// hoist - When an instruction is found to only use loop invariant operands
186 /// that is safe to hoist, this instruction is called to do the dirty work.
187 ///
Chris Lattner7e708292002-06-25 16:13:24 +0000188 void hoist(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000189
Chris Lattnera2706512003-12-10 06:41:05 +0000190 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
191 /// is not a trapping instruction or if it is a trapping instruction and is
192 /// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000193 ///
Chris Lattnera2706512003-12-10 06:41:05 +0000194 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner9966c032003-08-05 18:45:46 +0000195
Chris Lattner94170592002-09-26 16:52:07 +0000196 /// pointerInvalidatedByLoop - Return true if the body of this loop may
197 /// store into the memory location pointed to by V.
Misha Brukmanfd939082005-04-21 23:48:37 +0000198 ///
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000199 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0252e492003-03-03 23:32:45 +0000200 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000201 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000202 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000203
Chris Lattnera2706512003-12-10 06:41:05 +0000204 bool canSinkOrHoistInst(Instruction &I);
205 bool isLoopInvariantInst(Instruction &I);
206 bool isNotUsedInLoop(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000207
Chris Lattner2e6e7412003-02-24 03:52:32 +0000208 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
209 /// to scalars as we can.
210 ///
211 void PromoteValuesInLoop();
212
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000213 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman352361b2003-09-11 15:32:37 +0000214 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000215 /// If these are found, create an alloca for the value, add it to the
216 /// PromotedValues list, and keep track of the mapping from value to
217 /// alloca...
218 ///
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000219 void FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000220 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000221 DenseMap<Value*, AllocaInst*> &Val2AlMap);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000222 };
223}
224
Dan Gohman844731a2008-05-13 00:00:25 +0000225char LICM::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000226INITIALIZE_PASS(LICM, "licm", "Loop Invariant Code Motion", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +0000227
Daniel Dunbar394f0442008-10-22 23:32:42 +0000228Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000229
Devang Patel8d246f02007-07-31 16:52:25 +0000230/// Hoist expressions out of the specified loop. Note, alias info for inner
231/// loop is not preserved so it is not a good idea to run LICM multiple
232/// times on one loop.
Chris Lattner94170592002-09-26 16:52:07 +0000233///
Devang Patel54959d62007-03-07 04:41:30 +0000234bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000235 Changed = false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000236
Chris Lattner2e6e7412003-02-24 03:52:32 +0000237 // Get our Loop and Alias Analysis information...
238 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000239 AA = &getAnalysis<AliasAnalysis>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000240 DF = &getAnalysis<DominanceFrontier>();
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000241 DT = &getAnalysis<DominatorTree>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000242
Devang Patel54959d62007-03-07 04:41:30 +0000243 CurAST = new AliasSetTracker(*AA);
Devang Patelf38ac5d2007-05-30 15:29:37 +0000244 // Collect Alias info from subloops
Devang Patel54959d62007-03-07 04:41:30 +0000245 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
246 LoopItr != LoopItrE; ++LoopItr) {
247 Loop *InnerL = *LoopItr;
248 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
249 assert (InnerAST && "Where is my AST?");
250
251 // What if InnerLoop was modified by other passes ?
252 CurAST->add(*InnerAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000253 }
Devang Patel54959d62007-03-07 04:41:30 +0000254
Chris Lattnere0e734e2002-05-10 22:44:58 +0000255 CurLoop = L;
256
Chris Lattner99a57212002-09-26 19:40:25 +0000257 // Get the preheader block to move instructions into...
258 Preheader = L->getLoopPreheader();
Chris Lattner99a57212002-09-26 19:40:25 +0000259
Chris Lattner2e6e7412003-02-24 03:52:32 +0000260 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0252e492003-03-03 23:32:45 +0000261 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner2e6e7412003-02-24 03:52:32 +0000262 // subloops.
263 //
Dan Gohman9b787632008-06-22 20:18:58 +0000264 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
265 I != E; ++I) {
266 BasicBlock *BB = *I;
267 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops...
268 CurAST->add(*BB); // Incorporate the specified basic block
269 }
Chris Lattner2e6e7412003-02-24 03:52:32 +0000270
Chris Lattnere0e734e2002-05-10 22:44:58 +0000271 // We want to visit all of the instructions in this loop... that are not parts
272 // of our subloops (they have already had their invariants hoisted out of
273 // their loop, into this loop, so there is no need to process the BODIES of
274 // the subloops).
275 //
Chris Lattner952eaee2002-09-29 21:46:09 +0000276 // Traverse the body of the loop in depth first order on the dominator tree so
277 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckyaf5cbc82007-08-18 15:08:56 +0000278 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattnere4365b22003-12-19 07:22:45 +0000279 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner952eaee2002-09-29 21:46:09 +0000280 //
Dan Gohman03e896b2009-11-05 21:11:53 +0000281 if (L->hasDedicatedExits())
282 SinkRegion(DT->getNode(L->getHeader()));
283 if (Preheader)
284 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattnere0e734e2002-05-10 22:44:58 +0000285
Chris Lattner2e6e7412003-02-24 03:52:32 +0000286 // Now that all loop invariants have been removed from the loop, promote any
287 // memory references to scalars that we can...
Dan Gohman03e896b2009-11-05 21:11:53 +0000288 if (!DisablePromotion && Preheader && L->hasDedicatedExits())
Chris Lattner2e6e7412003-02-24 03:52:32 +0000289 PromoteValuesInLoop();
290
Chris Lattnere0e734e2002-05-10 22:44:58 +0000291 // Clear out loops state information for the next iteration
292 CurLoop = 0;
Chris Lattner99a57212002-09-26 19:40:25 +0000293 Preheader = 0;
Devang Patel54959d62007-03-07 04:41:30 +0000294
295 LoopToAliasMap[L] = CurAST;
296 return Changed;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000297}
298
Chris Lattnere4365b22003-12-19 07:22:45 +0000299/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
300/// dominated by the specified block, and that are in the current loop) in
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000301/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
Chris Lattnere4365b22003-12-19 07:22:45 +0000302/// uses before definitions, allowing us to sink a loop body in one pass without
303/// iteration.
304///
Devang Patel26042422007-06-04 00:32:22 +0000305void LICM::SinkRegion(DomTreeNode *N) {
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000306 assert(N != 0 && "Null dominator tree node?");
307 BasicBlock *BB = N->getBlock();
Chris Lattnere4365b22003-12-19 07:22:45 +0000308
309 // If this subregion is not in the top level loop at all, exit.
310 if (!CurLoop->contains(BB)) return;
311
312 // We are processing blocks in reverse dfo, so process children first...
Devang Patel26042422007-06-04 00:32:22 +0000313 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattnere4365b22003-12-19 07:22:45 +0000314 for (unsigned i = 0, e = Children.size(); i != e; ++i)
315 SinkRegion(Children[i]);
316
317 // Only need to process the contents of this block if it is not part of a
318 // subloop (which would already have been processed).
319 if (inSubLoop(BB)) return;
320
Chris Lattnera3df8a92003-12-19 08:18:16 +0000321 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
322 Instruction &I = *--II;
Misha Brukmanfd939082005-04-21 23:48:37 +0000323
Chris Lattnere4365b22003-12-19 07:22:45 +0000324 // Check to see if we can sink this instruction to the exit blocks
325 // of the loop. We can do this if the all users of the instruction are
326 // outside of the loop. In this case, it doesn't even matter if the
327 // operands of the instruction are loop invariant.
328 //
Chris Lattner70ac2dc2005-03-25 00:22:36 +0000329 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattnera3df8a92003-12-19 08:18:16 +0000330 ++II;
Chris Lattnere4365b22003-12-19 07:22:45 +0000331 sink(I);
Chris Lattnera3df8a92003-12-19 08:18:16 +0000332 }
Chris Lattnere4365b22003-12-19 07:22:45 +0000333 }
334}
335
Chris Lattner952eaee2002-09-29 21:46:09 +0000336/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
337/// dominated by the specified block, and that are in the current loop) in depth
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000338/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner952eaee2002-09-29 21:46:09 +0000339/// before uses, allowing us to hoist a loop body in one pass without iteration.
340///
Devang Patel26042422007-06-04 00:32:22 +0000341void LICM::HoistRegion(DomTreeNode *N) {
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000342 assert(N != 0 && "Null dominator tree node?");
343 BasicBlock *BB = N->getBlock();
Chris Lattner952eaee2002-09-29 21:46:09 +0000344
Chris Lattnerb4613732002-09-29 22:26:07 +0000345 // If this subregion is not in the top level loop at all, exit.
Chris Lattnered6dfc22003-12-09 19:32:44 +0000346 if (!CurLoop->contains(BB)) return;
Chris Lattner952eaee2002-09-29 21:46:09 +0000347
Chris Lattnera2706512003-12-10 06:41:05 +0000348 // Only need to process the contents of this block if it is not part of a
349 // subloop (which would already have been processed).
Chris Lattnered6dfc22003-12-09 19:32:44 +0000350 if (!inSubLoop(BB))
Chris Lattnera2706512003-12-10 06:41:05 +0000351 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
352 Instruction &I = *II++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000353
Chris Lattnere4365b22003-12-19 07:22:45 +0000354 // Try hoisting the instruction out to the preheader. We can only do this
355 // if all of the operands of the instruction are loop invariant and if it
356 // is safe to hoist the instruction.
357 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000358 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattnere4365b22003-12-19 07:22:45 +0000359 isSafeToExecuteUnconditionally(I))
Chris Lattner3c80a512006-06-26 19:10:05 +0000360 hoist(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000361 }
Chris Lattner952eaee2002-09-29 21:46:09 +0000362
Devang Patel26042422007-06-04 00:32:22 +0000363 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner952eaee2002-09-29 21:46:09 +0000364 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner56b7ee22004-06-19 20:23:35 +0000365 HoistRegion(Children[i]);
Chris Lattner952eaee2002-09-29 21:46:09 +0000366}
367
Chris Lattnera2706512003-12-10 06:41:05 +0000368/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
369/// instruction.
370///
371bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattnered6dfc22003-12-09 19:32:44 +0000372 // Loads have extra constraints we have to verify before we can hoist them.
373 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
374 if (LI->isVolatile())
375 return false; // Don't hoist volatile loads!
376
Chris Lattner967948b2008-07-23 05:06:28 +0000377 // Loads from constant memory are always safe to move, even if they end up
378 // in the same alias set as something that ends up being modified.
Dan Gohmandab249b2009-11-19 19:00:10 +0000379 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner967948b2008-07-23 05:06:28 +0000380 return true;
381
Chris Lattnered6dfc22003-12-09 19:32:44 +0000382 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000383 unsigned Size = 0;
384 if (LI->getType()->isSized())
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000385 Size = AA->getTypeStoreSize(LI->getType());
Chris Lattnerf3e1d692004-11-26 21:20:09 +0000386 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner118dd0c2004-03-15 04:11:30 +0000387 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
388 // Handle obvious cases efficiently.
Duncan Sandsdff67102007-12-01 07:51:45 +0000389 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
390 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
391 return true;
392 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
393 // If this call only reads from memory and there are no writes to memory
394 // in the loop, we can hoist or sink the call as appropriate.
395 bool FoundMod = false;
396 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
397 I != E; ++I) {
398 AliasSet &AS = *I;
399 if (!AS.isForwardingAliasSet() && AS.isMod()) {
400 FoundMod = true;
401 break;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000402 }
Chris Lattner118dd0c2004-03-15 04:11:30 +0000403 }
Duncan Sandsdff67102007-12-01 07:51:45 +0000404 if (!FoundMod) return true;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000405 }
406
407 // FIXME: This should use mod/ref information to see if we can hoist or sink
408 // the call.
Misha Brukmanfd939082005-04-21 23:48:37 +0000409
Chris Lattner118dd0c2004-03-15 04:11:30 +0000410 return false;
Chris Lattnered6dfc22003-12-09 19:32:44 +0000411 }
412
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 // Otherwise these instructions are hoistable/sinkable
Reid Spencer832254e2007-02-02 02:16:23 +0000414 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Dan Gohmand8af90c2007-06-05 16:05:55 +0000415 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
416 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
417 isa<ShuffleVectorInst>(I);
Chris Lattnera2706512003-12-10 06:41:05 +0000418}
419
420/// isNotUsedInLoop - Return true if the only users of this instruction are
421/// outside of the loop. If this is true, we can sink the instruction to the
422/// exit blocks of the loop.
423///
424bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattnerea9403f2003-12-11 22:23:32 +0000425 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
426 Instruction *User = cast<Instruction>(*UI);
427 if (PHINode *PN = dyn_cast<PHINode>(User)) {
428 // PHI node uses occur in predecessor blocks!
429 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
430 if (PN->getIncomingValue(i) == &I)
431 if (CurLoop->contains(PN->getIncomingBlock(i)))
432 return false;
Dan Gohman92329c72009-12-18 01:24:09 +0000433 } else if (CurLoop->contains(User)) {
Chris Lattnera2706512003-12-10 06:41:05 +0000434 return false;
Chris Lattnerea9403f2003-12-11 22:23:32 +0000435 }
436 }
Chris Lattnera2706512003-12-10 06:41:05 +0000437 return true;
438}
439
440
441/// isLoopInvariantInst - Return true if all operands of this instruction are
442/// loop invariant. We also filter out non-hoistable instructions here just for
443/// efficiency.
444///
445bool LICM::isLoopInvariantInst(Instruction &I) {
446 // The instruction is loop invariant if all of its operands are loop-invariant
447 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3280f7b2004-04-18 22:46:08 +0000448 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattnera2706512003-12-10 06:41:05 +0000449 return false;
450
Chris Lattnered6dfc22003-12-09 19:32:44 +0000451 // If we got this far, the instruction is loop invariant!
452 return true;
453}
454
Chris Lattnera2706512003-12-10 06:41:05 +0000455/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattnera3df8a92003-12-19 08:18:16 +0000456/// this function moves it to the exit blocks and patches up SSA form as needed.
457/// This method is guaranteed to remove the original instruction from its
458/// position, and may either delete it or move it to outside of the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000459///
460void LICM::sink(Instruction &I) {
Nick Lewycky39a38312010-07-30 20:27:01 +0000461 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Chris Lattnera2706512003-12-10 06:41:05 +0000462
Devang Patelb7211a22007-08-21 00:31:24 +0000463 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000464 CurLoop->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000465
466 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000467 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattnerdf45bd32003-12-10 20:43:29 +0000468 ++NumSunk;
469 Changed = true;
470
Chris Lattnera2706512003-12-10 06:41:05 +0000471 // The case where there is only a single exit node of this loop is common
472 // enough that we handle it as a special (more efficient) case. It is more
473 // efficient to handle because there are no PHI nodes that need to be placed.
474 if (ExitBlocks.size() == 1) {
475 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
476 // Instruction is not used, just delete it.
Chris Lattner2741c972004-05-23 21:20:19 +0000477 CurAST->deleteValue(&I);
Devang Patel1bf5ebc2009-10-13 21:41:20 +0000478 // If I has users in unreachable blocks, eliminate.
Devang Patel228ebd02009-10-13 22:56:32 +0000479 // If I is not void type then replaceAllUsesWith undef.
480 // This allows ValueHandlers and custom metadata to adjust itself.
Chris Lattnera6a36f52010-08-29 04:55:06 +0000481 if (!I.use_empty())
Devang Patel228ebd02009-10-13 22:56:32 +0000482 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000483 I.eraseFromParent();
Chris Lattnera2706512003-12-10 06:41:05 +0000484 } else {
485 // Move the instruction to the start of the exit block, after any PHI
486 // nodes in it.
Chris Lattner3c80a512006-06-26 19:10:05 +0000487 I.removeFromParent();
Dan Gohman02dea8b2008-05-23 21:05:58 +0000488 BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
Chris Lattnera2706512003-12-10 06:41:05 +0000489 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
490 }
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000491 return;
492 }
493
494 if (ExitBlocks.empty()) {
Chris Lattnera2706512003-12-10 06:41:05 +0000495 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner2741c972004-05-23 21:20:19 +0000496 CurAST->deleteValue(&I);
Devang Patel1bf5ebc2009-10-13 21:41:20 +0000497 // If I has users in unreachable blocks, eliminate.
Devang Patel228ebd02009-10-13 22:56:32 +0000498 // If I is not void type then replaceAllUsesWith undef.
499 // This allows ValueHandlers and custom metadata to adjust itself.
Chris Lattnera6a36f52010-08-29 04:55:06 +0000500 if (!I.use_empty())
Devang Patel228ebd02009-10-13 22:56:32 +0000501 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner3c80a512006-06-26 19:10:05 +0000502 I.eraseFromParent();
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000503 return;
504 }
505
Chris Lattnera6a36f52010-08-29 04:55:06 +0000506 // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
507 // hard work of inserting PHI nodes as necessary.
508 SmallVector<PHINode*, 8> NewPHIs;
509 SSAUpdater SSA(&NewPHIs);
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000510
Chris Lattnera6a36f52010-08-29 04:55:06 +0000511 if (!I.use_empty())
512 SSA.Initialize(&I);
513
514 // Insert a copy of the instruction in each exit block of the loop that is
515 // dominated by the instruction. Each exit block is known to only be in the
516 // ExitBlocks list once.
517 BasicBlock *InstOrigBB = I.getParent();
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000518 unsigned NumInserted = 0;
Chris Lattnera6a36f52010-08-29 04:55:06 +0000519
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000520 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
521 BasicBlock *ExitBlock = ExitBlocks[i];
Chris Lattnera6a36f52010-08-29 04:55:06 +0000522
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000523 if (!isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB))
524 continue;
525
Chris Lattnera6a36f52010-08-29 04:55:06 +0000526 // Insert the code after the last PHI node.
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000527 BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
Chris Lattnera6a36f52010-08-29 04:55:06 +0000528
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000529 // If this is the first exit block processed, just move the original
530 // instruction, otherwise clone the original instruction and insert
531 // the copy.
532 Instruction *New;
Chris Lattnera6a36f52010-08-29 04:55:06 +0000533 if (NumInserted++ == 0) {
534 I.moveBefore(InsertPt);
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000535 New = &I;
536 } else {
537 New = I.clone();
538 CurAST->copyValue(&I, New);
539 if (!I.getName().empty())
540 New->setName(I.getName()+".le");
541 ExitBlock->getInstList().insert(InsertPt, New);
Chris Lattnereaa24302004-07-27 07:38:32 +0000542 }
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000543
Chris Lattnera6a36f52010-08-29 04:55:06 +0000544 // Now that we have inserted the instruction, inform SSAUpdater.
545 if (!I.use_empty())
546 SSA.AddAvailableValue(ExitBlock, New);
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000547 }
Chris Lattnera6a36f52010-08-29 04:55:06 +0000548
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000549 // If the instruction doesn't dominate any exit blocks, it must be dead.
550 if (NumInserted == 0) {
551 CurAST->deleteValue(&I);
Chris Lattnera6a36f52010-08-29 04:55:06 +0000552 if (!I.use_empty())
553 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000554 I.eraseFromParent();
Chris Lattnera6a36f52010-08-29 04:55:06 +0000555 return;
Chris Lattnerd7bc19d2010-08-29 04:28:20 +0000556 }
Chris Lattnera6a36f52010-08-29 04:55:06 +0000557
558 // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
559 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
560 // Grab the use before incrementing the iterator.
561 Use &U = UI.getUse();
562 // Increment the iterator before removing the use from the list.
563 ++UI;
564 SSA.RewriteUseAfterInsertions(U);
Chris Lattnera2706512003-12-10 06:41:05 +0000565 }
Chris Lattnera6a36f52010-08-29 04:55:06 +0000566
567 // Update CurAST for NewPHIs if I had pointer type.
568 if (I.getType()->isPointerTy())
569 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
570 CurAST->copyValue(NewPHIs[i], &I);
Chris Lattnera2706512003-12-10 06:41:05 +0000571}
Chris Lattner952eaee2002-09-29 21:46:09 +0000572
Chris Lattner94170592002-09-26 16:52:07 +0000573/// hoist - When an instruction is found to only use loop invariant operands
574/// that is safe to hoist, this instruction is called to do the dirty work.
575///
Chris Lattnera2706512003-12-10 06:41:05 +0000576void LICM::hoist(Instruction &I) {
David Greenef1582692010-01-05 01:27:30 +0000577 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
Evan Cheng67d1d1f2009-10-12 22:25:23 +0000578 << I << "\n");
Chris Lattnered6dfc22003-12-09 19:32:44 +0000579
Chris Lattner99a57212002-09-26 19:40:25 +0000580 // Remove the instruction from its current basic block... but don't delete the
581 // instruction.
Chris Lattner3c80a512006-06-26 19:10:05 +0000582 I.removeFromParent();
Chris Lattnere0e734e2002-05-10 22:44:58 +0000583
Chris Lattner9646e6b2002-09-26 16:38:03 +0000584 // Insert the new node in Preheader, before the terminator.
Chris Lattnera2706512003-12-10 06:41:05 +0000585 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000586
Chris Lattnera2706512003-12-10 06:41:05 +0000587 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner118dd0c2004-03-15 04:11:30 +0000588 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner9646e6b2002-09-26 16:38:03 +0000589 ++NumHoisted;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000590 Changed = true;
591}
592
Chris Lattnera2706512003-12-10 06:41:05 +0000593/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
594/// not a trapping instruction or if it is a trapping instruction and is
595/// guaranteed to execute.
Tanya Lattner9966c032003-08-05 18:45:46 +0000596///
Chris Lattnera2706512003-12-10 06:41:05 +0000597bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattner92094b42003-12-09 17:18:00 +0000598 // If it is not a trapping instruction, it is always safe to hoist.
Eli Friedman0b79a772009-07-17 04:28:42 +0000599 if (Inst.isSafeToSpeculativelyExecute())
600 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000601
Chris Lattner92094b42003-12-09 17:18:00 +0000602 // Otherwise we have to check to make sure that the instruction dominates all
603 // of the exit blocks. If it doesn't, then there is a path out of the loop
604 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner9966c032003-08-05 18:45:46 +0000605
Chris Lattner92094b42003-12-09 17:18:00 +0000606 // If the instruction is in the header block for the loop (which is very
607 // common), it is always guaranteed to dominate the exit blocks. Since this
608 // is a common case, and can save some work, check it now.
Chris Lattnera2706512003-12-10 06:41:05 +0000609 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattner92094b42003-12-09 17:18:00 +0000610 return true;
Tanya Lattner9966c032003-08-05 18:45:46 +0000611
Chris Lattner92094b42003-12-09 17:18:00 +0000612 // Get the exit blocks for the current loop.
Devang Patelb7211a22007-08-21 00:31:24 +0000613 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner5fa802f2004-04-18 22:15:13 +0000614 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner92094b42003-12-09 17:18:00 +0000615
Owen Anderson3a2b58f2007-04-24 06:40:39 +0000616 // For each exit block, get the DT node and walk up the DT until the
Chris Lattner92094b42003-12-09 17:18:00 +0000617 // instruction's basic block is found or we exit the loop.
Chris Lattnera2706512003-12-10 06:41:05 +0000618 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
619 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
620 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000621
Tanya Lattner9966c032003-08-05 18:45:46 +0000622 return true;
623}
624
Chris Lattnereb53ae42002-09-26 16:19:31 +0000625
Chris Lattner2e6e7412003-02-24 03:52:32 +0000626/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
627/// stores out of the loop and moving loads to before the loop. We do this by
628/// looping over the stores in the loop, looking for stores to Must pointers
629/// which are loop invariant. We promote these memory locations to use allocas
630/// instead. These allocas can easily be raised to register values by the
631/// PromoteMem2Reg functionality.
632///
633void LICM::PromoteValuesInLoop() {
634 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner065a6162003-09-10 05:29:43 +0000635 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner2e6e7412003-02-24 03:52:32 +0000636 // pointer.
637 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000638 DenseMap<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
Chris Lattner2e6e7412003-02-24 03:52:32 +0000639
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000640 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
641 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000642
643 Changed = true;
644 NumPromoted += PromotedValues.size();
645
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000646 std::vector<Value*> PointerValueNumbers;
647
Chris Lattner2e6e7412003-02-24 03:52:32 +0000648 // Emit a copy from the value into the alloca'd value in the loop preheader
649 TerminatorInst *LoopPredInst = Preheader->getTerminator();
650 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000651 Value *Ptr = PromotedValues[i].second;
652
653 // If we are promoting a pointer value, update alias information for the
654 // inserted load.
655 Value *LoadValue = 0;
Duncan Sands1df98592010-02-16 11:11:14 +0000656 if (cast<PointerType>(Ptr->getType())->getElementType()->isPointerTy()) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000657 // Locate a load or store through the pointer, and assign the same value
658 // to LI as we are loading or storing. Since we know that the value is
659 // stored in this loop, this will always succeed.
660 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
Gabor Greif488d4422010-04-14 16:13:56 +0000661 UI != E; ++UI) {
662 User *U = *UI;
663 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000664 LoadValue = LI;
665 break;
Gabor Greif488d4422010-04-14 16:13:56 +0000666 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerbdacd872004-09-15 02:34:40 +0000667 if (SI->getOperand(1) == Ptr) {
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000668 LoadValue = SI->getOperand(0);
669 break;
670 }
671 }
Gabor Greif488d4422010-04-14 16:13:56 +0000672 }
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000673 assert(LoadValue && "No store through the pointer found!");
674 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
675 }
676
677 // Load from the memory we are promoting.
678 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
679
680 if (LoadValue) CurAST->copyValue(LoadValue, LI);
681
682 // Store into the temporary alloca.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000683 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
684 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000685
Chris Lattner2e6e7412003-02-24 03:52:32 +0000686 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattner0ed2da92003-12-10 15:56:24 +0000687 // uses of the allocas in question.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000688 //
Dan Gohman9b787632008-06-22 20:18:58 +0000689 for (Loop::block_iterator I = CurLoop->block_begin(),
690 E = CurLoop->block_end(); I != E; ++I) {
691 BasicBlock *BB = *I;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000692 // Rewrite all loads and stores in the block of the pointer...
Dan Gohman9b787632008-06-22 20:18:58 +0000693 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
Chris Lattnere408e252003-04-23 16:37:45 +0000694 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000695 DenseMap<Value*, AllocaInst*>::iterator
Chris Lattner2e6e7412003-02-24 03:52:32 +0000696 I = ValueToAllocaMap.find(L->getOperand(0));
697 if (I != ValueToAllocaMap.end())
698 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattnere408e252003-04-23 16:37:45 +0000699 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000700 DenseMap<Value*, AllocaInst*>::iterator
Chris Lattner2e6e7412003-02-24 03:52:32 +0000701 I = ValueToAllocaMap.find(S->getOperand(1));
702 if (I != ValueToAllocaMap.end())
703 S->setOperand(1, I->second); // Rewrite store instruction...
704 }
705 }
Chris Lattner2e6e7412003-02-24 03:52:32 +0000706 }
707
Chris Lattner0ed2da92003-12-10 15:56:24 +0000708 // Now that the body of the loop uses the allocas instead of the original
709 // memory locations, insert code to copy the alloca value back into the
710 // original memory location on all exits from the loop. Note that we only
711 // want to insert one copy of the code in each exit block, though the loop may
712 // exit to the same block more than once.
713 //
Chris Lattner19d9d432008-05-22 03:22:42 +0000714 SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
Chris Lattner0ed2da92003-12-10 15:56:24 +0000715
Devang Patelb7211a22007-08-21 00:31:24 +0000716 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner5fa802f2004-04-18 22:15:13 +0000717 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner19d9d432008-05-22 03:22:42 +0000718 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
719 if (!ProcessedBlocks.insert(ExitBlocks[i]))
720 continue;
721
722 // Copy all of the allocas into their memory locations.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000723 BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
Chris Lattner19d9d432008-05-22 03:22:42 +0000724 Instruction *InsertPos = BI;
725 unsigned PVN = 0;
726 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
727 // Load from the alloca.
728 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000729
Chris Lattner19d9d432008-05-22 03:22:42 +0000730 // If this is a pointer type, update alias info appropriately.
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if (LI->getType()->isPointerTy())
Chris Lattner19d9d432008-05-22 03:22:42 +0000732 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000733
Chris Lattner19d9d432008-05-22 03:22:42 +0000734 // Store into the memory we promoted.
735 new StoreInst(LI, PromotedValues[i].second, InsertPos);
Chris Lattner0ed2da92003-12-10 15:56:24 +0000736 }
Chris Lattner19d9d432008-05-22 03:22:42 +0000737 }
Chris Lattner0ed2da92003-12-10 15:56:24 +0000738
Chris Lattner2e6e7412003-02-24 03:52:32 +0000739 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000740 // all of the new allocas we just created into real SSA registers.
Chris Lattner2e6e7412003-02-24 03:52:32 +0000741 //
742 std::vector<AllocaInst*> PromotedAllocas;
743 PromotedAllocas.reserve(PromotedValues.size());
744 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
745 PromotedAllocas.push_back(PromotedValues[i].first);
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000746 PromoteMemToReg(PromotedAllocas, *DT, *DF, CurAST);
Chris Lattner2e6e7412003-02-24 03:52:32 +0000747}
748
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000749/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Devang Patelf2038b12007-09-19 20:18:51 +0000750/// pointers, which are not loaded and stored through may aliases and are safe
751/// for promotion. If these are found, create an alloca for the value, add it
752/// to the PromotedValues list, and keep track of the mapping from value to
753/// alloca.
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000754void LICM::FindPromotableValuesInLoop(
Chris Lattner2e6e7412003-02-24 03:52:32 +0000755 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000756 DenseMap<Value*, AllocaInst*> &ValueToAllocaMap) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000757 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
758
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000759 // Loop over all of the alias sets in the tracker object.
Chris Lattner0252e492003-03-03 23:32:45 +0000760 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
761 I != E; ++I) {
762 AliasSet &AS = *I;
763 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnerfb3ee192004-09-15 01:04:07 +0000764 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner118dd0c2004-03-15 04:11:30 +0000765 // volatile loads or stores.
Chris Lattner29d92932008-05-22 00:53:38 +0000766 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000767 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Chris Lattner29d92932008-05-22 00:53:38 +0000768 continue;
769
770 assert(!AS.empty() &&
771 "Must alias set should have at least one pointer element in it!");
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000772 Value *V = AS.begin()->getValue();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000773
Chris Lattner29d92932008-05-22 00:53:38 +0000774 // Check that all of the pointers in the alias set have the same type. We
775 // cannot (yet) promote a memory location that is loaded and stored in
776 // different sizes.
777 {
Chris Lattner0252e492003-03-03 23:32:45 +0000778 bool PointerOk = true;
779 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
Chris Lattnerd7168dd2009-03-09 05:11:09 +0000780 if (V->getType() != I->getValue()->getType()) {
Chris Lattner0252e492003-03-03 23:32:45 +0000781 PointerOk = false;
782 break;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000783 }
Chris Lattner29d92932008-05-22 00:53:38 +0000784 if (!PointerOk)
785 continue;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000786 }
Chris Lattner29d92932008-05-22 00:53:38 +0000787
Chris Lattner19d9d432008-05-22 03:22:42 +0000788 // It isn't safe to promote a load/store from the loop if the load/store is
789 // conditional. For example, turning:
790 //
791 // for () { if (c) *P += 1; }
792 //
793 // into:
794 //
795 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
796 //
797 // is not safe, because *P may only be valid to access if 'c' is true.
798 //
799 // It is safe to promote P if all uses are direct load/stores and if at
800 // least one is guaranteed to be executed.
801 bool GuaranteedToExecute = false;
802 bool InvalidInst = false;
803 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
804 UI != UE; ++UI) {
805 // Ignore instructions not in this loop.
Chris Lattner29d92932008-05-22 00:53:38 +0000806 Instruction *Use = dyn_cast<Instruction>(*UI);
Dan Gohman92329c72009-12-18 01:24:09 +0000807 if (!Use || !CurLoop->contains(Use))
Chris Lattner29d92932008-05-22 00:53:38 +0000808 continue;
Chris Lattner29d92932008-05-22 00:53:38 +0000809
Chris Lattner19d9d432008-05-22 03:22:42 +0000810 if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
811 InvalidInst = true;
Chris Lattner29d92932008-05-22 00:53:38 +0000812 break;
Chris Lattner19d9d432008-05-22 03:22:42 +0000813 }
814
815 if (!GuaranteedToExecute)
816 GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
Chris Lattner29d92932008-05-22 00:53:38 +0000817 }
818
Chris Lattner19d9d432008-05-22 03:22:42 +0000819 // If there is an non-load/store instruction in the loop, we can't promote
820 // it. If there isn't a guaranteed-to-execute instruction, we can't
821 // promote.
822 if (InvalidInst || !GuaranteedToExecute)
Chris Lattner29d92932008-05-22 00:53:38 +0000823 continue;
824
825 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
Owen Anderson50dead02009-07-15 23:53:25 +0000826 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
Chris Lattner29d92932008-05-22 00:53:38 +0000827 PromotedValues.push_back(std::make_pair(AI, V));
828
829 // Update the AST and alias analysis.
830 CurAST->copyValue(V, AI);
831
832 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
Chris Lattnerdc1ceb32010-08-29 04:23:04 +0000833 ValueToAllocaMap[I->getValue()] = AI;
Chris Lattner29d92932008-05-22 00:53:38 +0000834
David Greenef1582692010-01-05 01:27:30 +0000835 DEBUG(dbgs() << "LICM: Promoting value: " << *V << "\n");
Chris Lattner2e6e7412003-02-24 03:52:32 +0000836 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000837}
Devang Patel91d22c82007-07-31 08:01:41 +0000838
839/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
840void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
841 AliasSetTracker *AST = LoopToAliasMap[L];
842 if (!AST)
843 return;
844
845 AST->copyValue(From, To);
846}
847
848/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
849/// set.
850void LICM::deleteAnalysisValue(Value *V, Loop *L) {
851 AliasSetTracker *AST = LoopToAliasMap[L];
852 if (!AST)
853 return;
854
855 AST->deleteValue(V);
856}