blob: f2288dae3bf5d6eeba27d7c938ef9c36f0a110c5 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// 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.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
23#include "llvm/Pass.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Target/TargetAsmInfo.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetLowering.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000029#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000031#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000032#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000033#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000034#include "llvm/Support/CommandLine.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000035#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000039using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000040using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041
Evan Chengab631522008-12-19 18:03:11 +000042static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
43 cl::init(false), cl::Hidden);
44
Eric Christopher692bf6b2008-09-24 05:32:41 +000045namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
47 /// TLI - Keep a pointer of a TargetLowering to consult for determining
48 /// transformation profitability.
49 const TargetLowering *TLI;
Evan Chengab631522008-12-19 18:03:11 +000050
51 /// BackEdges - Keep a set of all the loop back edges.
52 ///
53 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000054 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000056 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000057 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000058 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000059
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000061 bool EliminateMostlyEmptyBlocks(Function &F);
62 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
63 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000064 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000065 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
66 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000067 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
68 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000069 bool OptimizeExtUses(Instruction *I);
Evan Chengab631522008-12-19 18:03:11 +000070 void findLoopBackEdges(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000071 };
72}
Devang Patel794fd752007-05-01 21:15:47 +000073
Devang Patel19974732007-05-03 01:11:54 +000074char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000075static RegisterPass<CodeGenPrepare> X("codegenprepare",
76 "Optimize for code generation");
77
78FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
79 return new CodeGenPrepare(TLI);
80}
81
Evan Chengab631522008-12-19 18:03:11 +000082/// findLoopBackEdges - Do a DFS walk to find loop back edges.
83///
84void CodeGenPrepare::findLoopBackEdges(Function &F) {
85 SmallPtrSet<BasicBlock*, 8> Visited;
86 SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
87 SmallPtrSet<BasicBlock*, 8> InStack;
88
89 BasicBlock *BB = &F.getEntryBlock();
90 if (succ_begin(BB) == succ_end(BB))
91 return;
92 Visited.insert(BB);
93 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
94 InStack.insert(BB);
95 do {
96 std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
97 BasicBlock *ParentBB = Top.first;
98 succ_iterator &I = Top.second;
99
100 bool FoundNew = false;
101 while (I != succ_end(ParentBB)) {
102 BB = *I++;
103 if (Visited.insert(BB)) {
104 FoundNew = true;
105 break;
106 }
107 // Successor is in VisitStack, it's a back edge.
108 if (InStack.count(BB))
109 BackEdges.insert(std::make_pair(ParentBB, BB));
110 }
111
112 if (FoundNew) {
113 // Go down one level if there is a unvisited successor.
114 InStack.insert(BB);
115 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
116 } else {
117 // Go up one level.
118 std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
119 InStack.erase(Pop.first);
120 VisitStack.pop_back();
121 }
122 } while (!VisitStack.empty());
123}
124
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000125
126bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000127 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000128
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000129 // First pass, eliminate blocks that contain only PHI nodes and an
130 // unconditional branch.
131 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000132
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000133 // Now find loop back edges.
134 findLoopBackEdges(F);
135
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000136 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000137 while (MadeChange) {
138 MadeChange = false;
139 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
140 MadeChange |= OptimizeBlock(*BB);
141 EverMadeChange |= MadeChange;
142 }
143 return EverMadeChange;
144}
145
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000146/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000148/// often split edges in ways that are non-optimal for isel. Start by
149/// eliminating these blocks so we can split them the way we want them.
150bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
151 bool MadeChange = false;
152 // Note that this intentionally skips the entry block.
153 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
154 BasicBlock *BB = I++;
155
156 // If this block doesn't end with an uncond branch, ignore it.
157 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
158 if (!BI || !BI->isUnconditional())
159 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000160
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000161 // If the instruction before the branch isn't a phi node, then other stuff
162 // is happening here.
163 BasicBlock::iterator BBI = BI;
164 if (BBI != BB->begin()) {
165 --BBI;
166 if (!isa<PHINode>(BBI)) continue;
167 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000168
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000169 // Do not break infinite loops.
170 BasicBlock *DestBB = BI->getSuccessor(0);
171 if (DestBB == BB)
172 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000173
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000174 if (!CanMergeBlocks(BB, DestBB))
175 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000176
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000177 EliminateMostlyEmptyBlock(BB);
178 MadeChange = true;
179 }
180 return MadeChange;
181}
182
183/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
184/// single uncond branch between them, and BB contains no other non-phi
185/// instructions.
186bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
187 const BasicBlock *DestBB) const {
188 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
189 // the successor. If there are more complex condition (e.g. preheaders),
190 // don't mess around with them.
191 BasicBlock::const_iterator BBI = BB->begin();
192 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
193 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
194 UI != E; ++UI) {
195 const Instruction *User = cast<Instruction>(*UI);
196 if (User->getParent() != DestBB || !isa<PHINode>(User))
197 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000198 // If User is inside DestBB block and it is a PHINode then check
199 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000200 // a complex condition (e.g. preheaders) we want to avoid here.
201 if (User->getParent() == DestBB) {
202 if (const PHINode *UPN = dyn_cast<PHINode>(User))
203 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
204 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
205 if (Insn && Insn->getParent() == BB &&
206 Insn->getParent() != UPN->getIncomingBlock(I))
207 return false;
208 }
209 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000210 }
211 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000212
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000213 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
214 // and DestBB may have conflicting incoming values for the block. If so, we
215 // can't merge the block.
216 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
217 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000218
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000219 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000220 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
222 // It is faster to get preds from a PHI than with pred_iterator.
223 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
224 BBPreds.insert(BBPN->getIncomingBlock(i));
225 } else {
226 BBPreds.insert(pred_begin(BB), pred_end(BB));
227 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000228
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000229 // Walk the preds of DestBB.
230 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
231 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
232 if (BBPreds.count(Pred)) { // Common predecessor?
233 BBI = DestBB->begin();
234 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
235 const Value *V1 = PN->getIncomingValueForBlock(Pred);
236 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000237
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000238 // If V2 is a phi node in BB, look up what the mapped value will be.
239 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
240 if (V2PN->getParent() == BB)
241 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000242
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000243 // If there is a conflict, bail out.
244 if (V1 != V2) return false;
245 }
246 }
247 }
248
249 return true;
250}
251
252
253/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
254/// an unconditional branch in it.
255void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
256 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
257 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000258
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 // If the destination block has a single pred, then this is a trivial edge,
262 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000263 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000264 if (SinglePred != DestBB) {
265 // Remember if SinglePred was the entry block of the function. If so, we
266 // will need to move BB back to the entry position.
267 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
268 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000269
Chris Lattnerf5102a02008-11-28 19:54:49 +0000270 if (isEntry && BB != &BB->getParent()->getEntryBlock())
271 BB->moveBefore(&BB->getParent()->getEntryBlock());
272
273 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
274 return;
275 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000277
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000278 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
279 // to handle the new incoming edges it is about to have.
280 PHINode *PN;
281 for (BasicBlock::iterator BBI = DestBB->begin();
282 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
283 // Remove the incoming value for BB, and remember it.
284 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 // Two options: either the InVal is a phi node defined in BB or it is some
287 // value that dominates BB.
288 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
289 if (InValPhi && InValPhi->getParent() == BB) {
290 // Add all of the input values of the input PHI as inputs of this phi.
291 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
292 PN->addIncoming(InValPhi->getIncomingValue(i),
293 InValPhi->getIncomingBlock(i));
294 } else {
295 // Otherwise, add one instance of the dominating value for each edge that
296 // we will be adding.
297 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
298 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
299 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
300 } else {
301 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
302 PN->addIncoming(InVal, *PI);
303 }
304 }
305 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000306
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307 // The PHIs are now updated, change everything that refers to BB to use
308 // DestBB and remove BB.
309 BB->replaceAllUsesWith(DestBB);
310 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000311
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000312 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
313}
314
315
Chris Lattnerebe80752007-12-24 19:32:55 +0000316/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000317/// successor if it will improve codegen. We only do this if the successor has
318/// phi nodes (otherwise critical edges are ok). If there is already another
319/// predecessor of the succ that is empty (and thus has no phi nodes), use it
320/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000321static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
322 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
323 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000324 BasicBlock *TIBB = TI->getParent();
325 BasicBlock *Dest = TI->getSuccessor(SuccNum);
326 assert(isa<PHINode>(Dest->begin()) &&
327 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000328
Chris Lattnerebe80752007-12-24 19:32:55 +0000329 // As a hack, never split backedges of loops. Even though the copy for any
330 // PHIs inserted on the backedge would be dead for exits from the loop, we
331 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000332 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000333 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000334
Evan Chengab631522008-12-19 18:03:11 +0000335 if (!FactorCommonPreds) {
336 /// TIPHIValues - This array is lazily computed to determine the values of
337 /// PHIs in Dest that TI would provide.
338 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000339
Evan Chengab631522008-12-19 18:03:11 +0000340 // Check to see if Dest has any blocks that can be used as a split edge for
341 // this terminator.
342 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
343 BasicBlock *Pred = *PI;
344 // To be usable, the pred has to end with an uncond branch to the dest.
345 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
346 if (!PredBr || !PredBr->isUnconditional() ||
347 // Must be empty other than the branch.
348 &Pred->front() != PredBr ||
349 // Cannot be the entry block; its label does not get emitted.
350 Pred == &(Dest->getParent()->getEntryBlock()))
351 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Evan Chengab631522008-12-19 18:03:11 +0000353 // Finally, since we know that Dest has phi nodes in it, we have to make
354 // sure that jumping to Pred will have the same affect as going to Dest in
355 // terms of PHI values.
356 PHINode *PN;
357 unsigned PHINo = 0;
358 bool FoundMatch = true;
359 for (BasicBlock::iterator I = Dest->begin();
360 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
361 if (PHINo == TIPHIValues.size())
362 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Evan Chengab631522008-12-19 18:03:11 +0000364 // If the PHI entry doesn't work, we can't use this pred.
365 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
366 FoundMatch = false;
367 break;
368 }
369 }
370
371 // If we found a workable predecessor, change TI to branch to Succ.
372 if (FoundMatch) {
373 Dest->removePredecessor(TIBB);
374 TI->setSuccessor(SuccNum, Pred);
375 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000376 }
377 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000378
Evan Chengab631522008-12-19 18:03:11 +0000379 SplitCriticalEdge(TI, SuccNum, P, true);
380 return;
381 }
382
383 PHINode *PN;
384 SmallVector<Value*, 8> TIPHIValues;
385 for (BasicBlock::iterator I = Dest->begin();
386 (PN = dyn_cast<PHINode>(I)); ++I)
387 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
388
389 SmallVector<BasicBlock*, 8> IdenticalPreds;
390 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
391 BasicBlock *Pred = *PI;
392 if (BackEdges.count(std::make_pair(Pred, Dest)))
393 continue;
394 if (PI == TIBB)
395 IdenticalPreds.push_back(Pred);
396 else {
397 bool Identical = true;
398 unsigned PHINo = 0;
399 for (BasicBlock::iterator I = Dest->begin();
400 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
401 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
402 Identical = false;
403 break;
404 }
405 if (Identical)
406 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000407 }
408 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000409
Evan Chengab631522008-12-19 18:03:11 +0000410 assert(!IdenticalPreds.empty());
411 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
412 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000413}
414
Evan Chengab631522008-12-19 18:03:11 +0000415
Chris Lattnerdd77df32007-04-13 20:30:56 +0000416/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
417/// copy (e.g. it's casting from one pointer type to another, int->uint, or
418/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000419/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000420///
421/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000422///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000423static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000424 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000425 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
426 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000427
Chris Lattnerdd77df32007-04-13 20:30:56 +0000428 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000429 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000430 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000431
Chris Lattnerdd77df32007-04-13 20:30:56 +0000432 // If this is an extension, it will be a zero or sign extension, which
433 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000434 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436 // If these values will be promoted, find out what they will be promoted
437 // to. This helps us consider truncates on PPC as noop copies when they
438 // are.
439 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
440 SrcVT = TLI.getTypeToTransformTo(SrcVT);
441 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
442 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000443
Chris Lattnerdd77df32007-04-13 20:30:56 +0000444 // If, after promotion, these are the same types, this is a noop copy.
445 if (SrcVT != DstVT)
446 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000448 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000451 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000453 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000455 UI != E; ) {
456 Use &TheUse = UI.getUse();
457 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 // Figure out which BB this cast is used in. For PHI's this is the
460 // appropriate predecessor block.
461 BasicBlock *UserBB = User->getParent();
462 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000463 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000464 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 // Preincrement use iterator so we don't invalidate it.
467 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 // If this user is in the same block as the cast, don't change the cast.
470 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 // If we have already inserted a cast into this block, use it.
473 CastInst *&InsertedCast = InsertedCasts[UserBB];
474
475 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000476 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
478 InsertedCast =
479 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 InsertPt);
481 MadeChange = true;
482 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 TheUse = InsertedCast;
486 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000489 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000491 MadeChange = true;
492 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 return MadeChange;
495}
496
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000498/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000499/// a clear win except on targets with multiple condition code registers
500/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000501///
502/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000503static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000504 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 /// InsertedCmp - Only insert a cmp in each block once.
507 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000508
Dale Johannesence0b2372007-06-12 16:50:17 +0000509 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000511 UI != E; ) {
512 Use &TheUse = UI.getUse();
513 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 // Preincrement use iterator so we don't invalidate it.
516 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000517
Dale Johannesence0b2372007-06-12 16:50:17 +0000518 // Don't bother for PHI nodes.
519 if (isa<PHINode>(User))
520 continue;
521
522 // Figure out which BB this cmp is used in.
523 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 // If this user is in the same block as the cmp, don't change the cmp.
526 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 // If we have already inserted a cmp into this block, use it.
529 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
530
531 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000532 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533
534 InsertedCmp =
535 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 CI->getOperand(1), "", InsertPt);
537 MadeChange = true;
538 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 // Replace a use of the cmp with a use of the new cmp.
541 TheUse = InsertedCmp;
542 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 // If we removed all uses, nuke the cmp.
545 if (CI->use_empty())
546 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000547
Dale Johannesence0b2372007-06-12 16:50:17 +0000548 return MadeChange;
549}
550
Chris Lattner88a5c832008-11-25 07:09:13 +0000551//===----------------------------------------------------------------------===//
552// Addressing Mode Analysis and Optimization
553//===----------------------------------------------------------------------===//
554
Dan Gohman844731a2008-05-13 00:00:25 +0000555namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000556 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
557 /// which holds actual Value*'s for register values.
558 struct ExtAddrMode : public TargetLowering::AddrMode {
559 Value *BaseReg;
560 Value *ScaledReg;
561 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
562 void print(OStream &OS) const;
563 void dump() const {
564 print(cerr);
565 cerr << '\n';
566 }
567 };
568} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000569
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000570static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
Chris Lattner4744d852008-11-24 22:40:05 +0000571 AM.print(OS);
572 return OS;
573}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000574
Chris Lattner4744d852008-11-24 22:40:05 +0000575void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000576 bool NeedPlus = false;
577 OS << "[";
Dan Gohman03ce0422009-02-13 17:45:12 +0000578 if (BaseGV) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000579 OS << (NeedPlus ? " + " : "")
Dan Gohman03ce0422009-02-13 17:45:12 +0000580 << "GV:";
581 WriteAsOperand(*OS.stream(), BaseGV, /*PrintType=*/false);
582 NeedPlus = true;
583 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000584
Chris Lattner4744d852008-11-24 22:40:05 +0000585 if (BaseOffs)
586 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000587
Dan Gohman03ce0422009-02-13 17:45:12 +0000588 if (BaseReg) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000589 OS << (NeedPlus ? " + " : "")
Dan Gohman03ce0422009-02-13 17:45:12 +0000590 << "Base:";
591 WriteAsOperand(*OS.stream(), BaseReg, /*PrintType=*/false);
592 NeedPlus = true;
593 }
594 if (Scale) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000595 OS << (NeedPlus ? " + " : "")
Dan Gohman03ce0422009-02-13 17:45:12 +0000596 << Scale << "*";
597 WriteAsOperand(*OS.stream(), ScaledReg, /*PrintType=*/false);
598 NeedPlus = true;
599 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000600
Chris Lattner4744d852008-11-24 22:40:05 +0000601 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000602}
603
Chris Lattner88a5c832008-11-25 07:09:13 +0000604namespace {
605/// AddressingModeMatcher - This class exposes a single public method, which is
606/// used to construct a "maximal munch" of the addressing mode for the target
607/// specified by TLI for an access to "V" with an access type of AccessTy. This
608/// returns the addressing mode that is actually matched by value, but also
609/// returns the list of instructions involved in that addressing computation in
610/// AddrModeInsts.
611class AddressingModeMatcher {
612 SmallVectorImpl<Instruction*> &AddrModeInsts;
613 const TargetLowering &TLI;
Chris Lattner896617b2008-11-26 03:20:37 +0000614
615 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
616 /// the memory instruction that we're computing this address for.
Chris Lattner88a5c832008-11-25 07:09:13 +0000617 const Type *AccessTy;
Chris Lattner896617b2008-11-26 03:20:37 +0000618 Instruction *MemoryInst;
619
620 /// AddrMode - This is the addressing mode that we're building up. This is
621 /// part of the return value of this addressing mode matching stuff.
Chris Lattner88a5c832008-11-25 07:09:13 +0000622 ExtAddrMode &AddrMode;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000623
624 /// IgnoreProfitability - This is set to true when we should not do
625 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
626 /// always returns true.
627 bool IgnoreProfitability;
628
Chris Lattner88a5c832008-11-25 07:09:13 +0000629 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
Chris Lattner896617b2008-11-26 03:20:37 +0000630 const TargetLowering &T, const Type *AT,
631 Instruction *MI, ExtAddrMode &AM)
632 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000633 IgnoreProfitability = false;
634 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000635public:
636
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000637 /// Match - Find the maximal addressing mode that a load/store of V can fold,
638 /// give an access type of AccessTy. This returns a list of involved
639 /// instructions in AddrModeInsts.
Chris Lattner896617b2008-11-26 03:20:37 +0000640 static ExtAddrMode Match(Value *V, const Type *AccessTy,
641 Instruction *MemoryInst,
Chris Lattner88a5c832008-11-25 07:09:13 +0000642 SmallVectorImpl<Instruction*> &AddrModeInsts,
643 const TargetLowering &TLI) {
644 ExtAddrMode Result;
645
646 bool Success =
Chris Lattner896617b2008-11-26 03:20:37 +0000647 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
648 MemoryInst, Result).MatchAddr(V, 0);
Chris Lattner88a5c832008-11-25 07:09:13 +0000649 Success = Success; assert(Success && "Couldn't select *anything*?");
650 return Result;
651 }
652private:
Chris Lattner3b485012008-11-25 07:25:26 +0000653 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Chris Lattner88a5c832008-11-25 07:09:13 +0000654 bool MatchAddr(Value *V, unsigned Depth);
655 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
Chris Lattner84d1b402008-11-26 03:02:41 +0000656 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
657 ExtAddrMode &AMBefore,
658 ExtAddrMode &AMAfter);
659 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Chris Lattner88a5c832008-11-25 07:09:13 +0000660};
661} // end anonymous namespace
662
663/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
664/// Return true and update AddrMode if this addr mode is legal for the target,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000665/// false if not.
Chris Lattner3b485012008-11-25 07:25:26 +0000666bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
667 unsigned Depth) {
668 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
669 // mode. Just process that directly.
670 if (Scale == 1)
671 return MatchAddr(ScaleReg, Depth);
672
673 // If the scale is 0, it takes nothing to add this.
674 if (Scale == 0)
675 return true;
676
Chris Lattner85fa13c2008-11-24 22:44:16 +0000677 // If we already have a scale of this value, we can add to it, otherwise, we
678 // need an available scale field.
679 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
680 return false;
681
Chris Lattner088a1e82008-11-25 04:42:10 +0000682 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000683
684 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
685 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000686 TestAddrMode.Scale += Scale;
687 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000688
Chris Lattner088a1e82008-11-25 04:42:10 +0000689 // If the new address isn't legal, bail out.
690 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
691 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000692
Chris Lattner088a1e82008-11-25 04:42:10 +0000693 // It was legal, so commit it.
694 AddrMode = TestAddrMode;
695
696 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
697 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
698 // X*Scale + C*Scale to addr mode.
699 ConstantInt *CI; Value *AddLHS;
Chris Lattnerd62284a2009-01-18 20:35:00 +0000700 if (isa<Instruction>(ScaleReg) && // not a constant expr.
701 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
Chris Lattner088a1e82008-11-25 04:42:10 +0000702 TestAddrMode.ScaledReg = AddLHS;
703 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
704
705 // If this addressing mode is legal, commit it and remember that we folded
706 // this instruction.
707 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
708 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
709 AddrMode = TestAddrMode;
Chris Lattner88a5c832008-11-25 07:09:13 +0000710 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000711 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000712 }
713
Chris Lattner088a1e82008-11-25 04:42:10 +0000714 // Otherwise, not (x+c)*scale, just return what we have.
715 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000716}
717
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000718/// MightBeFoldableInst - This is a little filter, which returns true if an
719/// addressing computation involving I might be folded into a load/store
720/// accessing it. This doesn't need to be perfect, but needs to accept at least
721/// the set of instructions that MatchOperationAddr can.
722static bool MightBeFoldableInst(Instruction *I) {
723 switch (I->getOpcode()) {
724 case Instruction::BitCast:
725 // Don't touch identity bitcasts.
726 if (I->getType() == I->getOperand(0)->getType())
727 return false;
728 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
729 case Instruction::PtrToInt:
730 // PtrToInt is always a noop, as we know that the int type is pointer sized.
731 return true;
732 case Instruction::IntToPtr:
733 // We know the input is intptr_t, so this is foldable.
734 return true;
735 case Instruction::Add:
736 return true;
737 case Instruction::Mul:
738 case Instruction::Shl:
739 // Can only handle X*C and X << C.
740 return isa<ConstantInt>(I->getOperand(1));
741 case Instruction::GetElementPtr:
742 return true;
743 default:
744 return false;
745 }
746}
747
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000748
Chris Lattner88a5c832008-11-25 07:09:13 +0000749/// MatchOperationAddr - Given an instruction or constant expr, see if we can
750/// fold the operation into the addressing mode. If so, update the addressing
751/// mode and return true, otherwise return false without modifying AddrMode.
752bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
753 unsigned Depth) {
754 // Avoid exponential behavior on extremely deep expression trees.
755 if (Depth >= 5) return false;
756
Chris Lattnerdd77df32007-04-13 20:30:56 +0000757 switch (Opcode) {
758 case Instruction::PtrToInt:
759 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Chris Lattner88a5c832008-11-25 07:09:13 +0000760 return MatchAddr(AddrInst->getOperand(0), Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000761 case Instruction::IntToPtr:
762 // This inttoptr is a no-op if the integer type is pointer sized.
763 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Chris Lattner88a5c832008-11-25 07:09:13 +0000764 TLI.getPointerTy())
765 return MatchAddr(AddrInst->getOperand(0), Depth);
766 return false;
Chris Lattner2efbbb32008-11-26 00:26:16 +0000767 case Instruction::BitCast:
768 // BitCast is always a noop, and we can handle it as long as it is
769 // int->int or pointer->pointer (we don't want int<->fp or something).
770 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
771 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
772 // Don't touch identity bitcasts. These were probably put here by LSR,
773 // and we don't want to mess around with them. Assume it knows what it
774 // is doing.
775 AddrInst->getOperand(0)->getType() != AddrInst->getType())
776 return MatchAddr(AddrInst->getOperand(0), Depth);
777 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000778 case Instruction::Add: {
779 // Check to see if we can merge in the RHS then the LHS. If so, we win.
780 ExtAddrMode BackupAddrMode = AddrMode;
781 unsigned OldSize = AddrModeInsts.size();
Chris Lattner88a5c832008-11-25 07:09:13 +0000782 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
783 MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000784 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000785
Chris Lattnerdd77df32007-04-13 20:30:56 +0000786 // Restore the old addr mode info.
787 AddrMode = BackupAddrMode;
788 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000789
Chris Lattnerdd77df32007-04-13 20:30:56 +0000790 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Chris Lattner88a5c832008-11-25 07:09:13 +0000791 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
792 MatchAddr(AddrInst->getOperand(1), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000793 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000794
Chris Lattnerdd77df32007-04-13 20:30:56 +0000795 // Otherwise we definitely can't merge the ADD in.
796 AddrMode = BackupAddrMode;
797 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000798 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000799 }
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000800 //case Instruction::Or:
801 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
802 //break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000803 case Instruction::Mul:
804 case Instruction::Shl: {
Chris Lattner7ad1c732008-11-25 04:47:41 +0000805 // Can only handle X*C and X << C.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000806 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Chris Lattner88a5c832008-11-25 07:09:13 +0000807 if (!RHS) return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000808 int64_t Scale = RHS->getSExtValue();
809 if (Opcode == Instruction::Shl)
810 Scale = 1 << Scale;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000811
Chris Lattner3b485012008-11-25 07:25:26 +0000812 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000813 }
814 case Instruction::GetElementPtr: {
815 // Scan the GEP. We check it if it contains constant offsets and at most
816 // one variable offset.
817 int VariableOperand = -1;
818 unsigned VariableScale = 0;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000819
Chris Lattnerdd77df32007-04-13 20:30:56 +0000820 int64_t ConstantOffset = 0;
821 const TargetData *TD = TLI.getTargetData();
822 gep_type_iterator GTI = gep_type_begin(AddrInst);
823 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
824 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
825 const StructLayout *SL = TD->getStructLayout(STy);
826 unsigned Idx =
Chris Lattner88a5c832008-11-25 07:09:13 +0000827 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
Chris Lattnerdd77df32007-04-13 20:30:56 +0000828 ConstantOffset += SL->getElementOffset(Idx);
829 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000830 uint64_t TypeSize = TD->getTypePaddedSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000831 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
832 ConstantOffset += CI->getSExtValue()*TypeSize;
833 } else if (TypeSize) { // Scales of zero don't do anything.
834 // We only allow one variable index at the moment.
Chris Lattner88a5c832008-11-25 07:09:13 +0000835 if (VariableOperand != -1)
836 return false;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000837
Chris Lattnerdd77df32007-04-13 20:30:56 +0000838 // Remember the variable index.
839 VariableOperand = i;
840 VariableScale = TypeSize;
841 }
842 }
843 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000844
Chris Lattnerdd77df32007-04-13 20:30:56 +0000845 // A common case is for the GEP to only do a constant offset. In this case,
846 // just add it to the disp field and check validity.
847 if (VariableOperand == -1) {
848 AddrMode.BaseOffs += ConstantOffset;
849 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
850 // Check to see if we can fold the base pointer in too.
Chris Lattner88a5c832008-11-25 07:09:13 +0000851 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000852 return true;
853 }
854 AddrMode.BaseOffs -= ConstantOffset;
Chris Lattner88a5c832008-11-25 07:09:13 +0000855 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000856 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000857
858 // Save the valid addressing mode in case we can't match.
859 ExtAddrMode BackupAddrMode = AddrMode;
860
861 // Check that this has no base reg yet. If so, we won't have a place to
862 // put the base of the GEP (assuming it is not a null ptr).
863 bool SetBaseReg = true;
864 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
865 SetBaseReg = false; // null pointer base doesn't need representation.
866 else if (AddrMode.HasBaseReg)
867 return false; // Base register already specified, can't match GEP.
868 else {
869 // Otherwise, we'll use the GEP base as the BaseReg.
870 AddrMode.HasBaseReg = true;
871 AddrMode.BaseReg = AddrInst->getOperand(0);
872 }
873
874 // See if the scale and offset amount is valid for this target.
875 AddrMode.BaseOffs += ConstantOffset;
876
Chris Lattner3b485012008-11-25 07:25:26 +0000877 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
878 Depth)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000879 AddrMode = BackupAddrMode;
880 return false;
881 }
882
883 // If we have a null as the base of the GEP, folding in the constant offset
884 // plus variable scale is all we can do.
885 if (!SetBaseReg) return true;
886
887 // If this match succeeded, we know that we can form an address with the
888 // GepBase as the basereg. Match the base pointer of the GEP more
889 // aggressively by zeroing out BaseReg and rematching. If the base is
890 // (for example) another GEP, this allows merging in that other GEP into
891 // the addressing mode we're forming.
892 AddrMode.HasBaseReg = false;
893 AddrMode.BaseReg = 0;
894 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
895 assert(Success && "MatchAddr should be able to fill in BaseReg!");
896 Success=Success;
897 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 }
899 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000900 return false;
901}
Eric Christopher692bf6b2008-09-24 05:32:41 +0000902
Chris Lattner88a5c832008-11-25 07:09:13 +0000903/// MatchAddr - If we can, try to add the value of 'Addr' into the current
904/// addressing mode. If Addr can't be added to AddrMode this returns false and
905/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
906/// or intptr_t for the target.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000907///
Chris Lattner88a5c832008-11-25 07:09:13 +0000908bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000909 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
910 // Fold in immediates if legal for the target.
911 AddrMode.BaseOffs += CI->getSExtValue();
912 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
913 return true;
914 AddrMode.BaseOffs -= CI->getSExtValue();
915 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000916 // If this is a global variable, try to fold it into the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000917 if (AddrMode.BaseGV == 0) {
918 AddrMode.BaseGV = GV;
919 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
920 return true;
921 AddrMode.BaseGV = 0;
922 }
923 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000924 ExtAddrMode BackupAddrMode = AddrMode;
925 unsigned OldSize = AddrModeInsts.size();
926
927 // Check to see if it is possible to fold this operation.
Chris Lattner88a5c832008-11-25 07:09:13 +0000928 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000929 // Okay, it's possible to fold this. Check to see if it is actually
930 // *profitable* to do so. We use a simple cost model to avoid increasing
931 // register pressure too much.
Chris Lattner84d1b402008-11-26 03:02:41 +0000932 if (I->hasOneUse() ||
933 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000934 AddrModeInsts.push_back(I);
935 return true;
936 }
937
938 // It isn't profitable to do this, roll back.
939 //cerr << "NOT FOLDING: " << *I;
940 AddrMode = BackupAddrMode;
941 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000942 }
943 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000944 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000945 return true;
946 } else if (isa<ConstantPointerNull>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000947 // Null pointer gets folded without affecting the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000948 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000949 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000950
Chris Lattnerdd77df32007-04-13 20:30:56 +0000951 // Worse case, the target should support [reg] addressing modes. :)
952 if (!AddrMode.HasBaseReg) {
953 AddrMode.HasBaseReg = true;
Chris Lattner653b2582008-11-26 02:11:11 +0000954 AddrMode.BaseReg = Addr;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000955 // Still check for legality in case the target supports [imm] but not [i+r].
Chris Lattner653b2582008-11-26 02:11:11 +0000956 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000958 AddrMode.HasBaseReg = false;
Chris Lattner653b2582008-11-26 02:11:11 +0000959 AddrMode.BaseReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000960 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000961
Chris Lattnerdd77df32007-04-13 20:30:56 +0000962 // If the base register is already taken, see if we can do [r+r].
963 if (AddrMode.Scale == 0) {
964 AddrMode.Scale = 1;
Chris Lattner653b2582008-11-26 02:11:11 +0000965 AddrMode.ScaledReg = Addr;
966 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000967 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000968 AddrMode.Scale = 0;
Chris Lattner653b2582008-11-26 02:11:11 +0000969 AddrMode.ScaledReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000970 }
971 // Couldn't match.
972 return false;
973}
974
Chris Lattner695d8ec2008-11-26 04:59:11 +0000975
976/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
977/// inline asm call are due to memory operands. If so, return true, otherwise
978/// return false.
979static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
980 const TargetLowering &TLI) {
981 std::vector<InlineAsm::ConstraintInfo>
982 Constraints = IA->ParseConstraints();
983
984 unsigned ArgNo = 1; // ArgNo - The operand of the CallInst.
985 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
986 TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
987
988 // Compute the value type for each operand.
989 switch (OpInfo.Type) {
990 case InlineAsm::isOutput:
991 if (OpInfo.isIndirect)
992 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
993 break;
994 case InlineAsm::isInput:
995 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
996 break;
997 case InlineAsm::isClobber:
998 // Nothing to do.
999 break;
1000 }
1001
1002 // Compute the constraint code and ConstraintType to use.
1003 TLI.ComputeConstraintToUse(OpInfo, SDValue(),
1004 OpInfo.ConstraintType == TargetLowering::C_Memory);
1005
1006 // If this asm operand is our Value*, and if it isn't an indirect memory
1007 // operand, we can't fold it!
1008 if (OpInfo.CallOperandVal == OpVal &&
1009 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1010 !OpInfo.isIndirect))
1011 return false;
1012 }
1013
1014 return true;
1015}
1016
1017
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001018/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1019/// memory use. If we find an obviously non-foldable instruction, return true.
1020/// Add the ultimately found memory instructions to MemoryUses.
1021static bool FindAllMemoryUses(Instruction *I,
1022 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Chris Lattner695d8ec2008-11-26 04:59:11 +00001023 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1024 const TargetLowering &TLI) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001025 // If we already considered this instruction, we're done.
1026 if (!ConsideredInsts.insert(I))
1027 return false;
1028
1029 // If this is an obviously unfoldable instruction, bail out.
1030 if (!MightBeFoldableInst(I))
1031 return true;
1032
1033 // Loop over all the uses, recursively processing them.
1034 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1035 UI != E; ++UI) {
1036 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1037 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1038 continue;
1039 }
1040
1041 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1042 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
1043 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
1044 continue;
1045 }
1046
1047 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1048 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1049 if (IA == 0) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001050
Chris Lattner695d8ec2008-11-26 04:59:11 +00001051 // If this is a memory operand, we're cool, otherwise bail out.
1052 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1053 return true;
1054 continue;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001055 }
1056
Chris Lattner695d8ec2008-11-26 04:59:11 +00001057 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
1058 TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001059 return true;
1060 }
1061
1062 return false;
1063}
Chris Lattner84d1b402008-11-26 03:02:41 +00001064
1065
1066/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1067/// the use site that we're folding it into. If so, there is no cost to
1068/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
1069/// that we know are live at the instruction already.
1070bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1071 Value *KnownLive2) {
1072 // If Val is either of the known-live values, we know it is live!
1073 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1074 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001075
Chris Lattner896617b2008-11-26 03:20:37 +00001076 // All values other than instructions and arguments (e.g. constants) are live.
Chris Lattner84d1b402008-11-26 03:02:41 +00001077 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
1078
1079 // If Val is a constant sized alloca in the entry block, it is live, this is
1080 // true because it is just a reference to the stack/frame pointer, which is
1081 // live for the whole function.
1082 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1083 if (AI->isStaticAlloca())
1084 return true;
1085
Chris Lattner896617b2008-11-26 03:20:37 +00001086 // Check to see if this value is already used in the memory instruction's
1087 // block. If so, it's already live into the block at the very least, so we
1088 // can reasonably fold it.
1089 BasicBlock *MemBB = MemoryInst->getParent();
1090 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1091 UI != E; ++UI)
1092 // We know that uses of arguments and instructions have to be instructions.
1093 if (cast<Instruction>(*UI)->getParent() == MemBB)
1094 return true;
1095
Chris Lattner84d1b402008-11-26 03:02:41 +00001096 return false;
1097}
1098
1099
1100
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001101/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1102/// mode of the machine to fold the specified instruction into a load or store
1103/// that ultimately uses it. However, the specified instruction has multiple
1104/// uses. Given this, it may actually increase register pressure to fold it
1105/// into the load. For example, consider this code:
1106///
1107/// X = ...
1108/// Y = X+1
1109/// use(Y) -> nonload/store
1110/// Z = Y+1
1111/// load Z
1112///
1113/// In this case, Y has multiple uses, and can be folded into the load of Z
1114/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1115/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1116/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1117/// number of computations either.
1118///
1119/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1120/// X was live across 'load Z' for other reasons, we actually *would* want to
Chris Lattner653b2582008-11-26 02:11:11 +00001121/// fold the addressing mode in the Z case. This would make Y die earlier.
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001122bool AddressingModeMatcher::
Chris Lattner84d1b402008-11-26 03:02:41 +00001123IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1124 ExtAddrMode &AMAfter) {
Chris Lattnerab8b7942008-11-26 22:16:44 +00001125 if (IgnoreProfitability) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001126
Chris Lattner84d1b402008-11-26 03:02:41 +00001127 // AMBefore is the addressing mode before this instruction was folded into it,
1128 // and AMAfter is the addressing mode after the instruction was folded. Get
1129 // the set of registers referenced by AMAfter and subtract out those
1130 // referenced by AMBefore: this is the set of values which folding in this
1131 // address extends the lifetime of.
1132 //
1133 // Note that there are only two potential values being referenced here,
1134 // BaseReg and ScaleReg (global addresses are always available, as are any
1135 // folded immediates).
1136 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1137
1138 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1139 // lifetime wasn't extended by adding this instruction.
1140 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1141 BaseReg = 0;
1142 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1143 ScaledReg = 0;
1144
1145 // If folding this instruction (and it's subexprs) didn't extend any live
1146 // ranges, we're ok with it.
1147 if (BaseReg == 0 && ScaledReg == 0)
1148 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001149
1150 // If all uses of this instruction are ultimately load/store/inlineasm's,
1151 // check to see if their addressing modes will include this instruction. If
1152 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1153 // uses.
1154 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1155 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Chris Lattner695d8ec2008-11-26 04:59:11 +00001156 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001157 return false; // Has a non-memory, non-foldable use!
1158
1159 // Now that we know that all uses of this instruction are part of a chain of
1160 // computation involving only operations that could theoretically be folded
1161 // into a memory use, loop over each of these uses and see if they could
1162 // *actually* fold the instruction.
1163 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1164 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1165 Instruction *User = MemoryUses[i].first;
1166 unsigned OpNo = MemoryUses[i].second;
1167
1168 // Get the access type of this use. If the use isn't a pointer, we don't
1169 // know what it accesses.
1170 Value *Address = User->getOperand(OpNo);
1171 if (!isa<PointerType>(Address->getType()))
1172 return false;
1173 const Type *AddressAccessTy =
1174 cast<PointerType>(Address->getType())->getElementType();
1175
1176 // Do a match against the root of this address, ignoring profitability. This
1177 // will tell us if the addressing mode for the memory operation will
1178 // *actually* cover the shared instruction.
1179 ExtAddrMode Result;
1180 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Chris Lattner896617b2008-11-26 03:20:37 +00001181 MemoryInst, Result);
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001182 Matcher.IgnoreProfitability = true;
1183 bool Success = Matcher.MatchAddr(Address, 0);
1184 Success = Success; assert(Success && "Couldn't select *anything*?");
1185
1186 // If the match didn't cover I, then it won't be shared by it.
1187 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1188 I) == MatchedAddrModeInsts.end())
1189 return false;
1190
1191 MatchedAddrModeInsts.clear();
1192 }
1193
1194 return true;
1195}
1196
Chris Lattnerdd77df32007-04-13 20:30:56 +00001197
Chris Lattner88a5c832008-11-25 07:09:13 +00001198//===----------------------------------------------------------------------===//
1199// Memory Optimization
1200//===----------------------------------------------------------------------===//
1201
Chris Lattnerdd77df32007-04-13 20:30:56 +00001202/// IsNonLocalValue - Return true if the specified values are defined in a
1203/// different basic block than BB.
1204static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1205 if (Instruction *I = dyn_cast<Instruction>(V))
1206 return I->getParent() != BB;
1207 return false;
1208}
1209
Chris Lattner88a5c832008-11-25 07:09:13 +00001210/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00001211/// addressing modes that can do significant amounts of computation. As such,
1212/// instruction selection will try to get the load or store to do as much
1213/// computation as possible for the program. The problem is that isel can only
1214/// see within a single block. As such, we sink as much legal addressing mode
1215/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00001216///
1217/// This method is used to optimize both load/store and inline asms with memory
1218/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00001219bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +00001220 const Type *AccessTy,
1221 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001222 // Figure out what addressing mode will be built up for this operation.
1223 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +00001224 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1225 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001226
Chris Lattnerdd77df32007-04-13 20:30:56 +00001227 // Check to see if any of the instructions supersumed by this addr mode are
1228 // non-local to I's BB.
1229 bool AnyNonLocal = false;
1230 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00001231 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001232 AnyNonLocal = true;
1233 break;
1234 }
1235 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001236
Chris Lattnerdd77df32007-04-13 20:30:56 +00001237 // If all the instructions matched are already in this BB, don't do anything.
1238 if (!AnyNonLocal) {
1239 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1240 return false;
1241 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001242
Chris Lattnerdd77df32007-04-13 20:30:56 +00001243 // Insert this computation right after this user. Since our caller is
1244 // scanning from the top of the BB to the bottom, reuse of the expr are
1245 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +00001246 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001247
Chris Lattnerdd77df32007-04-13 20:30:56 +00001248 // Now that we determined the addressing expression we want to use and know
1249 // that we have to sink it into this block. Check to see if we have already
1250 // done this for some other load/store instr in this block. If so, reuse the
1251 // computation.
1252 Value *&SunkAddr = SunkAddrs[Addr];
1253 if (SunkAddr) {
Chris Lattner65c02fb2009-02-12 06:56:08 +00001254 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
1255 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001256 if (SunkAddr->getType() != Addr->getType())
1257 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1258 } else {
Chris Lattner65c02fb2009-02-12 06:56:08 +00001259 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
1260 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001261 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001262
Chris Lattnerdd77df32007-04-13 20:30:56 +00001263 Value *Result = 0;
1264 // Start with the scale value.
1265 if (AddrMode.Scale) {
1266 Value *V = AddrMode.ScaledReg;
1267 if (V->getType() == IntPtrTy) {
1268 // done.
1269 } else if (isa<PointerType>(V->getType())) {
1270 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1271 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1272 cast<IntegerType>(V->getType())->getBitWidth()) {
1273 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1274 } else {
1275 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1276 }
1277 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001278 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +00001279 AddrMode.Scale),
1280 "sunkaddr", InsertPt);
1281 Result = V;
1282 }
1283
1284 // Add in the base register.
1285 if (AddrMode.BaseReg) {
1286 Value *V = AddrMode.BaseReg;
1287 if (V->getType() != IntPtrTy)
1288 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1289 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001290 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001291 else
1292 Result = V;
1293 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001294
Chris Lattnerdd77df32007-04-13 20:30:56 +00001295 // Add in the BaseGV if present.
1296 if (AddrMode.BaseGV) {
1297 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1298 InsertPt);
1299 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001300 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001301 else
1302 Result = V;
1303 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001304
Chris Lattnerdd77df32007-04-13 20:30:56 +00001305 // Add in the Base Offset if present.
1306 if (AddrMode.BaseOffs) {
1307 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1308 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001309 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001310 else
1311 Result = V;
1312 }
1313
1314 if (Result == 0)
1315 SunkAddr = Constant::getNullValue(Addr->getType());
1316 else
1317 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1318 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001319
Chris Lattner896617b2008-11-26 03:20:37 +00001320 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001321
Chris Lattnerdd77df32007-04-13 20:30:56 +00001322 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +00001323 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001324 return true;
1325}
1326
Evan Cheng9bf12b52008-02-26 02:42:37 +00001327/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001328/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001329/// possible / profitable.
1330bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1331 DenseMap<Value*,Value*> &SunkAddrs) {
1332 bool MadeChange = false;
1333 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1334
1335 // Do a prepass over the constraints, canonicalizing them, and building up the
1336 // ConstraintOperands list.
1337 std::vector<InlineAsm::ConstraintInfo>
1338 ConstraintInfos = IA->ParseConstraints();
1339
1340 /// ConstraintOperands - Information about all of the constraints.
1341 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1342 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1343 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1344 ConstraintOperands.
1345 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1346 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1347
1348 // Compute the value type for each operand.
1349 switch (OpInfo.Type) {
1350 case InlineAsm::isOutput:
1351 if (OpInfo.isIndirect)
1352 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1353 break;
1354 case InlineAsm::isInput:
1355 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1356 break;
1357 case InlineAsm::isClobber:
1358 // Nothing to do.
1359 break;
1360 }
1361
1362 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +00001363 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1364 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001365
Eli Friedman9ec80952008-02-26 18:37:49 +00001366 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1367 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001368 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +00001369 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001370 }
1371 }
1372
1373 return MadeChange;
1374}
1375
Evan Chengbdcb7262007-12-05 23:58:20 +00001376bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1377 BasicBlock *DefBB = I->getParent();
1378
1379 // If both result of the {s|z}xt and its source are live out, rewrite all
1380 // other uses of the source with result of extension.
1381 Value *Src = I->getOperand(0);
1382 if (Src->hasOneUse())
1383 return false;
1384
Evan Cheng696e5c02007-12-13 07:50:36 +00001385 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001386 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001387 return false;
1388
Evan Cheng772de512007-12-12 00:51:06 +00001389 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001390 // this block.
1391 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001392 return false;
1393
Evan Chengbdcb7262007-12-05 23:58:20 +00001394 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001395 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001396 UI != E; ++UI) {
1397 Instruction *User = cast<Instruction>(*UI);
1398
1399 // Figure out which BB this ext is used in.
1400 BasicBlock *UserBB = User->getParent();
1401 if (UserBB == DefBB) continue;
1402 DefIsLiveOut = true;
1403 break;
1404 }
1405 if (!DefIsLiveOut)
1406 return false;
1407
Evan Cheng765dff22007-12-12 02:53:41 +00001408 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001409 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001410 UI != E; ++UI) {
1411 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001412 BasicBlock *UserBB = User->getParent();
1413 if (UserBB == DefBB) continue;
1414 // Be conservative. We don't want this xform to end up introducing
1415 // reloads just before load / store instructions.
1416 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001417 return false;
1418 }
1419
Evan Chengbdcb7262007-12-05 23:58:20 +00001420 // InsertedTruncs - Only insert one trunc in each block once.
1421 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1422
1423 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001424 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001425 UI != E; ++UI) {
1426 Use &TheUse = UI.getUse();
1427 Instruction *User = cast<Instruction>(*UI);
1428
1429 // Figure out which BB this ext is used in.
1430 BasicBlock *UserBB = User->getParent();
1431 if (UserBB == DefBB) continue;
1432
1433 // Both src and def are live in this block. Rewrite the use.
1434 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1435
1436 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001437 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001438
Evan Chengbdcb7262007-12-05 23:58:20 +00001439 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1440 }
1441
1442 // Replace a use of the {s|z}ext source with a use of the result.
1443 TheUse = InsertedTrunc;
1444
1445 MadeChange = true;
1446 }
1447
1448 return MadeChange;
1449}
1450
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001451// In this pass we look for GEP and cast instructions that are used
1452// across basic blocks and rewrite them to improve basic-block-at-a-time
1453// selection.
1454bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1455 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001456
Evan Chengab631522008-12-19 18:03:11 +00001457 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001458 TerminatorInst *BBTI = BB.getTerminator();
1459 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +00001460 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1461 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1462 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1463 SplitEdgeNicely(BBTI, i, BackEdges, this);
1464 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001465 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001466
Chris Lattnerdd77df32007-04-13 20:30:56 +00001467 // Keep track of non-local addresses that have been sunk into this block.
1468 // This allows us to avoid inserting duplicate code for blocks with multiple
1469 // load/stores of the same address.
1470 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001472 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1473 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001474
Chris Lattnerdd77df32007-04-13 20:30:56 +00001475 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001476 // If the source of the cast is a constant, then this should have
1477 // already been constant folded. The only reason NOT to constant fold
1478 // it is if something (e.g. LSR) was careful to place the constant
1479 // evaluation in a block other than then one that uses it (e.g. to hoist
1480 // the address of globals out of a loop). If this is the case, we don't
1481 // want to forward-subst the cast.
1482 if (isa<Constant>(CI->getOperand(0)))
1483 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001484
Evan Chengbdcb7262007-12-05 23:58:20 +00001485 bool Change = false;
1486 if (TLI) {
1487 Change = OptimizeNoopCopyExpression(CI, *TLI);
1488 MadeChange |= Change;
1489 }
1490
Evan Cheng55e641b2008-03-19 22:02:26 +00001491 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001492 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001493 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1494 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001495 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1496 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001497 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1498 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001499 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1500 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001501 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1502 SI->getOperand(0)->getType(),
1503 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001504 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001505 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001506 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001507 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001508 GEPI->getName(), GEPI);
1509 GEPI->replaceAllUsesWith(NC);
1510 GEPI->eraseFromParent();
1511 MadeChange = true;
1512 BBI = NC;
1513 }
1514 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1515 // If we found an inline asm expession, and if the target knows how to
1516 // lower it to normal LLVM code, do so now.
1517 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001518 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001519 TLI->getTargetMachine().getTargetAsmInfo()) {
Chris Lattner65c02fb2009-02-12 06:56:08 +00001520 if (TAI->ExpandInlineAsm(CI)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001521 BBI = BB.begin();
Chris Lattner65c02fb2009-02-12 06:56:08 +00001522 // Avoid processing instructions out of order, which could cause
1523 // reuse before a value is defined.
1524 SunkAddrs.clear();
1525 } else
Evan Cheng9bf12b52008-02-26 02:42:37 +00001526 // Sink address computing for memory operands into the block.
1527 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001528 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001529 }
1530 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001531
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001532 return MadeChange;
1533}