blob: 21e6f8925e7e5b400408cfe1c00dbe1f92bd1659 [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"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000025#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000028#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000030#include "llvm/Transforms/Utils/Local.h"
31#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000033#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000034#include "llvm/Support/CallSite.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000035#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000037#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000038#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000039using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000040using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041
Eric Christopher692bf6b2008-09-24 05:32:41 +000042namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000043 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000044 /// TLI - Keep a pointer of a TargetLowering to consult for determining
45 /// transformation profitability.
46 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000047 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000048
49 /// BackEdges - Keep a set of all the loop back edges.
50 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000051 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000052 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000054 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000055 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000056 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000057
Andreas Neustifterad809812009-09-16 09:26:52 +000058 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addPreserved<ProfileInfo>();
60 }
61
Dan Gohmanaa0e5232010-02-05 19:24:11 +000062 virtual void releaseMemory() {
63 BackEdges.clear();
64 }
65
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000067 bool EliminateMostlyEmptyBlocks(Function &F);
68 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
69 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000070 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000071 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
72 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000073 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
74 DenseMap<Value*,Value*> &SunkAddrs);
Dan Gohmanb00f2362009-10-16 20:59:35 +000075 bool MoveExtToFormExtLoad(Instruction *I);
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
Evan Cheng04149f72009-12-17 09:39:49 +0000102 PFI = 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
David Greene68d67fd2010-01-05 01:27:11 +0000240 DEBUG(dbgs() << "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
David Greene68d67fd2010-01-05 01:27:11 +0000254 DEBUG(dbgs() << "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);
Evan Cheng04149f72009-12-17 09:39:49 +0000291 if (PFI) {
292 PFI->replaceAllUses(BB, DestBB);
293 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000294 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000296
David Greene68d67fd2010-01-05 01:27:11 +0000297 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000298}
299
Chris Lattner98d5c312010-02-13 05:35:08 +0000300/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
301/// lives in to see if there is a block that we can reuse as a critical edge
302/// from TIBB.
303static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
304 BasicBlock *Dest = DestPHI->getParent();
305
306 /// TIPHIValues - This array is lazily computed to determine the values of
307 /// PHIs in Dest that TI would provide.
308 SmallVector<Value*, 32> TIPHIValues;
309
310 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
311 unsigned TIBBEntryNo = 0;
312
313 // Check to see if Dest has any blocks that can be used as a split edge for
314 // this terminator.
315 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
316 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
317 // To be usable, the pred has to end with an uncond branch to the dest.
318 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
319 if (!PredBr || !PredBr->isUnconditional())
320 continue;
321 // Must be empty other than the branch and debug info.
322 BasicBlock::iterator I = Pred->begin();
323 while (isa<DbgInfoIntrinsic>(I))
324 I++;
325 if (&*I != PredBr)
326 continue;
327 // Cannot be the entry block; its label does not get emitted.
328 if (Pred == &Dest->getParent()->getEntryBlock())
329 continue;
330
331 // Finally, since we know that Dest has phi nodes in it, we have to make
332 // sure that jumping to Pred will have the same effect as going to Dest in
333 // terms of PHI values.
334 PHINode *PN;
335 unsigned PHINo = 0;
336 unsigned PredEntryNo = pi;
337
338 bool FoundMatch = true;
339 for (BasicBlock::iterator I = Dest->begin();
340 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
341 if (PHINo == TIPHIValues.size()) {
342 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
343 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
344 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
345 }
346
347 // If the PHI entry doesn't work, we can't use this pred.
348 if (PN->getIncomingBlock(PredEntryNo) != Pred)
349 PredEntryNo = PN->getBasicBlockIndex(Pred);
350
351 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
352 FoundMatch = false;
353 break;
354 }
355 }
356
357 // If we found a workable predecessor, change TI to branch to Succ.
358 if (FoundMatch)
359 return Pred;
360 }
361 return 0;
362}
363
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000364
Chris Lattnerebe80752007-12-24 19:32:55 +0000365/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000366/// successor if it will improve codegen. We only do this if the successor has
367/// phi nodes (otherwise critical edges are ok). If there is already another
368/// predecessor of the succ that is empty (and thus has no phi nodes), use it
369/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000370static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000371 SmallSet<std::pair<const BasicBlock*,
372 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000373 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000374 BasicBlock *TIBB = TI->getParent();
375 BasicBlock *Dest = TI->getSuccessor(SuccNum);
376 assert(isa<PHINode>(Dest->begin()) &&
377 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000378 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000379
Evan Chengfc0b80d2009-03-13 22:59:14 +0000380 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000381 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000382 if (Invoke->getSuccessor(1) == Dest)
383 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000384
Chris Lattnerebe80752007-12-24 19:32:55 +0000385 // As a hack, never split backedges of loops. Even though the copy for any
386 // PHIs inserted on the backedge would be dead for exits from the loop, we
387 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000388 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000389 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000390
Chris Lattnerc09687b2010-02-13 19:07:06 +0000391 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
392 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
393 if (PFI)
394 PFI->splitEdge(TIBB, Dest, ReuseBB);
395 Dest->removePredecessor(TIBB);
396 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000397 return;
398 }
399
Chris Lattnerc09687b2010-02-13 19:07:06 +0000400 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000401}
402
Evan Chengab631522008-12-19 18:03:11 +0000403
Chris Lattnerdd77df32007-04-13 20:30:56 +0000404/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000405/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
406/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000407/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000408///
409/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000410///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000411static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000413 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
414 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
Chris Lattnerdd77df32007-04-13 20:30:56 +0000416 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000417 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000418 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000419
Chris Lattnerdd77df32007-04-13 20:30:56 +0000420 // If this is an extension, it will be a zero or sign extension, which
421 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000422 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Chris Lattnerdd77df32007-04-13 20:30:56 +0000424 // If these values will be promoted, find out what they will be promoted
425 // to. This helps us consider truncates on PPC as noop copies when they
426 // are.
Owen Anderson23b9b192009-08-12 00:36:31 +0000427 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
428 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
429 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
430 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerdd77df32007-04-13 20:30:56 +0000432 // If, after promotion, these are the same types, this is a noop copy.
433 if (SrcVT != DstVT)
434 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000436 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000438 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000439 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000441 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000443 UI != E; ) {
444 Use &TheUse = UI.getUse();
445 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000447 // Figure out which BB this cast is used in. For PHI's this is the
448 // appropriate predecessor block.
449 BasicBlock *UserBB = User->getParent();
450 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000451 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 // Preincrement use iterator so we don't invalidate it.
455 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457 // If this user is in the same block as the cast, don't change the cast.
458 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000460 // If we have already inserted a cast into this block, use it.
461 CastInst *&InsertedCast = InsertedCasts[UserBB];
462
463 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000464 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
466 InsertedCast =
467 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 InsertPt);
469 MadeChange = true;
470 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Dale Johannesence0b2372007-06-12 16:50:17 +0000472 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 TheUse = InsertedCast;
474 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000477 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000478 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000479 MadeChange = true;
480 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 return MadeChange;
483}
484
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000486/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000487/// a clear win except on targets with multiple condition code registers
488/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000489///
490/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000491static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000492 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Dale Johannesence0b2372007-06-12 16:50:17 +0000494 /// InsertedCmp - Only insert a cmp in each block once.
495 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Dale Johannesence0b2372007-06-12 16:50:17 +0000497 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000498 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000499 UI != E; ) {
500 Use &TheUse = UI.getUse();
501 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000502
Dale Johannesence0b2372007-06-12 16:50:17 +0000503 // Preincrement use iterator so we don't invalidate it.
504 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 // Don't bother for PHI nodes.
507 if (isa<PHINode>(User))
508 continue;
509
510 // Figure out which BB this cmp is used in.
511 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512
Dale Johannesence0b2372007-06-12 16:50:17 +0000513 // If this user is in the same block as the cmp, don't change the cmp.
514 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000515
Dale Johannesence0b2372007-06-12 16:50:17 +0000516 // If we have already inserted a cmp into this block, use it.
517 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
518
519 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000520 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
522 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000523 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000524 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 CI->getOperand(1), "", InsertPt);
526 MadeChange = true;
527 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 // Replace a use of the cmp with a use of the new cmp.
530 TheUse = InsertedCmp;
531 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 // If we removed all uses, nuke the cmp.
534 if (CI->use_empty())
535 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536
Dale Johannesence0b2372007-06-12 16:50:17 +0000537 return MadeChange;
538}
539
Chris Lattner88a5c832008-11-25 07:09:13 +0000540//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000541// Memory Optimization
542//===----------------------------------------------------------------------===//
543
Chris Lattnerdd77df32007-04-13 20:30:56 +0000544/// IsNonLocalValue - Return true if the specified values are defined in a
545/// different basic block than BB.
546static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
547 if (Instruction *I = dyn_cast<Instruction>(V))
548 return I->getParent() != BB;
549 return false;
550}
551
Bob Wilson4a8ee232009-12-03 21:47:07 +0000552/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000553/// addressing modes that can do significant amounts of computation. As such,
554/// instruction selection will try to get the load or store to do as much
555/// computation as possible for the program. The problem is that isel can only
556/// see within a single block. As such, we sink as much legal addressing mode
557/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000558///
559/// This method is used to optimize both load/store and inline asms with memory
560/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000561bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000562 const Type *AccessTy,
563 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000564 // Figure out what addressing mode will be built up for this operation.
565 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000566 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
567 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000568
Chris Lattnerdd77df32007-04-13 20:30:56 +0000569 // Check to see if any of the instructions supersumed by this addr mode are
570 // non-local to I's BB.
571 bool AnyNonLocal = false;
572 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000573 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000574 AnyNonLocal = true;
575 break;
576 }
577 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000578
Chris Lattnerdd77df32007-04-13 20:30:56 +0000579 // If all the instructions matched are already in this BB, don't do anything.
580 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000581 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000582 return false;
583 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000584
Chris Lattnerdd77df32007-04-13 20:30:56 +0000585 // Insert this computation right after this user. Since our caller is
586 // scanning from the top of the BB to the bottom, reuse of the expr are
587 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000588 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000589
Chris Lattnerdd77df32007-04-13 20:30:56 +0000590 // Now that we determined the addressing expression we want to use and know
591 // that we have to sink it into this block. Check to see if we have already
592 // done this for some other load/store instr in this block. If so, reuse the
593 // computation.
594 Value *&SunkAddr = SunkAddrs[Addr];
595 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000596 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000597 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000598 if (SunkAddr->getType() != Addr->getType())
599 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
600 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000601 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000602 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000603 const Type *IntPtrTy =
604 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000605
Chris Lattnerdd77df32007-04-13 20:30:56 +0000606 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000607
608 // Start with the base register. Do this first so that subsequent address
609 // matching finds it last, which will prevent it from trying to match it
610 // as the scaled value in case it happens to be a mul. That would be
611 // problematic if we've sunk a different mul for the scale, because then
612 // we'd end up sinking both muls.
613 if (AddrMode.BaseReg) {
614 Value *V = AddrMode.BaseReg;
615 if (isa<PointerType>(V->getType()))
616 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
617 if (V->getType() != IntPtrTy)
618 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
619 "sunkaddr", InsertPt);
620 Result = V;
621 }
622
623 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000624 if (AddrMode.Scale) {
625 Value *V = AddrMode.ScaledReg;
626 if (V->getType() == IntPtrTy) {
627 // done.
628 } else if (isa<PointerType>(V->getType())) {
629 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
630 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
631 cast<IntegerType>(V->getType())->getBitWidth()) {
632 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
633 } else {
634 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
635 }
636 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000637 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000638 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000639 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000640 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000641 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000642 else
643 Result = V;
644 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000645
Chris Lattnerdd77df32007-04-13 20:30:56 +0000646 // Add in the BaseGV if present.
647 if (AddrMode.BaseGV) {
648 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
649 InsertPt);
650 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000651 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000652 else
653 Result = V;
654 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000655
Chris Lattnerdd77df32007-04-13 20:30:56 +0000656 // Add in the Base Offset if present.
657 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000658 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000659 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000660 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000661 else
662 Result = V;
663 }
664
665 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000666 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000667 else
668 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
669 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000670
Chris Lattner896617b2008-11-26 03:20:37 +0000671 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000672
Chris Lattnerdd77df32007-04-13 20:30:56 +0000673 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000674 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000675 return true;
676}
677
Evan Cheng9bf12b52008-02-26 02:42:37 +0000678/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000679/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000680/// possible / profitable.
681bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
682 DenseMap<Value*,Value*> &SunkAddrs) {
683 bool MadeChange = false;
684 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
685
686 // Do a prepass over the constraints, canonicalizing them, and building up the
687 // ConstraintOperands list.
688 std::vector<InlineAsm::ConstraintInfo>
689 ConstraintInfos = IA->ParseConstraints();
690
691 /// ConstraintOperands - Information about all of the constraints.
692 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
693 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
694 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
695 ConstraintOperands.
696 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
697 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
698
699 // Compute the value type for each operand.
700 switch (OpInfo.Type) {
701 case InlineAsm::isOutput:
702 if (OpInfo.isIndirect)
703 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
704 break;
705 case InlineAsm::isInput:
706 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
707 break;
708 case InlineAsm::isClobber:
709 // Nothing to do.
710 break;
711 }
712
713 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000714 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
715 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000716
Eli Friedman9ec80952008-02-26 18:37:49 +0000717 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
718 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000719 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000720 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000721 }
722 }
723
724 return MadeChange;
725}
726
Dan Gohmanb00f2362009-10-16 20:59:35 +0000727/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
728/// basic block as the load, unless conditions are unfavorable. This allows
729/// SelectionDAG to fold the extend into the load.
730///
731bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
732 // Look for a load being extended.
733 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
734 if (!LI) return false;
735
736 // If they're already in the same block, there's nothing to do.
737 if (LI->getParent() == I->getParent())
738 return false;
739
740 // If the load has other users and the truncate is not free, this probably
741 // isn't worthwhile.
742 if (!LI->hasOneUse() &&
743 TLI && !TLI->isTruncateFree(I->getType(), LI->getType()))
744 return false;
745
746 // Check whether the target supports casts folded into loads.
747 unsigned LType;
748 if (isa<ZExtInst>(I))
749 LType = ISD::ZEXTLOAD;
750 else {
751 assert(isa<SExtInst>(I) && "Unexpected ext type!");
752 LType = ISD::SEXTLOAD;
753 }
754 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
755 return false;
756
757 // Move the extend into the same block as the load, so that SelectionDAG
758 // can fold it.
759 I->removeFromParent();
760 I->insertAfter(LI);
761 return true;
762}
763
Evan Chengbdcb7262007-12-05 23:58:20 +0000764bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
765 BasicBlock *DefBB = I->getParent();
766
767 // If both result of the {s|z}xt and its source are live out, rewrite all
768 // other uses of the source with result of extension.
769 Value *Src = I->getOperand(0);
770 if (Src->hasOneUse())
771 return false;
772
Evan Cheng696e5c02007-12-13 07:50:36 +0000773 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000774 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000775 return false;
776
Evan Cheng772de512007-12-12 00:51:06 +0000777 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000778 // this block.
779 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000780 return false;
781
Evan Chengbdcb7262007-12-05 23:58:20 +0000782 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000783 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000784 UI != E; ++UI) {
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 DefIsLiveOut = true;
791 break;
792 }
793 if (!DefIsLiveOut)
794 return false;
795
Evan Cheng765dff22007-12-12 02:53:41 +0000796 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000797 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000798 UI != E; ++UI) {
799 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000800 BasicBlock *UserBB = User->getParent();
801 if (UserBB == DefBB) continue;
802 // Be conservative. We don't want this xform to end up introducing
803 // reloads just before load / store instructions.
804 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000805 return false;
806 }
807
Evan Chengbdcb7262007-12-05 23:58:20 +0000808 // InsertedTruncs - Only insert one trunc in each block once.
809 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
810
811 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000812 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000813 UI != E; ++UI) {
814 Use &TheUse = UI.getUse();
815 Instruction *User = cast<Instruction>(*UI);
816
817 // Figure out which BB this ext is used in.
818 BasicBlock *UserBB = User->getParent();
819 if (UserBB == DefBB) continue;
820
821 // Both src and def are live in this block. Rewrite the use.
822 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
823
824 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000825 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000826
Evan Chengbdcb7262007-12-05 23:58:20 +0000827 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
828 }
829
830 // Replace a use of the {s|z}ext source with a use of the result.
831 TheUse = InsertedTrunc;
832
833 MadeChange = true;
834 }
835
836 return MadeChange;
837}
838
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000839// In this pass we look for GEP and cast instructions that are used
840// across basic blocks and rewrite them to improve basic-block-at-a-time
841// selection.
842bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
843 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000844
Evan Chengab631522008-12-19 18:03:11 +0000845 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000846 TerminatorInst *BBTI = BB.getTerminator();
Chris Lattnera4b04212009-10-31 22:04:43 +0000847 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
Evan Chengab631522008-12-19 18:03:11 +0000848 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
849 BasicBlock *SuccBB = BBTI->getSuccessor(i);
850 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
851 SplitEdgeNicely(BBTI, i, BackEdges, this);
852 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000853 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000854
Chris Lattnerdd77df32007-04-13 20:30:56 +0000855 // Keep track of non-local addresses that have been sunk into this block.
856 // This allows us to avoid inserting duplicate code for blocks with multiple
857 // load/stores of the same address.
858 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000859
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000860 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
861 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000862
Chris Lattnerdd77df32007-04-13 20:30:56 +0000863 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000864 // If the source of the cast is a constant, then this should have
865 // already been constant folded. The only reason NOT to constant fold
866 // it is if something (e.g. LSR) was careful to place the constant
867 // evaluation in a block other than then one that uses it (e.g. to hoist
868 // the address of globals out of a loop). If this is the case, we don't
869 // want to forward-subst the cast.
870 if (isa<Constant>(CI->getOperand(0)))
871 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000872
Evan Chengbdcb7262007-12-05 23:58:20 +0000873 bool Change = false;
874 if (TLI) {
875 Change = OptimizeNoopCopyExpression(CI, *TLI);
876 MadeChange |= Change;
877 }
878
Dan Gohmanb00f2362009-10-16 20:59:35 +0000879 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
880 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000881 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000882 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000883 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
884 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000885 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
886 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000887 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
888 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000889 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
890 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000891 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
892 SI->getOperand(0)->getType(),
893 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000895 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000896 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000897 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 GEPI->getName(), GEPI);
899 GEPI->replaceAllUsesWith(NC);
900 GEPI->eraseFromParent();
901 MadeChange = true;
902 BBI = NC;
903 }
904 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
905 // If we found an inline asm expession, and if the target knows how to
906 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000907 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
908 if (TLI->ExpandInlineAsm(CI)) {
909 BBI = BB.begin();
910 // Avoid processing instructions out of order, which could cause
911 // reuse before a value is defined.
912 SunkAddrs.clear();
913 } else
914 // Sink address computing for memory operands into the block.
915 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
916 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000917 }
918 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000919
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000920 return MadeChange;
921}