blob: 9bf39911b6c697f80a2059766b225f506fd9f2a8 [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"
Evan Cheng9bf12b52008-02-26 02:42:37 +000032#include "llvm/Support/CallSite.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000033#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000034#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000036#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000037using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000038using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000039
Eric Christopher692bf6b2008-09-24 05:32:41 +000040namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
42 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// transformation profitability.
44 const TargetLowering *TLI;
45 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000046 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000047 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000048 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000050
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000051 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000052 bool EliminateMostlyEmptyBlocks(Function &F);
53 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
54 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000055 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000056 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
57 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000058 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
59 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000060 bool OptimizeExtUses(Instruction *I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000061 };
62}
Devang Patel794fd752007-05-01 21:15:47 +000063
Devang Patel19974732007-05-03 01:11:54 +000064char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000065static RegisterPass<CodeGenPrepare> X("codegenprepare",
66 "Optimize for code generation");
67
68FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
69 return new CodeGenPrepare(TLI);
70}
71
72
73bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000075
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000076 // First pass, eliminate blocks that contain only PHI nodes and an
77 // unconditional branch.
78 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000079
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000080 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000081 while (MadeChange) {
82 MadeChange = false;
83 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
84 MadeChange |= OptimizeBlock(*BB);
85 EverMadeChange |= MadeChange;
86 }
87 return EverMadeChange;
88}
89
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000090/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
Eric Christopher692bf6b2008-09-24 05:32:41 +000091/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000092/// often split edges in ways that are non-optimal for isel. Start by
93/// eliminating these blocks so we can split them the way we want them.
94bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
95 bool MadeChange = false;
96 // Note that this intentionally skips the entry block.
97 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
98 BasicBlock *BB = I++;
99
100 // If this block doesn't end with an uncond branch, ignore it.
101 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
102 if (!BI || !BI->isUnconditional())
103 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000104
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000105 // If the instruction before the branch isn't a phi node, then other stuff
106 // is happening here.
107 BasicBlock::iterator BBI = BI;
108 if (BBI != BB->begin()) {
109 --BBI;
110 if (!isa<PHINode>(BBI)) continue;
111 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000112
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000113 // Do not break infinite loops.
114 BasicBlock *DestBB = BI->getSuccessor(0);
115 if (DestBB == BB)
116 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000117
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118 if (!CanMergeBlocks(BB, DestBB))
119 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000120
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000121 EliminateMostlyEmptyBlock(BB);
122 MadeChange = true;
123 }
124 return MadeChange;
125}
126
127/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
128/// single uncond branch between them, and BB contains no other non-phi
129/// instructions.
130bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
131 const BasicBlock *DestBB) const {
132 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
133 // the successor. If there are more complex condition (e.g. preheaders),
134 // don't mess around with them.
135 BasicBlock::const_iterator BBI = BB->begin();
136 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
137 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
138 UI != E; ++UI) {
139 const Instruction *User = cast<Instruction>(*UI);
140 if (User->getParent() != DestBB || !isa<PHINode>(User))
141 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000142 // If User is inside DestBB block and it is a PHINode then check
143 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000144 // a complex condition (e.g. preheaders) we want to avoid here.
145 if (User->getParent() == DestBB) {
146 if (const PHINode *UPN = dyn_cast<PHINode>(User))
147 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
148 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
149 if (Insn && Insn->getParent() == BB &&
150 Insn->getParent() != UPN->getIncomingBlock(I))
151 return false;
152 }
153 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000154 }
155 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000156
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000157 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
158 // and DestBB may have conflicting incoming values for the block. If so, we
159 // can't merge the block.
160 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
161 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000162
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000164 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
166 // It is faster to get preds from a PHI than with pred_iterator.
167 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
168 BBPreds.insert(BBPN->getIncomingBlock(i));
169 } else {
170 BBPreds.insert(pred_begin(BB), pred_end(BB));
171 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 // Walk the preds of DestBB.
174 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
175 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
176 if (BBPreds.count(Pred)) { // Common predecessor?
177 BBI = DestBB->begin();
178 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
179 const Value *V1 = PN->getIncomingValueForBlock(Pred);
180 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000181
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000182 // If V2 is a phi node in BB, look up what the mapped value will be.
183 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
184 if (V2PN->getParent() == BB)
185 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000186
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 // If there is a conflict, bail out.
188 if (V1 != V2) return false;
189 }
190 }
191 }
192
193 return true;
194}
195
196
197/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
198/// an unconditional branch in it.
199void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
200 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
201 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000202
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000204
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 // If the destination block has a single pred, then this is a trivial edge,
206 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000207 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
208 // Remember if SinglePred was the entry block of the function. If so, we
209 // will need to move BB back to the entry position.
210 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Chris Lattner3c4f8b92008-11-27 07:54:12 +0000211 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000212
213 if (isEntry && BB != &BB->getParent()->getEntryBlock())
214 BB->moveBefore(&BB->getParent()->getEntryBlock());
215
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000216 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
217 return;
218 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000219
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000220 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
221 // to handle the new incoming edges it is about to have.
222 PHINode *PN;
223 for (BasicBlock::iterator BBI = DestBB->begin();
224 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
225 // Remove the incoming value for BB, and remember it.
226 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 // Two options: either the InVal is a phi node defined in BB or it is some
229 // value that dominates BB.
230 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
231 if (InValPhi && InValPhi->getParent() == BB) {
232 // Add all of the input values of the input PHI as inputs of this phi.
233 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
234 PN->addIncoming(InValPhi->getIncomingValue(i),
235 InValPhi->getIncomingBlock(i));
236 } else {
237 // Otherwise, add one instance of the dominating value for each edge that
238 // we will be adding.
239 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
240 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
241 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
242 } else {
243 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
244 PN->addIncoming(InVal, *PI);
245 }
246 }
247 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000248
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000249 // The PHIs are now updated, change everything that refers to BB to use
250 // DestBB and remove BB.
251 BB->replaceAllUsesWith(DestBB);
252 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000253
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000254 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
255}
256
257
Chris Lattnerebe80752007-12-24 19:32:55 +0000258/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000259/// successor if it will improve codegen. We only do this if the successor has
260/// phi nodes (otherwise critical edges are ok). If there is already another
261/// predecessor of the succ that is empty (and thus has no phi nodes), use it
262/// instead of introducing a new block.
263static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
264 BasicBlock *TIBB = TI->getParent();
265 BasicBlock *Dest = TI->getSuccessor(SuccNum);
266 assert(isa<PHINode>(Dest->begin()) &&
267 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Chris Lattnerebe80752007-12-24 19:32:55 +0000269 // As a hack, never split backedges of loops. Even though the copy for any
270 // PHIs inserted on the backedge would be dead for exits from the loop, we
271 // assume that the cost of *splitting* the backedge would be too high.
Chris Lattnerff26ab22007-12-25 19:06:45 +0000272 if (Dest == TIBB)
Chris Lattnerebe80752007-12-24 19:32:55 +0000273 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000274
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000275 /// TIPHIValues - This array is lazily computed to determine the values of
276 /// PHIs in Dest that TI would provide.
Chris Lattnerebe80752007-12-24 19:32:55 +0000277 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000278
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000279 // Check to see if Dest has any blocks that can be used as a split edge for
280 // this terminator.
281 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
282 BasicBlock *Pred = *PI;
283 // To be usable, the pred has to end with an uncond branch to the dest.
284 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
285 if (!PredBr || !PredBr->isUnconditional() ||
286 // Must be empty other than the branch.
Dale Johannesen6603a1b2007-05-08 01:01:04 +0000287 &Pred->front() != PredBr ||
288 // Cannot be the entry block; its label does not get emitted.
289 Pred == &(Dest->getParent()->getEntryBlock()))
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000290 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000291
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000292 // Finally, since we know that Dest has phi nodes in it, we have to make
293 // sure that jumping to Pred will have the same affect as going to Dest in
294 // terms of PHI values.
295 PHINode *PN;
296 unsigned PHINo = 0;
297 bool FoundMatch = true;
298 for (BasicBlock::iterator I = Dest->begin();
299 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
300 if (PHINo == TIPHIValues.size())
301 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000302
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000303 // If the PHI entry doesn't work, we can't use this pred.
304 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
305 FoundMatch = false;
306 break;
307 }
308 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000310 // If we found a workable predecessor, change TI to branch to Succ.
311 if (FoundMatch) {
312 Dest->removePredecessor(TIBB);
313 TI->setSuccessor(SuccNum, Pred);
314 return;
315 }
316 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000317
318 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000319}
320
Chris Lattnerdd77df32007-04-13 20:30:56 +0000321/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
322/// copy (e.g. it's casting from one pointer type to another, int->uint, or
323/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000324/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000325///
326/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000327///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000328static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000329 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000330 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
331 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000332
Chris Lattnerdd77df32007-04-13 20:30:56 +0000333 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000334 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000335 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000336
Chris Lattnerdd77df32007-04-13 20:30:56 +0000337 // If this is an extension, it will be a zero or sign extension, which
338 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000339 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000340
Chris Lattnerdd77df32007-04-13 20:30:56 +0000341 // If these values will be promoted, find out what they will be promoted
342 // to. This helps us consider truncates on PPC as noop copies when they
343 // are.
344 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
345 SrcVT = TLI.getTypeToTransformTo(SrcVT);
346 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
347 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000348
Chris Lattnerdd77df32007-04-13 20:30:56 +0000349 // If, after promotion, these are the same types, this is a noop copy.
350 if (SrcVT != DstVT)
351 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000353 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000355 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000356 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000357
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000358 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000359 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000360 UI != E; ) {
361 Use &TheUse = UI.getUse();
362 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000364 // Figure out which BB this cast is used in. For PHI's this is the
365 // appropriate predecessor block.
366 BasicBlock *UserBB = User->getParent();
367 if (PHINode *PN = dyn_cast<PHINode>(User)) {
368 unsigned OpVal = UI.getOperandNo()/2;
369 UserBB = PN->getIncomingBlock(OpVal);
370 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000371
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000372 // Preincrement use iterator so we don't invalidate it.
373 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000374
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000375 // If this user is in the same block as the cast, don't change the cast.
376 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000377
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000378 // If we have already inserted a cast into this block, use it.
379 CastInst *&InsertedCast = InsertedCasts[UserBB];
380
381 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000382 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
384 InsertedCast =
385 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000386 InsertPt);
387 MadeChange = true;
388 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
Dale Johannesence0b2372007-06-12 16:50:17 +0000390 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000391 TheUse = InsertedCast;
392 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000393
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000394 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000395 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000396 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000397 MadeChange = true;
398 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000399
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000400 return MadeChange;
401}
402
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000404/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000405/// a clear win except on targets with multiple condition code registers
406/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000407///
408/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000409static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000410 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000411
Dale Johannesence0b2372007-06-12 16:50:17 +0000412 /// InsertedCmp - Only insert a cmp in each block once.
413 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000414
Dale Johannesence0b2372007-06-12 16:50:17 +0000415 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000416 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000417 UI != E; ) {
418 Use &TheUse = UI.getUse();
419 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000420
Dale Johannesence0b2372007-06-12 16:50:17 +0000421 // Preincrement use iterator so we don't invalidate it.
422 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Dale Johannesence0b2372007-06-12 16:50:17 +0000424 // Don't bother for PHI nodes.
425 if (isa<PHINode>(User))
426 continue;
427
428 // Figure out which BB this cmp is used in.
429 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000430
Dale Johannesence0b2372007-06-12 16:50:17 +0000431 // If this user is in the same block as the cmp, don't change the cmp.
432 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Dale Johannesence0b2372007-06-12 16:50:17 +0000434 // If we have already inserted a cmp into this block, use it.
435 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
436
437 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000438 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000439
440 InsertedCmp =
441 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000442 CI->getOperand(1), "", InsertPt);
443 MadeChange = true;
444 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Dale Johannesence0b2372007-06-12 16:50:17 +0000446 // Replace a use of the cmp with a use of the new cmp.
447 TheUse = InsertedCmp;
448 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 // If we removed all uses, nuke the cmp.
451 if (CI->use_empty())
452 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Dale Johannesence0b2372007-06-12 16:50:17 +0000454 return MadeChange;
455}
456
Chris Lattner85fa13c2008-11-24 22:44:16 +0000457/// EraseDeadInstructions - Erase any dead instructions, recursively.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000458static void EraseDeadInstructions(Value *V) {
459 Instruction *I = dyn_cast<Instruction>(V);
460 if (!I || !I->use_empty()) return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Chris Lattnerdd77df32007-04-13 20:30:56 +0000462 SmallPtrSet<Instruction*, 16> Insts;
463 Insts.insert(I);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
Chris Lattnerdd77df32007-04-13 20:30:56 +0000465 while (!Insts.empty()) {
466 I = *Insts.begin();
467 Insts.erase(I);
468 if (isInstructionTriviallyDead(I)) {
469 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
470 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
471 Insts.insert(U);
472 I->eraseFromParent();
473 }
474 }
475}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476
Chris Lattner88a5c832008-11-25 07:09:13 +0000477//===----------------------------------------------------------------------===//
478// Addressing Mode Analysis and Optimization
479//===----------------------------------------------------------------------===//
480
Dan Gohman844731a2008-05-13 00:00:25 +0000481namespace {
Chris Lattner4744d852008-11-24 22:40:05 +0000482 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
483 /// which holds actual Value*'s for register values.
484 struct ExtAddrMode : public TargetLowering::AddrMode {
485 Value *BaseReg;
486 Value *ScaledReg;
487 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
488 void print(OStream &OS) const;
489 void dump() const {
490 print(cerr);
491 cerr << '\n';
492 }
493 };
494} // end anonymous namespace
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000496static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
Chris Lattner4744d852008-11-24 22:40:05 +0000497 AM.print(OS);
498 return OS;
499}
Chris Lattnerdd77df32007-04-13 20:30:56 +0000500
Chris Lattner4744d852008-11-24 22:40:05 +0000501void ExtAddrMode::print(OStream &OS) const {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000502 bool NeedPlus = false;
503 OS << "[";
Chris Lattner4744d852008-11-24 22:40:05 +0000504 if (BaseGV)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000505 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000506 << "GV:%" << BaseGV->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattner4744d852008-11-24 22:40:05 +0000508 if (BaseOffs)
509 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Chris Lattner4744d852008-11-24 22:40:05 +0000511 if (BaseReg)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000512 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000513 << "Base:%" << BaseReg->getName(), NeedPlus = true;
514 if (Scale)
Chris Lattnerdd77df32007-04-13 20:30:56 +0000515 OS << (NeedPlus ? " + " : "")
Chris Lattner4744d852008-11-24 22:40:05 +0000516 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000517
Chris Lattner4744d852008-11-24 22:40:05 +0000518 OS << ']';
Dan Gohman844731a2008-05-13 00:00:25 +0000519}
520
Chris Lattner88a5c832008-11-25 07:09:13 +0000521namespace {
522/// AddressingModeMatcher - This class exposes a single public method, which is
523/// used to construct a "maximal munch" of the addressing mode for the target
524/// specified by TLI for an access to "V" with an access type of AccessTy. This
525/// returns the addressing mode that is actually matched by value, but also
526/// returns the list of instructions involved in that addressing computation in
527/// AddrModeInsts.
528class AddressingModeMatcher {
529 SmallVectorImpl<Instruction*> &AddrModeInsts;
530 const TargetLowering &TLI;
Chris Lattner896617b2008-11-26 03:20:37 +0000531
532 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
533 /// the memory instruction that we're computing this address for.
Chris Lattner88a5c832008-11-25 07:09:13 +0000534 const Type *AccessTy;
Chris Lattner896617b2008-11-26 03:20:37 +0000535 Instruction *MemoryInst;
536
537 /// AddrMode - This is the addressing mode that we're building up. This is
538 /// part of the return value of this addressing mode matching stuff.
Chris Lattner88a5c832008-11-25 07:09:13 +0000539 ExtAddrMode &AddrMode;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000540
541 /// IgnoreProfitability - This is set to true when we should not do
542 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
543 /// always returns true.
544 bool IgnoreProfitability;
545
Chris Lattner88a5c832008-11-25 07:09:13 +0000546 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
Chris Lattner896617b2008-11-26 03:20:37 +0000547 const TargetLowering &T, const Type *AT,
548 Instruction *MI, ExtAddrMode &AM)
549 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000550 IgnoreProfitability = false;
551 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000552public:
553
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000554 /// Match - Find the maximal addressing mode that a load/store of V can fold,
555 /// give an access type of AccessTy. This returns a list of involved
556 /// instructions in AddrModeInsts.
Chris Lattner896617b2008-11-26 03:20:37 +0000557 static ExtAddrMode Match(Value *V, const Type *AccessTy,
558 Instruction *MemoryInst,
Chris Lattner88a5c832008-11-25 07:09:13 +0000559 SmallVectorImpl<Instruction*> &AddrModeInsts,
560 const TargetLowering &TLI) {
561 ExtAddrMode Result;
562
563 bool Success =
Chris Lattner896617b2008-11-26 03:20:37 +0000564 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
565 MemoryInst, Result).MatchAddr(V, 0);
Chris Lattner88a5c832008-11-25 07:09:13 +0000566 Success = Success; assert(Success && "Couldn't select *anything*?");
567 return Result;
568 }
569private:
Chris Lattner3b485012008-11-25 07:25:26 +0000570 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Chris Lattner88a5c832008-11-25 07:09:13 +0000571 bool MatchAddr(Value *V, unsigned Depth);
572 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
Chris Lattner84d1b402008-11-26 03:02:41 +0000573 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
574 ExtAddrMode &AMBefore,
575 ExtAddrMode &AMAfter);
576 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Chris Lattner88a5c832008-11-25 07:09:13 +0000577};
578} // end anonymous namespace
579
580/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
581/// Return true and update AddrMode if this addr mode is legal for the target,
Chris Lattner85fa13c2008-11-24 22:44:16 +0000582/// false if not.
Chris Lattner3b485012008-11-25 07:25:26 +0000583bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
584 unsigned Depth) {
585 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
586 // mode. Just process that directly.
587 if (Scale == 1)
588 return MatchAddr(ScaleReg, Depth);
589
590 // If the scale is 0, it takes nothing to add this.
591 if (Scale == 0)
592 return true;
593
Chris Lattner85fa13c2008-11-24 22:44:16 +0000594 // If we already have a scale of this value, we can add to it, otherwise, we
595 // need an available scale field.
596 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
597 return false;
598
Chris Lattner088a1e82008-11-25 04:42:10 +0000599 ExtAddrMode TestAddrMode = AddrMode;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000600
601 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
602 // [A+B + A*7] -> [B+A*8].
Chris Lattner088a1e82008-11-25 04:42:10 +0000603 TestAddrMode.Scale += Scale;
604 TestAddrMode.ScaledReg = ScaleReg;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000605
Chris Lattner088a1e82008-11-25 04:42:10 +0000606 // If the new address isn't legal, bail out.
607 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
608 return false;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000609
Chris Lattner088a1e82008-11-25 04:42:10 +0000610 // It was legal, so commit it.
611 AddrMode = TestAddrMode;
612
613 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
614 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
615 // X*Scale + C*Scale to addr mode.
616 ConstantInt *CI; Value *AddLHS;
617 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
618 TestAddrMode.ScaledReg = AddLHS;
619 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
620
621 // If this addressing mode is legal, commit it and remember that we folded
622 // this instruction.
623 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
624 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
625 AddrMode = TestAddrMode;
Chris Lattner88a5c832008-11-25 07:09:13 +0000626 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000627 }
Chris Lattner85fa13c2008-11-24 22:44:16 +0000628 }
629
Chris Lattner088a1e82008-11-25 04:42:10 +0000630 // Otherwise, not (x+c)*scale, just return what we have.
631 return true;
Chris Lattner85fa13c2008-11-24 22:44:16 +0000632}
633
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000634/// MightBeFoldableInst - This is a little filter, which returns true if an
635/// addressing computation involving I might be folded into a load/store
636/// accessing it. This doesn't need to be perfect, but needs to accept at least
637/// the set of instructions that MatchOperationAddr can.
638static bool MightBeFoldableInst(Instruction *I) {
639 switch (I->getOpcode()) {
640 case Instruction::BitCast:
641 // Don't touch identity bitcasts.
642 if (I->getType() == I->getOperand(0)->getType())
643 return false;
644 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
645 case Instruction::PtrToInt:
646 // PtrToInt is always a noop, as we know that the int type is pointer sized.
647 return true;
648 case Instruction::IntToPtr:
649 // We know the input is intptr_t, so this is foldable.
650 return true;
651 case Instruction::Add:
652 return true;
653 case Instruction::Mul:
654 case Instruction::Shl:
655 // Can only handle X*C and X << C.
656 return isa<ConstantInt>(I->getOperand(1));
657 case Instruction::GetElementPtr:
658 return true;
659 default:
660 return false;
661 }
662}
663
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000664
Chris Lattner88a5c832008-11-25 07:09:13 +0000665/// MatchOperationAddr - Given an instruction or constant expr, see if we can
666/// fold the operation into the addressing mode. If so, update the addressing
667/// mode and return true, otherwise return false without modifying AddrMode.
668bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
669 unsigned Depth) {
670 // Avoid exponential behavior on extremely deep expression trees.
671 if (Depth >= 5) return false;
672
Chris Lattnerdd77df32007-04-13 20:30:56 +0000673 switch (Opcode) {
674 case Instruction::PtrToInt:
675 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Chris Lattner88a5c832008-11-25 07:09:13 +0000676 return MatchAddr(AddrInst->getOperand(0), Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000677 case Instruction::IntToPtr:
678 // This inttoptr is a no-op if the integer type is pointer sized.
679 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Chris Lattner88a5c832008-11-25 07:09:13 +0000680 TLI.getPointerTy())
681 return MatchAddr(AddrInst->getOperand(0), Depth);
682 return false;
Chris Lattner2efbbb32008-11-26 00:26:16 +0000683 case Instruction::BitCast:
684 // BitCast is always a noop, and we can handle it as long as it is
685 // int->int or pointer->pointer (we don't want int<->fp or something).
686 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
687 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
688 // Don't touch identity bitcasts. These were probably put here by LSR,
689 // and we don't want to mess around with them. Assume it knows what it
690 // is doing.
691 AddrInst->getOperand(0)->getType() != AddrInst->getType())
692 return MatchAddr(AddrInst->getOperand(0), Depth);
693 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000694 case Instruction::Add: {
695 // Check to see if we can merge in the RHS then the LHS. If so, we win.
696 ExtAddrMode BackupAddrMode = AddrMode;
697 unsigned OldSize = AddrModeInsts.size();
Chris Lattner88a5c832008-11-25 07:09:13 +0000698 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
699 MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000700 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000701
Chris Lattnerdd77df32007-04-13 20:30:56 +0000702 // Restore the old addr mode info.
703 AddrMode = BackupAddrMode;
704 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000705
Chris Lattnerdd77df32007-04-13 20:30:56 +0000706 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Chris Lattner88a5c832008-11-25 07:09:13 +0000707 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
708 MatchAddr(AddrInst->getOperand(1), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000709 return true;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000710
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 // Otherwise we definitely can't merge the ADD in.
712 AddrMode = BackupAddrMode;
713 AddrModeInsts.resize(OldSize);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000714 break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000715 }
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000716 //case Instruction::Or:
717 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
718 //break;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000719 case Instruction::Mul:
720 case Instruction::Shl: {
Chris Lattner7ad1c732008-11-25 04:47:41 +0000721 // Can only handle X*C and X << C.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000722 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Chris Lattner88a5c832008-11-25 07:09:13 +0000723 if (!RHS) return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724 int64_t Scale = RHS->getSExtValue();
725 if (Opcode == Instruction::Shl)
726 Scale = 1 << Scale;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000727
Chris Lattner3b485012008-11-25 07:25:26 +0000728 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000729 }
730 case Instruction::GetElementPtr: {
731 // Scan the GEP. We check it if it contains constant offsets and at most
732 // one variable offset.
733 int VariableOperand = -1;
734 unsigned VariableScale = 0;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000735
Chris Lattnerdd77df32007-04-13 20:30:56 +0000736 int64_t ConstantOffset = 0;
737 const TargetData *TD = TLI.getTargetData();
738 gep_type_iterator GTI = gep_type_begin(AddrInst);
739 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
740 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
741 const StructLayout *SL = TD->getStructLayout(STy);
742 unsigned Idx =
Chris Lattner88a5c832008-11-25 07:09:13 +0000743 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
Chris Lattnerdd77df32007-04-13 20:30:56 +0000744 ConstantOffset += SL->getElementOffset(Idx);
745 } else {
Duncan Sands514ab342007-11-01 20:53:16 +0000746 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000747 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
748 ConstantOffset += CI->getSExtValue()*TypeSize;
749 } else if (TypeSize) { // Scales of zero don't do anything.
750 // We only allow one variable index at the moment.
Chris Lattner88a5c832008-11-25 07:09:13 +0000751 if (VariableOperand != -1)
752 return false;
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000753
Chris Lattnerdd77df32007-04-13 20:30:56 +0000754 // Remember the variable index.
755 VariableOperand = i;
756 VariableScale = TypeSize;
757 }
758 }
759 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000760
Chris Lattnerdd77df32007-04-13 20:30:56 +0000761 // A common case is for the GEP to only do a constant offset. In this case,
762 // just add it to the disp field and check validity.
763 if (VariableOperand == -1) {
764 AddrMode.BaseOffs += ConstantOffset;
765 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
766 // Check to see if we can fold the base pointer in too.
Chris Lattner88a5c832008-11-25 07:09:13 +0000767 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000768 return true;
769 }
770 AddrMode.BaseOffs -= ConstantOffset;
Chris Lattner88a5c832008-11-25 07:09:13 +0000771 return false;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000772 }
Chris Lattner88a5c832008-11-25 07:09:13 +0000773
774 // Save the valid addressing mode in case we can't match.
775 ExtAddrMode BackupAddrMode = AddrMode;
776
777 // Check that this has no base reg yet. If so, we won't have a place to
778 // put the base of the GEP (assuming it is not a null ptr).
779 bool SetBaseReg = true;
780 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
781 SetBaseReg = false; // null pointer base doesn't need representation.
782 else if (AddrMode.HasBaseReg)
783 return false; // Base register already specified, can't match GEP.
784 else {
785 // Otherwise, we'll use the GEP base as the BaseReg.
786 AddrMode.HasBaseReg = true;
787 AddrMode.BaseReg = AddrInst->getOperand(0);
788 }
789
790 // See if the scale and offset amount is valid for this target.
791 AddrMode.BaseOffs += ConstantOffset;
792
Chris Lattner3b485012008-11-25 07:25:26 +0000793 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
794 Depth)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000795 AddrMode = BackupAddrMode;
796 return false;
797 }
798
799 // If we have a null as the base of the GEP, folding in the constant offset
800 // plus variable scale is all we can do.
801 if (!SetBaseReg) return true;
802
803 // If this match succeeded, we know that we can form an address with the
804 // GepBase as the basereg. Match the base pointer of the GEP more
805 // aggressively by zeroing out BaseReg and rematching. If the base is
806 // (for example) another GEP, this allows merging in that other GEP into
807 // the addressing mode we're forming.
808 AddrMode.HasBaseReg = false;
809 AddrMode.BaseReg = 0;
810 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
811 assert(Success && "MatchAddr should be able to fill in BaseReg!");
812 Success=Success;
813 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000814 }
815 }
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000816 return false;
817}
Eric Christopher692bf6b2008-09-24 05:32:41 +0000818
Chris Lattner88a5c832008-11-25 07:09:13 +0000819/// MatchAddr - If we can, try to add the value of 'Addr' into the current
820/// addressing mode. If Addr can't be added to AddrMode this returns false and
821/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
822/// or intptr_t for the target.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000823///
Chris Lattner88a5c832008-11-25 07:09:13 +0000824bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000825 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
826 // Fold in immediates if legal for the target.
827 AddrMode.BaseOffs += CI->getSExtValue();
828 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
829 return true;
830 AddrMode.BaseOffs -= CI->getSExtValue();
831 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000832 // If this is a global variable, try to fold it into the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000833 if (AddrMode.BaseGV == 0) {
834 AddrMode.BaseGV = GV;
835 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
836 return true;
837 AddrMode.BaseGV = 0;
838 }
839 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000840 ExtAddrMode BackupAddrMode = AddrMode;
841 unsigned OldSize = AddrModeInsts.size();
842
843 // Check to see if it is possible to fold this operation.
Chris Lattner88a5c832008-11-25 07:09:13 +0000844 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000845 // Okay, it's possible to fold this. Check to see if it is actually
846 // *profitable* to do so. We use a simple cost model to avoid increasing
847 // register pressure too much.
Chris Lattner84d1b402008-11-26 03:02:41 +0000848 if (I->hasOneUse() ||
849 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000850 AddrModeInsts.push_back(I);
851 return true;
852 }
853
854 // It isn't profitable to do this, roll back.
855 //cerr << "NOT FOLDING: " << *I;
856 AddrMode = BackupAddrMode;
857 AddrModeInsts.resize(OldSize);
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000858 }
859 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000860 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000861 return true;
862 } else if (isa<ConstantPointerNull>(Addr)) {
Chris Lattner88a5c832008-11-25 07:09:13 +0000863 // Null pointer gets folded without affecting the addressing mode.
Chris Lattnerbb3204a2008-11-25 05:15:49 +0000864 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000866
Chris Lattnerdd77df32007-04-13 20:30:56 +0000867 // Worse case, the target should support [reg] addressing modes. :)
868 if (!AddrMode.HasBaseReg) {
869 AddrMode.HasBaseReg = true;
Chris Lattner653b2582008-11-26 02:11:11 +0000870 AddrMode.BaseReg = Addr;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000871 // Still check for legality in case the target supports [imm] but not [i+r].
Chris Lattner653b2582008-11-26 02:11:11 +0000872 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000873 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000874 AddrMode.HasBaseReg = false;
Chris Lattner653b2582008-11-26 02:11:11 +0000875 AddrMode.BaseReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000876 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000877
Chris Lattnerdd77df32007-04-13 20:30:56 +0000878 // If the base register is already taken, see if we can do [r+r].
879 if (AddrMode.Scale == 0) {
880 AddrMode.Scale = 1;
Chris Lattner653b2582008-11-26 02:11:11 +0000881 AddrMode.ScaledReg = Addr;
882 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000883 return true;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000884 AddrMode.Scale = 0;
Chris Lattner653b2582008-11-26 02:11:11 +0000885 AddrMode.ScaledReg = 0;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000886 }
887 // Couldn't match.
888 return false;
889}
890
Chris Lattner695d8ec2008-11-26 04:59:11 +0000891
892/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
893/// inline asm call are due to memory operands. If so, return true, otherwise
894/// return false.
895static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
896 const TargetLowering &TLI) {
897 std::vector<InlineAsm::ConstraintInfo>
898 Constraints = IA->ParseConstraints();
899
900 unsigned ArgNo = 1; // ArgNo - The operand of the CallInst.
901 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
902 TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
903
904 // Compute the value type for each operand.
905 switch (OpInfo.Type) {
906 case InlineAsm::isOutput:
907 if (OpInfo.isIndirect)
908 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
909 break;
910 case InlineAsm::isInput:
911 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
912 break;
913 case InlineAsm::isClobber:
914 // Nothing to do.
915 break;
916 }
917
918 // Compute the constraint code and ConstraintType to use.
919 TLI.ComputeConstraintToUse(OpInfo, SDValue(),
920 OpInfo.ConstraintType == TargetLowering::C_Memory);
921
922 // If this asm operand is our Value*, and if it isn't an indirect memory
923 // operand, we can't fold it!
924 if (OpInfo.CallOperandVal == OpVal &&
925 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
926 !OpInfo.isIndirect))
927 return false;
928 }
929
930 return true;
931}
932
933
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000934/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
935/// memory use. If we find an obviously non-foldable instruction, return true.
936/// Add the ultimately found memory instructions to MemoryUses.
937static bool FindAllMemoryUses(Instruction *I,
938 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
Chris Lattner695d8ec2008-11-26 04:59:11 +0000939 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
940 const TargetLowering &TLI) {
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000941 // If we already considered this instruction, we're done.
942 if (!ConsideredInsts.insert(I))
943 return false;
944
945 // If this is an obviously unfoldable instruction, bail out.
946 if (!MightBeFoldableInst(I))
947 return true;
948
949 // Loop over all the uses, recursively processing them.
950 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
951 UI != E; ++UI) {
952 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
953 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
954 continue;
955 }
956
957 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
958 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
959 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
960 continue;
961 }
962
963 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
964 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
965 if (IA == 0) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000966
Chris Lattner695d8ec2008-11-26 04:59:11 +0000967 // If this is a memory operand, we're cool, otherwise bail out.
968 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
969 return true;
970 continue;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000971 }
972
Chris Lattner695d8ec2008-11-26 04:59:11 +0000973 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
974 TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000975 return true;
976 }
977
978 return false;
979}
Chris Lattner84d1b402008-11-26 03:02:41 +0000980
981
982/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
983/// the use site that we're folding it into. If so, there is no cost to
984/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
985/// that we know are live at the instruction already.
986bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
987 Value *KnownLive2) {
988 // If Val is either of the known-live values, we know it is live!
989 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
990 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +0000991
Chris Lattner896617b2008-11-26 03:20:37 +0000992 // All values other than instructions and arguments (e.g. constants) are live.
Chris Lattner84d1b402008-11-26 03:02:41 +0000993 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
994
995 // If Val is a constant sized alloca in the entry block, it is live, this is
996 // true because it is just a reference to the stack/frame pointer, which is
997 // live for the whole function.
998 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
999 if (AI->isStaticAlloca())
1000 return true;
1001
Chris Lattner896617b2008-11-26 03:20:37 +00001002 // Check to see if this value is already used in the memory instruction's
1003 // block. If so, it's already live into the block at the very least, so we
1004 // can reasonably fold it.
1005 BasicBlock *MemBB = MemoryInst->getParent();
1006 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1007 UI != E; ++UI)
1008 // We know that uses of arguments and instructions have to be instructions.
1009 if (cast<Instruction>(*UI)->getParent() == MemBB)
1010 return true;
1011
Chris Lattner84d1b402008-11-26 03:02:41 +00001012 return false;
1013}
1014
1015
1016
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001017/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1018/// mode of the machine to fold the specified instruction into a load or store
1019/// that ultimately uses it. However, the specified instruction has multiple
1020/// uses. Given this, it may actually increase register pressure to fold it
1021/// into the load. For example, consider this code:
1022///
1023/// X = ...
1024/// Y = X+1
1025/// use(Y) -> nonload/store
1026/// Z = Y+1
1027/// load Z
1028///
1029/// In this case, Y has multiple uses, and can be folded into the load of Z
1030/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1031/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1032/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1033/// number of computations either.
1034///
1035/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1036/// X was live across 'load Z' for other reasons, we actually *would* want to
Chris Lattner653b2582008-11-26 02:11:11 +00001037/// fold the addressing mode in the Z case. This would make Y die earlier.
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001038bool AddressingModeMatcher::
Chris Lattner84d1b402008-11-26 03:02:41 +00001039IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1040 ExtAddrMode &AMAfter) {
Chris Lattnerab8b7942008-11-26 22:16:44 +00001041 if (IgnoreProfitability) return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001042
Chris Lattner84d1b402008-11-26 03:02:41 +00001043 // AMBefore is the addressing mode before this instruction was folded into it,
1044 // and AMAfter is the addressing mode after the instruction was folded. Get
1045 // the set of registers referenced by AMAfter and subtract out those
1046 // referenced by AMBefore: this is the set of values which folding in this
1047 // address extends the lifetime of.
1048 //
1049 // Note that there are only two potential values being referenced here,
1050 // BaseReg and ScaleReg (global addresses are always available, as are any
1051 // folded immediates).
1052 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1053
1054 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1055 // lifetime wasn't extended by adding this instruction.
1056 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1057 BaseReg = 0;
1058 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1059 ScaledReg = 0;
1060
1061 // If folding this instruction (and it's subexprs) didn't extend any live
1062 // ranges, we're ok with it.
1063 if (BaseReg == 0 && ScaledReg == 0)
1064 return true;
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001065
1066 // If all uses of this instruction are ultimately load/store/inlineasm's,
1067 // check to see if their addressing modes will include this instruction. If
1068 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1069 // uses.
1070 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1071 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Chris Lattner695d8ec2008-11-26 04:59:11 +00001072 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001073 return false; // Has a non-memory, non-foldable use!
1074
1075 // Now that we know that all uses of this instruction are part of a chain of
1076 // computation involving only operations that could theoretically be folded
1077 // into a memory use, loop over each of these uses and see if they could
1078 // *actually* fold the instruction.
1079 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1080 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1081 Instruction *User = MemoryUses[i].first;
1082 unsigned OpNo = MemoryUses[i].second;
1083
1084 // Get the access type of this use. If the use isn't a pointer, we don't
1085 // know what it accesses.
1086 Value *Address = User->getOperand(OpNo);
1087 if (!isa<PointerType>(Address->getType()))
1088 return false;
1089 const Type *AddressAccessTy =
1090 cast<PointerType>(Address->getType())->getElementType();
1091
1092 // Do a match against the root of this address, ignoring profitability. This
1093 // will tell us if the addressing mode for the memory operation will
1094 // *actually* cover the shared instruction.
1095 ExtAddrMode Result;
1096 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Chris Lattner896617b2008-11-26 03:20:37 +00001097 MemoryInst, Result);
Chris Lattner5eecb7f2008-11-26 02:00:14 +00001098 Matcher.IgnoreProfitability = true;
1099 bool Success = Matcher.MatchAddr(Address, 0);
1100 Success = Success; assert(Success && "Couldn't select *anything*?");
1101
1102 // If the match didn't cover I, then it won't be shared by it.
1103 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1104 I) == MatchedAddrModeInsts.end())
1105 return false;
1106
1107 MatchedAddrModeInsts.clear();
1108 }
1109
1110 return true;
1111}
1112
Chris Lattnerdd77df32007-04-13 20:30:56 +00001113
Chris Lattner88a5c832008-11-25 07:09:13 +00001114//===----------------------------------------------------------------------===//
1115// Memory Optimization
1116//===----------------------------------------------------------------------===//
1117
Chris Lattnerdd77df32007-04-13 20:30:56 +00001118/// IsNonLocalValue - Return true if the specified values are defined in a
1119/// different basic block than BB.
1120static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1121 if (Instruction *I = dyn_cast<Instruction>(V))
1122 return I->getParent() != BB;
1123 return false;
1124}
1125
Chris Lattner88a5c832008-11-25 07:09:13 +00001126/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +00001127/// addressing modes that can do significant amounts of computation. As such,
1128/// instruction selection will try to get the load or store to do as much
1129/// computation as possible for the program. The problem is that isel can only
1130/// see within a single block. As such, we sink as much legal addressing mode
1131/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +00001132///
1133/// This method is used to optimize both load/store and inline asms with memory
1134/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +00001135bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +00001136 const Type *AccessTy,
1137 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001138 // Figure out what addressing mode will be built up for this operation.
1139 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +00001140 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1141 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001142
Chris Lattnerdd77df32007-04-13 20:30:56 +00001143 // Check to see if any of the instructions supersumed by this addr mode are
1144 // non-local to I's BB.
1145 bool AnyNonLocal = false;
1146 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +00001147 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001148 AnyNonLocal = true;
1149 break;
1150 }
1151 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001152
Chris Lattnerdd77df32007-04-13 20:30:56 +00001153 // If all the instructions matched are already in this BB, don't do anything.
1154 if (!AnyNonLocal) {
1155 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1156 return false;
1157 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001158
Chris Lattnerdd77df32007-04-13 20:30:56 +00001159 // Insert this computation right after this user. Since our caller is
1160 // scanning from the top of the BB to the bottom, reuse of the expr are
1161 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +00001162 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001163
Chris Lattnerdd77df32007-04-13 20:30:56 +00001164 // Now that we determined the addressing expression we want to use and know
1165 // that we have to sink it into this block. Check to see if we have already
1166 // done this for some other load/store instr in this block. If so, reuse the
1167 // computation.
1168 Value *&SunkAddr = SunkAddrs[Addr];
1169 if (SunkAddr) {
1170 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1171 if (SunkAddr->getType() != Addr->getType())
1172 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1173 } else {
1174 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1175 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001176
Chris Lattnerdd77df32007-04-13 20:30:56 +00001177 Value *Result = 0;
1178 // Start with the scale value.
1179 if (AddrMode.Scale) {
1180 Value *V = AddrMode.ScaledReg;
1181 if (V->getType() == IntPtrTy) {
1182 // done.
1183 } else if (isa<PointerType>(V->getType())) {
1184 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1185 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1186 cast<IntegerType>(V->getType())->getBitWidth()) {
1187 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1188 } else {
1189 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1190 }
1191 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001192 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +00001193 AddrMode.Scale),
1194 "sunkaddr", InsertPt);
1195 Result = V;
1196 }
1197
1198 // Add in the base register.
1199 if (AddrMode.BaseReg) {
1200 Value *V = AddrMode.BaseReg;
1201 if (V->getType() != IntPtrTy)
1202 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1203 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001204 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001205 else
1206 Result = V;
1207 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001208
Chris Lattnerdd77df32007-04-13 20:30:56 +00001209 // Add in the BaseGV if present.
1210 if (AddrMode.BaseGV) {
1211 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1212 InsertPt);
1213 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001214 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001215 else
1216 Result = V;
1217 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001218
Chris Lattnerdd77df32007-04-13 20:30:56 +00001219 // Add in the Base Offset if present.
1220 if (AddrMode.BaseOffs) {
1221 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1222 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001223 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001224 else
1225 Result = V;
1226 }
1227
1228 if (Result == 0)
1229 SunkAddr = Constant::getNullValue(Addr->getType());
1230 else
1231 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1232 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001233
Chris Lattner896617b2008-11-26 03:20:37 +00001234 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001235
Chris Lattnerdd77df32007-04-13 20:30:56 +00001236 if (Addr->use_empty())
1237 EraseDeadInstructions(Addr);
1238 return true;
1239}
1240
Evan Cheng9bf12b52008-02-26 02:42:37 +00001241/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001242/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001243/// possible / profitable.
1244bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1245 DenseMap<Value*,Value*> &SunkAddrs) {
1246 bool MadeChange = false;
1247 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1248
1249 // Do a prepass over the constraints, canonicalizing them, and building up the
1250 // ConstraintOperands list.
1251 std::vector<InlineAsm::ConstraintInfo>
1252 ConstraintInfos = IA->ParseConstraints();
1253
1254 /// ConstraintOperands - Information about all of the constraints.
1255 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1256 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1257 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1258 ConstraintOperands.
1259 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1260 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1261
1262 // Compute the value type for each operand.
1263 switch (OpInfo.Type) {
1264 case InlineAsm::isOutput:
1265 if (OpInfo.isIndirect)
1266 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1267 break;
1268 case InlineAsm::isInput:
1269 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1270 break;
1271 case InlineAsm::isClobber:
1272 // Nothing to do.
1273 break;
1274 }
1275
1276 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +00001277 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1278 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001279
Eli Friedman9ec80952008-02-26 18:37:49 +00001280 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1281 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001282 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +00001283 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +00001284 }
1285 }
1286
1287 return MadeChange;
1288}
1289
Evan Chengbdcb7262007-12-05 23:58:20 +00001290bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1291 BasicBlock *DefBB = I->getParent();
1292
1293 // If both result of the {s|z}xt and its source are live out, rewrite all
1294 // other uses of the source with result of extension.
1295 Value *Src = I->getOperand(0);
1296 if (Src->hasOneUse())
1297 return false;
1298
Evan Cheng696e5c02007-12-13 07:50:36 +00001299 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001300 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001301 return false;
1302
Evan Cheng772de512007-12-12 00:51:06 +00001303 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001304 // this block.
1305 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001306 return false;
1307
Evan Chengbdcb7262007-12-05 23:58:20 +00001308 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001309 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001310 UI != E; ++UI) {
1311 Instruction *User = cast<Instruction>(*UI);
1312
1313 // Figure out which BB this ext is used in.
1314 BasicBlock *UserBB = User->getParent();
1315 if (UserBB == DefBB) continue;
1316 DefIsLiveOut = true;
1317 break;
1318 }
1319 if (!DefIsLiveOut)
1320 return false;
1321
Evan Cheng765dff22007-12-12 02:53:41 +00001322 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001323 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001324 UI != E; ++UI) {
1325 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001326 BasicBlock *UserBB = User->getParent();
1327 if (UserBB == DefBB) continue;
1328 // Be conservative. We don't want this xform to end up introducing
1329 // reloads just before load / store instructions.
1330 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001331 return false;
1332 }
1333
Evan Chengbdcb7262007-12-05 23:58:20 +00001334 // InsertedTruncs - Only insert one trunc in each block once.
1335 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1336
1337 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001338 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001339 UI != E; ++UI) {
1340 Use &TheUse = UI.getUse();
1341 Instruction *User = cast<Instruction>(*UI);
1342
1343 // Figure out which BB this ext is used in.
1344 BasicBlock *UserBB = User->getParent();
1345 if (UserBB == DefBB) continue;
1346
1347 // Both src and def are live in this block. Rewrite the use.
1348 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1349
1350 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001351 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001352
Evan Chengbdcb7262007-12-05 23:58:20 +00001353 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1354 }
1355
1356 // Replace a use of the {s|z}ext source with a use of the result.
1357 TheUse = InsertedTrunc;
1358
1359 MadeChange = true;
1360 }
1361
1362 return MadeChange;
1363}
1364
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001365// In this pass we look for GEP and cast instructions that are used
1366// across basic blocks and rewrite them to improve basic-block-at-a-time
1367// selection.
1368bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1369 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001370
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001371 // Split all critical edges where the dest block has a PHI and where the phi
1372 // has shared immediate operands.
1373 TerminatorInst *BBTI = BB.getTerminator();
1374 if (BBTI->getNumSuccessors() > 1) {
1375 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1376 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1377 isCriticalEdge(BBTI, i, true))
1378 SplitEdgeNicely(BBTI, i, this);
1379 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001380
1381
Chris Lattnerdd77df32007-04-13 20:30:56 +00001382 // Keep track of non-local addresses that have been sunk into this block.
1383 // This allows us to avoid inserting duplicate code for blocks with multiple
1384 // load/stores of the same address.
1385 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001386
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001387 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1388 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001389
Chris Lattnerdd77df32007-04-13 20:30:56 +00001390 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001391 // If the source of the cast is a constant, then this should have
1392 // already been constant folded. The only reason NOT to constant fold
1393 // it is if something (e.g. LSR) was careful to place the constant
1394 // evaluation in a block other than then one that uses it (e.g. to hoist
1395 // the address of globals out of a loop). If this is the case, we don't
1396 // want to forward-subst the cast.
1397 if (isa<Constant>(CI->getOperand(0)))
1398 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001399
Evan Chengbdcb7262007-12-05 23:58:20 +00001400 bool Change = false;
1401 if (TLI) {
1402 Change = OptimizeNoopCopyExpression(CI, *TLI);
1403 MadeChange |= Change;
1404 }
1405
Evan Cheng55e641b2008-03-19 22:02:26 +00001406 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +00001407 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +00001408 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1409 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001410 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1411 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001412 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1413 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001414 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1415 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001416 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1417 SI->getOperand(0)->getType(),
1418 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001419 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001420 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001421 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001422 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001423 GEPI->getName(), GEPI);
1424 GEPI->replaceAllUsesWith(NC);
1425 GEPI->eraseFromParent();
1426 MadeChange = true;
1427 BBI = NC;
1428 }
1429 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1430 // If we found an inline asm expession, and if the target knows how to
1431 // lower it to normal LLVM code, do so now.
1432 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +00001433 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +00001434 TLI->getTargetMachine().getTargetAsmInfo()) {
1435 if (TAI->ExpandInlineAsm(CI))
1436 BBI = BB.begin();
Evan Cheng9bf12b52008-02-26 02:42:37 +00001437 else
1438 // Sink address computing for memory operands into the block.
1439 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001440 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001441 }
1442 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001443
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001444 return MadeChange;
1445}