blob: a3e3fea4da076553ef0a2e483ed51220bb95a5c5 [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"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000024#include "llvm/LLVMContext.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000026#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000029#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000031#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000040#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000042using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043
Evan Chengab631522008-12-19 18:03:11 +000044static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
46
Eric Christopher692bf6b2008-09-24 05:32:41 +000047namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
Andreas Neustifterad809812009-09-16 09:26:52 +000052 ProfileInfo *PI;
Evan Chengab631522008-12-19 18:03:11 +000053
54 /// BackEdges - Keep a set of all the loop back edges.
55 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000056 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000057 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000058 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000059 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000060 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000061 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000062
Andreas Neustifterad809812009-09-16 09:26:52 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addPreserved<ProfileInfo>();
65 }
66
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000067 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000068 bool EliminateMostlyEmptyBlocks(Function &F);
69 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
70 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000071 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000072 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
73 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000074 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
75 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000076 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000077 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000078 };
79}
Devang Patel794fd752007-05-01 21:15:47 +000080
Devang Patel19974732007-05-03 01:11:54 +000081char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000082static RegisterPass<CodeGenPrepare> X("codegenprepare",
83 "Optimize for code generation");
84
85FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
86 return new CodeGenPrepare(TLI);
87}
88
Evan Chengab631522008-12-19 18:03:11 +000089/// findLoopBackEdges - Do a DFS walk to find loop back edges.
90///
Mike Stumpfe095f32009-05-04 18:40:41 +000091void CodeGenPrepare::findLoopBackEdges(const Function &F) {
92 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
93 FindFunctionBackedges(F, Edges);
94
95 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +000096}
97
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000098
99bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000100 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000101
Andreas Neustifterad809812009-09-16 09:26:52 +0000102 PI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000103 // First pass, eliminate blocks that contain only PHI nodes and an
104 // unconditional branch.
105 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000106
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000107 // Now find loop back edges.
108 findLoopBackEdges(F);
109
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000110 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000111 while (MadeChange) {
112 MadeChange = false;
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
114 MadeChange |= OptimizeBlock(*BB);
115 EverMadeChange |= MadeChange;
116 }
117 return EverMadeChange;
118}
119
Dale Johannesen2d697242009-03-27 01:13:37 +0000120/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
121/// debug info directives, and an unconditional branch. Passes before isel
122/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
123/// isel. Start by eliminating these blocks so we can split them the way we
124/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000125bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
126 bool MadeChange = false;
127 // Note that this intentionally skips the entry block.
128 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
129 BasicBlock *BB = I++;
130
131 // If this block doesn't end with an uncond branch, ignore it.
132 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
133 if (!BI || !BI->isUnconditional())
134 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000135
Dale Johannesen2d697242009-03-27 01:13:37 +0000136 // If the instruction before the branch (skipping debug info) isn't a phi
137 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000138 BasicBlock::iterator BBI = BI;
139 if (BBI != BB->begin()) {
140 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000141 while (isa<DbgInfoIntrinsic>(BBI)) {
142 if (BBI == BB->begin())
143 break;
144 --BBI;
145 }
146 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
147 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000148 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000149
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000150 // Do not break infinite loops.
151 BasicBlock *DestBB = BI->getSuccessor(0);
152 if (DestBB == BB)
153 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000154
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000155 if (!CanMergeBlocks(BB, DestBB))
156 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000157
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000158 EliminateMostlyEmptyBlock(BB);
159 MadeChange = true;
160 }
161 return MadeChange;
162}
163
164/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
165/// single uncond branch between them, and BB contains no other non-phi
166/// instructions.
167bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
168 const BasicBlock *DestBB) const {
169 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
170 // the successor. If there are more complex condition (e.g. preheaders),
171 // don't mess around with them.
172 BasicBlock::const_iterator BBI = BB->begin();
173 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
174 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
175 UI != E; ++UI) {
176 const Instruction *User = cast<Instruction>(*UI);
177 if (User->getParent() != DestBB || !isa<PHINode>(User))
178 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000179 // If User is inside DestBB block and it is a PHINode then check
180 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000181 // a complex condition (e.g. preheaders) we want to avoid here.
182 if (User->getParent() == DestBB) {
183 if (const PHINode *UPN = dyn_cast<PHINode>(User))
184 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
185 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
186 if (Insn && Insn->getParent() == BB &&
187 Insn->getParent() != UPN->getIncomingBlock(I))
188 return false;
189 }
190 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000191 }
192 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000193
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000194 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
195 // and DestBB may have conflicting incoming values for the block. If so, we
196 // can't merge the block.
197 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
198 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000199
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000200 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000201 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000202 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
203 // It is faster to get preds from a PHI than with pred_iterator.
204 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
205 BBPreds.insert(BBPN->getIncomingBlock(i));
206 } else {
207 BBPreds.insert(pred_begin(BB), pred_end(BB));
208 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000209
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000210 // Walk the preds of DestBB.
211 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
212 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
213 if (BBPreds.count(Pred)) { // Common predecessor?
214 BBI = DestBB->begin();
215 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
216 const Value *V1 = PN->getIncomingValueForBlock(Pred);
217 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000218
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000219 // If V2 is a phi node in BB, look up what the mapped value will be.
220 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
221 if (V2PN->getParent() == BB)
222 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000223
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 // If there is a conflict, bail out.
225 if (V1 != V2) return false;
226 }
227 }
228 }
229
230 return true;
231}
232
233
234/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
235/// an unconditional branch in it.
236void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
237 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
238 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000239
Chris Lattnerbdff5482009-08-23 04:37:46 +0000240 DEBUG(errs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000241
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000242 // If the destination block has a single pred, then this is a trivial edge,
243 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000244 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000245 if (SinglePred != DestBB) {
246 // Remember if SinglePred was the entry block of the function. If so, we
247 // will need to move BB back to the entry position.
248 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000249 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000250
Chris Lattnerf5102a02008-11-28 19:54:49 +0000251 if (isEntry && BB != &BB->getParent()->getEntryBlock())
252 BB->moveBefore(&BB->getParent()->getEntryBlock());
253
Chris Lattnerbdff5482009-08-23 04:37:46 +0000254 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000255 return;
256 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000257 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000258
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
260 // to handle the new incoming edges it is about to have.
261 PHINode *PN;
262 for (BasicBlock::iterator BBI = DestBB->begin();
263 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
264 // Remove the incoming value for BB, and remember it.
265 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000266
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000267 // Two options: either the InVal is a phi node defined in BB or it is some
268 // value that dominates BB.
269 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
270 if (InValPhi && InValPhi->getParent() == BB) {
271 // Add all of the input values of the input PHI as inputs of this phi.
272 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
273 PN->addIncoming(InValPhi->getIncomingValue(i),
274 InValPhi->getIncomingBlock(i));
275 } else {
276 // Otherwise, add one instance of the dominating value for each edge that
277 // we will be adding.
278 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
279 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
280 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
281 } else {
282 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
283 PN->addIncoming(InVal, *PI);
284 }
285 }
286 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000287
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 // The PHIs are now updated, change everything that refers to BB to use
289 // DestBB and remove BB.
290 BB->replaceAllUsesWith(DestBB);
Andreas Neustifterad809812009-09-16 09:26:52 +0000291 if (PI) {
292 PI->replaceAllUses(BB, DestBB);
293 PI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
294 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000296
Chris Lattnerbdff5482009-08-23 04:37:46 +0000297 DEBUG(errs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000298}
299
300
Chris Lattnerebe80752007-12-24 19:32:55 +0000301/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000302/// successor if it will improve codegen. We only do this if the successor has
303/// phi nodes (otherwise critical edges are ok). If there is already another
304/// predecessor of the succ that is empty (and thus has no phi nodes), use it
305/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000306static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000307 SmallSet<std::pair<const BasicBlock*,
308 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000309 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000310 BasicBlock *TIBB = TI->getParent();
311 BasicBlock *Dest = TI->getSuccessor(SuccNum);
312 assert(isa<PHINode>(Dest->begin()) &&
313 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000314
Evan Chengfc0b80d2009-03-13 22:59:14 +0000315 // Do not split edges to EH landing pads.
316 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
317 if (Invoke->getSuccessor(1) == Dest)
318 return;
319 }
320
Chris Lattnerebe80752007-12-24 19:32:55 +0000321 // As a hack, never split backedges of loops. Even though the copy for any
322 // PHIs inserted on the backedge would be dead for exits from the loop, we
323 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000324 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000325 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000326
Evan Chengab631522008-12-19 18:03:11 +0000327 if (!FactorCommonPreds) {
328 /// TIPHIValues - This array is lazily computed to determine the values of
329 /// PHIs in Dest that TI would provide.
330 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000331
Evan Chengab631522008-12-19 18:03:11 +0000332 // Check to see if Dest has any blocks that can be used as a split edge for
333 // this terminator.
334 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
335 BasicBlock *Pred = *PI;
336 // To be usable, the pred has to end with an uncond branch to the dest.
337 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000338 if (!PredBr || !PredBr->isUnconditional())
339 continue;
340 // Must be empty other than the branch and debug info.
341 BasicBlock::iterator I = Pred->begin();
342 while (isa<DbgInfoIntrinsic>(I))
343 I++;
344 if (dyn_cast<Instruction>(I) != PredBr)
345 continue;
346 // Cannot be the entry block; its label does not get emitted.
347 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000348 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000349
Evan Chengab631522008-12-19 18:03:11 +0000350 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000351 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000352 // terms of PHI values.
353 PHINode *PN;
354 unsigned PHINo = 0;
355 bool FoundMatch = true;
356 for (BasicBlock::iterator I = Dest->begin();
357 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
358 if (PHINo == TIPHIValues.size())
359 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000360
Evan Chengab631522008-12-19 18:03:11 +0000361 // If the PHI entry doesn't work, we can't use this pred.
362 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
363 FoundMatch = false;
364 break;
365 }
366 }
367
368 // If we found a workable predecessor, change TI to branch to Succ.
369 if (FoundMatch) {
Andreas Neustifterad809812009-09-16 09:26:52 +0000370 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
371 if (PI)
372 PI->splitEdge(TIBB, Dest, Pred);
Evan Chengab631522008-12-19 18:03:11 +0000373 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
Dan Gohmana119de82009-06-14 23:30:43 +0000417/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
418/// 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,
Owen Andersone50ed302009-08-10 22:56:29 +0000425 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
426 EVT 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.
Owen Anderson23b9b192009-08-12 00:36:31 +0000439 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
440 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
441 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
442 DstVT = TLI.getTypeToTransformTo(CI->getContext(), 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 =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000535 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000536 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000537 CI->getOperand(1), "", InsertPt);
538 MadeChange = true;
539 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000540
Dale Johannesence0b2372007-06-12 16:50:17 +0000541 // Replace a use of the cmp with a use of the new cmp.
542 TheUse = InsertedCmp;
543 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // If we removed all uses, nuke the cmp.
546 if (CI->use_empty())
547 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 return MadeChange;
550}
551
Chris Lattner88a5c832008-11-25 07:09:13 +0000552//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000553// Memory Optimization
554//===----------------------------------------------------------------------===//
555
Chris Lattnerdd77df32007-04-13 20:30:56 +0000556/// IsNonLocalValue - Return true if the specified values are defined in a
557/// different basic block than BB.
558static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
559 if (Instruction *I = dyn_cast<Instruction>(V))
560 return I->getParent() != BB;
561 return false;
562}
563
Chris Lattner88a5c832008-11-25 07:09:13 +0000564/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000565/// addressing modes that can do significant amounts of computation. As such,
566/// instruction selection will try to get the load or store to do as much
567/// computation as possible for the program. The problem is that isel can only
568/// see within a single block. As such, we sink as much legal addressing mode
569/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000570///
571/// This method is used to optimize both load/store and inline asms with memory
572/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000573bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000574 const Type *AccessTy,
575 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000576 // Figure out what addressing mode will be built up for this operation.
577 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000578 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
579 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000580
Chris Lattnerdd77df32007-04-13 20:30:56 +0000581 // Check to see if any of the instructions supersumed by this addr mode are
582 // non-local to I's BB.
583 bool AnyNonLocal = false;
584 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000585 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000586 AnyNonLocal = true;
587 break;
588 }
589 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000590
Chris Lattnerdd77df32007-04-13 20:30:56 +0000591 // If all the instructions matched are already in this BB, don't do anything.
592 if (!AnyNonLocal) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000593 DEBUG(errs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000594 return false;
595 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000596
Chris Lattnerdd77df32007-04-13 20:30:56 +0000597 // Insert this computation right after this user. Since our caller is
598 // scanning from the top of the BB to the bottom, reuse of the expr are
599 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000600 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000601
Chris Lattnerdd77df32007-04-13 20:30:56 +0000602 // Now that we determined the addressing expression we want to use and know
603 // that we have to sink it into this block. Check to see if we have already
604 // done this for some other load/store instr in this block. If so, reuse the
605 // computation.
606 Value *&SunkAddr = SunkAddrs[Addr];
607 if (SunkAddr) {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000608 DEBUG(errs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
609 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000610 if (SunkAddr->getType() != Addr->getType())
611 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
612 } else {
Dan Gohman6c1980b2009-07-25 01:13:51 +0000613 DEBUG(errs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
614 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000615 const Type *IntPtrTy =
616 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000617
Chris Lattnerdd77df32007-04-13 20:30:56 +0000618 Value *Result = 0;
619 // Start with the scale value.
620 if (AddrMode.Scale) {
621 Value *V = AddrMode.ScaledReg;
622 if (V->getType() == IntPtrTy) {
623 // done.
624 } else if (isa<PointerType>(V->getType())) {
625 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
626 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
627 cast<IntegerType>(V->getType())->getBitWidth()) {
628 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
629 } else {
630 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
631 }
632 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000633 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000634 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000635 "sunkaddr", InsertPt);
636 Result = V;
637 }
638
639 // Add in the base register.
640 if (AddrMode.BaseReg) {
641 Value *V = AddrMode.BaseReg;
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000642 if (isa<PointerType>(V->getType()))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000643 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000644 if (V->getType() != IntPtrTy)
645 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
646 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000647 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000648 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000649 else
650 Result = V;
651 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000652
Chris Lattnerdd77df32007-04-13 20:30:56 +0000653 // Add in the BaseGV if present.
654 if (AddrMode.BaseGV) {
655 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
656 InsertPt);
657 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000658 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000659 else
660 Result = V;
661 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000662
Chris Lattnerdd77df32007-04-13 20:30:56 +0000663 // Add in the Base Offset if present.
664 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000665 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000666 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000667 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000668 else
669 Result = V;
670 }
671
672 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000673 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000674 else
675 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
676 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000677
Chris Lattner896617b2008-11-26 03:20:37 +0000678 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000679
Chris Lattnerdd77df32007-04-13 20:30:56 +0000680 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000681 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000682 return true;
683}
684
Evan Cheng9bf12b52008-02-26 02:42:37 +0000685/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000686/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000687/// possible / profitable.
688bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
689 DenseMap<Value*,Value*> &SunkAddrs) {
690 bool MadeChange = false;
691 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
692
693 // Do a prepass over the constraints, canonicalizing them, and building up the
694 // ConstraintOperands list.
695 std::vector<InlineAsm::ConstraintInfo>
696 ConstraintInfos = IA->ParseConstraints();
697
698 /// ConstraintOperands - Information about all of the constraints.
699 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
700 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
701 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
702 ConstraintOperands.
703 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
704 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
705
706 // Compute the value type for each operand.
707 switch (OpInfo.Type) {
708 case InlineAsm::isOutput:
709 if (OpInfo.isIndirect)
710 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
711 break;
712 case InlineAsm::isInput:
713 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
714 break;
715 case InlineAsm::isClobber:
716 // Nothing to do.
717 break;
718 }
719
720 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000721 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
722 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000723
Eli Friedman9ec80952008-02-26 18:37:49 +0000724 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
725 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000726 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000727 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000728 }
729 }
730
731 return MadeChange;
732}
733
Evan Chengbdcb7262007-12-05 23:58:20 +0000734bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
735 BasicBlock *DefBB = I->getParent();
736
737 // If both result of the {s|z}xt and its source are live out, rewrite all
738 // other uses of the source with result of extension.
739 Value *Src = I->getOperand(0);
740 if (Src->hasOneUse())
741 return false;
742
Evan Cheng696e5c02007-12-13 07:50:36 +0000743 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000744 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000745 return false;
746
Evan Cheng772de512007-12-12 00:51:06 +0000747 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000748 // this block.
749 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000750 return false;
751
Evan Chengbdcb7262007-12-05 23:58:20 +0000752 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000753 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000754 UI != E; ++UI) {
755 Instruction *User = cast<Instruction>(*UI);
756
757 // Figure out which BB this ext is used in.
758 BasicBlock *UserBB = User->getParent();
759 if (UserBB == DefBB) continue;
760 DefIsLiveOut = true;
761 break;
762 }
763 if (!DefIsLiveOut)
764 return false;
765
Evan Cheng765dff22007-12-12 02:53:41 +0000766 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000767 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000768 UI != E; ++UI) {
769 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000770 BasicBlock *UserBB = User->getParent();
771 if (UserBB == DefBB) continue;
772 // Be conservative. We don't want this xform to end up introducing
773 // reloads just before load / store instructions.
774 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000775 return false;
776 }
777
Evan Chengbdcb7262007-12-05 23:58:20 +0000778 // InsertedTruncs - Only insert one trunc in each block once.
779 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
780
781 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000782 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000783 UI != E; ++UI) {
784 Use &TheUse = UI.getUse();
785 Instruction *User = cast<Instruction>(*UI);
786
787 // Figure out which BB this ext is used in.
788 BasicBlock *UserBB = User->getParent();
789 if (UserBB == DefBB) continue;
790
791 // Both src and def are live in this block. Rewrite the use.
792 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
793
794 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000795 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000796
Evan Chengbdcb7262007-12-05 23:58:20 +0000797 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
798 }
799
800 // Replace a use of the {s|z}ext source with a use of the result.
801 TheUse = InsertedTrunc;
802
803 MadeChange = true;
804 }
805
806 return MadeChange;
807}
808
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000809// In this pass we look for GEP and cast instructions that are used
810// across basic blocks and rewrite them to improve basic-block-at-a-time
811// selection.
812bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
813 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000814
Evan Chengab631522008-12-19 18:03:11 +0000815 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000816 TerminatorInst *BBTI = BB.getTerminator();
817 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +0000818 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
819 BasicBlock *SuccBB = BBTI->getSuccessor(i);
820 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
821 SplitEdgeNicely(BBTI, i, BackEdges, this);
822 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000823 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000824
Chris Lattnerdd77df32007-04-13 20:30:56 +0000825 // Keep track of non-local addresses that have been sunk into this block.
826 // This allows us to avoid inserting duplicate code for blocks with multiple
827 // load/stores of the same address.
828 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000829
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000830 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
831 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000832
Chris Lattnerdd77df32007-04-13 20:30:56 +0000833 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000834 // If the source of the cast is a constant, then this should have
835 // already been constant folded. The only reason NOT to constant fold
836 // it is if something (e.g. LSR) was careful to place the constant
837 // evaluation in a block other than then one that uses it (e.g. to hoist
838 // the address of globals out of a loop). If this is the case, we don't
839 // want to forward-subst the cast.
840 if (isa<Constant>(CI->getOperand(0)))
841 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000842
Evan Chengbdcb7262007-12-05 23:58:20 +0000843 bool Change = false;
844 if (TLI) {
845 Change = OptimizeNoopCopyExpression(CI, *TLI);
846 MadeChange |= Change;
847 }
848
Evan Cheng55e641b2008-03-19 22:02:26 +0000849 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +0000850 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +0000851 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
852 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000853 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
854 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000855 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
856 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000857 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
858 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000859 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
860 SI->getOperand(0)->getType(),
861 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000862 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000863 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000865 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000866 GEPI->getName(), GEPI);
867 GEPI->replaceAllUsesWith(NC);
868 GEPI->eraseFromParent();
869 MadeChange = true;
870 BBI = NC;
871 }
872 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
873 // If we found an inline asm expession, and if the target knows how to
874 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000875 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
876 if (TLI->ExpandInlineAsm(CI)) {
877 BBI = BB.begin();
878 // Avoid processing instructions out of order, which could cause
879 // reuse before a value is defined.
880 SunkAddrs.clear();
881 } else
882 // Sink address computing for memory operands into the block.
883 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
884 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000885 }
886 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000887
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000888 return MadeChange;
889}