blob: 6e01ed481565c3e2e17f9018943a79d4af4cbfc7 [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 Chengab631522008-12-19 18:03:11 +000035#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000039#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000040using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000041using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000042
Evan Chengab631522008-12-19 18:03:11 +000043static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
44 cl::init(false), cl::Hidden);
45
Eric Christopher692bf6b2008-09-24 05:32:41 +000046namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000047 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048 /// TLI - Keep a pointer of a TargetLowering to consult for determining
49 /// transformation profitability.
50 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000051 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000052
53 /// BackEdges - Keep a set of all the loop back edges.
54 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000055 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000056 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000057 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000058 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000061
Andreas Neustifterad809812009-09-16 09:26:52 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addPreserved<ProfileInfo>();
64 }
65
Dan Gohmanaa0e5232010-02-05 19:24:11 +000066 virtual void releaseMemory() {
67 BackEdges.clear();
68 }
69
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000070 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000071 bool EliminateMostlyEmptyBlocks(Function &F);
72 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
73 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000075 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
76 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000077 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
78 DenseMap<Value*,Value*> &SunkAddrs);
Dan Gohmanb00f2362009-10-16 20:59:35 +000079 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000080 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000081 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000082 };
83}
Devang Patel794fd752007-05-01 21:15:47 +000084
Devang Patel19974732007-05-03 01:11:54 +000085char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000086static RegisterPass<CodeGenPrepare> X("codegenprepare",
87 "Optimize for code generation");
88
89FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
90 return new CodeGenPrepare(TLI);
91}
92
Evan Chengab631522008-12-19 18:03:11 +000093/// findLoopBackEdges - Do a DFS walk to find loop back edges.
94///
Mike Stumpfe095f32009-05-04 18:40:41 +000095void CodeGenPrepare::findLoopBackEdges(const Function &F) {
96 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
97 FindFunctionBackedges(F, Edges);
98
99 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000100}
101
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000102
103bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000105
Evan Cheng04149f72009-12-17 09:39:49 +0000106 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000107 // First pass, eliminate blocks that contain only PHI nodes and an
108 // unconditional branch.
109 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000110
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000111 // Now find loop back edges.
112 findLoopBackEdges(F);
113
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000114 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 while (MadeChange) {
116 MadeChange = false;
117 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
118 MadeChange |= OptimizeBlock(*BB);
119 EverMadeChange |= MadeChange;
120 }
121 return EverMadeChange;
122}
123
Dale Johannesen2d697242009-03-27 01:13:37 +0000124/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
125/// debug info directives, and an unconditional branch. Passes before isel
126/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
127/// isel. Start by eliminating these blocks so we can split them the way we
128/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000129bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
130 bool MadeChange = false;
131 // Note that this intentionally skips the entry block.
132 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
133 BasicBlock *BB = I++;
134
135 // If this block doesn't end with an uncond branch, ignore it.
136 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
137 if (!BI || !BI->isUnconditional())
138 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000139
Dale Johannesen2d697242009-03-27 01:13:37 +0000140 // If the instruction before the branch (skipping debug info) isn't a phi
141 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142 BasicBlock::iterator BBI = BI;
143 if (BBI != BB->begin()) {
144 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000145 while (isa<DbgInfoIntrinsic>(BBI)) {
146 if (BBI == BB->begin())
147 break;
148 --BBI;
149 }
150 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
151 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000152 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000153
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000154 // Do not break infinite loops.
155 BasicBlock *DestBB = BI->getSuccessor(0);
156 if (DestBB == BB)
157 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000158
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000159 if (!CanMergeBlocks(BB, DestBB))
160 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000161
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000162 EliminateMostlyEmptyBlock(BB);
163 MadeChange = true;
164 }
165 return MadeChange;
166}
167
168/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
169/// single uncond branch between them, and BB contains no other non-phi
170/// instructions.
171bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
172 const BasicBlock *DestBB) const {
173 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
174 // the successor. If there are more complex condition (e.g. preheaders),
175 // don't mess around with them.
176 BasicBlock::const_iterator BBI = BB->begin();
177 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
178 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
179 UI != E; ++UI) {
180 const Instruction *User = cast<Instruction>(*UI);
181 if (User->getParent() != DestBB || !isa<PHINode>(User))
182 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000183 // If User is inside DestBB block and it is a PHINode then check
184 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000185 // a complex condition (e.g. preheaders) we want to avoid here.
186 if (User->getParent() == DestBB) {
187 if (const PHINode *UPN = dyn_cast<PHINode>(User))
188 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
189 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
190 if (Insn && Insn->getParent() == BB &&
191 Insn->getParent() != UPN->getIncomingBlock(I))
192 return false;
193 }
194 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000195 }
196 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000197
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000198 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
199 // and DestBB may have conflicting incoming values for the block. If so, we
200 // can't merge the block.
201 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
202 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000203
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000204 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000205 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000206 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
207 // It is faster to get preds from a PHI than with pred_iterator.
208 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
209 BBPreds.insert(BBPN->getIncomingBlock(i));
210 } else {
211 BBPreds.insert(pred_begin(BB), pred_end(BB));
212 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000213
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000214 // Walk the preds of DestBB.
215 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
216 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
217 if (BBPreds.count(Pred)) { // Common predecessor?
218 BBI = DestBB->begin();
219 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
220 const Value *V1 = PN->getIncomingValueForBlock(Pred);
221 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000222
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000223 // If V2 is a phi node in BB, look up what the mapped value will be.
224 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
225 if (V2PN->getParent() == BB)
226 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 // If there is a conflict, bail out.
229 if (V1 != V2) return false;
230 }
231 }
232 }
233
234 return true;
235}
236
237
238/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
239/// an unconditional branch in it.
240void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
241 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
242 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000243
David Greene68d67fd2010-01-05 01:27:11 +0000244 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000245
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000246 // If the destination block has a single pred, then this is a trivial edge,
247 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000248 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000249 if (SinglePred != DestBB) {
250 // Remember if SinglePred was the entry block of the function. If so, we
251 // will need to move BB back to the entry position.
252 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000253 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000254
Chris Lattnerf5102a02008-11-28 19:54:49 +0000255 if (isEntry && BB != &BB->getParent()->getEntryBlock())
256 BB->moveBefore(&BB->getParent()->getEntryBlock());
257
David Greene68d67fd2010-01-05 01:27:11 +0000258 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000259 return;
260 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000262
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000263 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
264 // to handle the new incoming edges it is about to have.
265 PHINode *PN;
266 for (BasicBlock::iterator BBI = DestBB->begin();
267 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
268 // Remove the incoming value for BB, and remember it.
269 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000270
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000271 // Two options: either the InVal is a phi node defined in BB or it is some
272 // value that dominates BB.
273 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
274 if (InValPhi && InValPhi->getParent() == BB) {
275 // Add all of the input values of the input PHI as inputs of this phi.
276 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
277 PN->addIncoming(InValPhi->getIncomingValue(i),
278 InValPhi->getIncomingBlock(i));
279 } else {
280 // Otherwise, add one instance of the dominating value for each edge that
281 // we will be adding.
282 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
283 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
284 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
285 } else {
286 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
287 PN->addIncoming(InVal, *PI);
288 }
289 }
290 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000291
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 // The PHIs are now updated, change everything that refers to BB to use
293 // DestBB and remove BB.
294 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000295 if (PFI) {
296 PFI->replaceAllUses(BB, DestBB);
297 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000298 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000299 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000300
David Greene68d67fd2010-01-05 01:27:11 +0000301 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000302}
303
Chris Lattner98d5c312010-02-13 05:35:08 +0000304/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
305/// lives in to see if there is a block that we can reuse as a critical edge
306/// from TIBB.
307static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
308 BasicBlock *Dest = DestPHI->getParent();
309
310 /// TIPHIValues - This array is lazily computed to determine the values of
311 /// PHIs in Dest that TI would provide.
312 SmallVector<Value*, 32> TIPHIValues;
313
314 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
315 unsigned TIBBEntryNo = 0;
316
317 // Check to see if Dest has any blocks that can be used as a split edge for
318 // this terminator.
319 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
320 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
321 // To be usable, the pred has to end with an uncond branch to the dest.
322 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
323 if (!PredBr || !PredBr->isUnconditional())
324 continue;
325 // Must be empty other than the branch and debug info.
326 BasicBlock::iterator I = Pred->begin();
327 while (isa<DbgInfoIntrinsic>(I))
328 I++;
329 if (&*I != PredBr)
330 continue;
331 // Cannot be the entry block; its label does not get emitted.
332 if (Pred == &Dest->getParent()->getEntryBlock())
333 continue;
334
335 // Finally, since we know that Dest has phi nodes in it, we have to make
336 // sure that jumping to Pred will have the same effect as going to Dest in
337 // terms of PHI values.
338 PHINode *PN;
339 unsigned PHINo = 0;
340 unsigned PredEntryNo = pi;
341
342 bool FoundMatch = true;
343 for (BasicBlock::iterator I = Dest->begin();
344 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
345 if (PHINo == TIPHIValues.size()) {
346 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
347 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
348 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
349 }
350
351 // If the PHI entry doesn't work, we can't use this pred.
352 if (PN->getIncomingBlock(PredEntryNo) != Pred)
353 PredEntryNo = PN->getBasicBlockIndex(Pred);
354
355 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
356 FoundMatch = false;
357 break;
358 }
359 }
360
361 // If we found a workable predecessor, change TI to branch to Succ.
362 if (FoundMatch)
363 return Pred;
364 }
365 return 0;
366}
367
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000368
Chris Lattnerebe80752007-12-24 19:32:55 +0000369/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000370/// successor if it will improve codegen. We only do this if the successor has
371/// phi nodes (otherwise critical edges are ok). If there is already another
372/// predecessor of the succ that is empty (and thus has no phi nodes), use it
373/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000374static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000375 SmallSet<std::pair<const BasicBlock*,
376 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000377 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000378 BasicBlock *TIBB = TI->getParent();
379 BasicBlock *Dest = TI->getSuccessor(SuccNum);
380 assert(isa<PHINode>(Dest->begin()) &&
381 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000382 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Evan Chengfc0b80d2009-03-13 22:59:14 +0000384 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000385 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000386 if (Invoke->getSuccessor(1) == Dest)
387 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000388
Chris Lattnerebe80752007-12-24 19:32:55 +0000389 // As a hack, never split backedges of loops. Even though the copy for any
390 // PHIs inserted on the backedge would be dead for exits from the loop, we
391 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000392 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000393 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000394
Evan Chengab631522008-12-19 18:03:11 +0000395 if (!FactorCommonPreds) {
Chris Lattner98d5c312010-02-13 05:35:08 +0000396 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
397 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
398 if (PFI)
399 PFI->splitEdge(TIBB, Dest, ReuseBB);
400 Dest->removePredecessor(TIBB);
401 TI->setSuccessor(SuccNum, ReuseBB);
402 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 }
Chris Lattner98d5c312010-02-13 05:35:08 +0000404
Evan Chengab631522008-12-19 18:03:11 +0000405 SplitCriticalEdge(TI, SuccNum, P, true);
406 return;
407 }
408
409 PHINode *PN;
410 SmallVector<Value*, 8> TIPHIValues;
411 for (BasicBlock::iterator I = Dest->begin();
412 (PN = dyn_cast<PHINode>(I)); ++I)
413 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
414
415 SmallVector<BasicBlock*, 8> IdenticalPreds;
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000416
417 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
418 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
Evan Chengab631522008-12-19 18:03:11 +0000419 if (BackEdges.count(std::make_pair(Pred, Dest)))
420 continue;
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000421 if (Pred == TIBB) {
Evan Chengab631522008-12-19 18:03:11 +0000422 IdenticalPreds.push_back(Pred);
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000423 continue;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000424 }
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000425 bool Identical = true;
426 unsigned PHINo = 0;
427 for (BasicBlock::iterator I = Dest->begin();
428 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
429 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
430 Identical = false;
431 break;
432 }
433 if (Identical)
434 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000435 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436
Evan Chengab631522008-12-19 18:03:11 +0000437 assert(!IdenticalPreds.empty());
438 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
439 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000440}
441
Evan Chengab631522008-12-19 18:03:11 +0000442
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000444/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
445/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000446/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000447///
448/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000449///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000452 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
453 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454
Chris Lattnerdd77df32007-04-13 20:30:56 +0000455 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000456 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000457 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000458
Chris Lattnerdd77df32007-04-13 20:30:56 +0000459 // If this is an extension, it will be a zero or sign extension, which
460 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000461 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdd77df32007-04-13 20:30:56 +0000463 // If these values will be promoted, find out what they will be promoted
464 // to. This helps us consider truncates on PPC as noop copies when they
465 // are.
Owen Anderson23b9b192009-08-12 00:36:31 +0000466 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
467 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
468 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
469 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470
Chris Lattnerdd77df32007-04-13 20:30:56 +0000471 // If, after promotion, these are the same types, this is a noop copy.
472 if (SrcVT != DstVT)
473 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000478 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000480 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 UI != E; ) {
483 Use &TheUse = UI.getUse();
484 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 // Figure out which BB this cast is used in. For PHI's this is the
487 // appropriate predecessor block.
488 BasicBlock *UserBB = User->getParent();
489 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000490 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000493 // Preincrement use iterator so we don't invalidate it.
494 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 // If this user is in the same block as the cast, don't change the cast.
497 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000498
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000499 // If we have already inserted a cast into this block, use it.
500 CastInst *&InsertedCast = InsertedCasts[UserBB];
501
502 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000503 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
505 InsertedCast =
506 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 InsertPt);
508 MadeChange = true;
509 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Dale Johannesence0b2372007-06-12 16:50:17 +0000511 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000512 TheUse = InsertedCast;
513 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000515 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000516 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000517 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000518 MadeChange = true;
519 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000521 return MadeChange;
522}
523
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000525/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000526/// a clear win except on targets with multiple condition code registers
527/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000528///
529/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000530static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 /// InsertedCmp - Only insert a cmp in each block once.
534 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 UI != E; ) {
539 Use &TheUse = UI.getUse();
540 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // Preincrement use iterator so we don't invalidate it.
543 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // Don't bother for PHI nodes.
546 if (isa<PHINode>(User))
547 continue;
548
549 // Figure out which BB this cmp is used in.
550 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000551
Dale Johannesence0b2372007-06-12 16:50:17 +0000552 // If this user is in the same block as the cmp, don't change the cmp.
553 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000554
Dale Johannesence0b2372007-06-12 16:50:17 +0000555 // If we have already inserted a cmp into this block, use it.
556 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
557
558 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000559 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
561 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000562 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000563 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 CI->getOperand(1), "", InsertPt);
565 MadeChange = true;
566 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000567
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 // Replace a use of the cmp with a use of the new cmp.
569 TheUse = InsertedCmp;
570 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000571
Dale Johannesence0b2372007-06-12 16:50:17 +0000572 // If we removed all uses, nuke the cmp.
573 if (CI->use_empty())
574 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000575
Dale Johannesence0b2372007-06-12 16:50:17 +0000576 return MadeChange;
577}
578
Chris Lattner88a5c832008-11-25 07:09:13 +0000579//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000580// Memory Optimization
581//===----------------------------------------------------------------------===//
582
Chris Lattnerdd77df32007-04-13 20:30:56 +0000583/// IsNonLocalValue - Return true if the specified values are defined in a
584/// different basic block than BB.
585static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
586 if (Instruction *I = dyn_cast<Instruction>(V))
587 return I->getParent() != BB;
588 return false;
589}
590
Bob Wilson4a8ee232009-12-03 21:47:07 +0000591/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000592/// addressing modes that can do significant amounts of computation. As such,
593/// instruction selection will try to get the load or store to do as much
594/// computation as possible for the program. The problem is that isel can only
595/// see within a single block. As such, we sink as much legal addressing mode
596/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000597///
598/// This method is used to optimize both load/store and inline asms with memory
599/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000600bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000601 const Type *AccessTy,
602 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000603 // Figure out what addressing mode will be built up for this operation.
604 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000605 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
606 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000607
Chris Lattnerdd77df32007-04-13 20:30:56 +0000608 // Check to see if any of the instructions supersumed by this addr mode are
609 // non-local to I's BB.
610 bool AnyNonLocal = false;
611 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000612 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000613 AnyNonLocal = true;
614 break;
615 }
616 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000617
Chris Lattnerdd77df32007-04-13 20:30:56 +0000618 // If all the instructions matched are already in this BB, don't do anything.
619 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000620 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000621 return false;
622 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000623
Chris Lattnerdd77df32007-04-13 20:30:56 +0000624 // Insert this computation right after this user. Since our caller is
625 // scanning from the top of the BB to the bottom, reuse of the expr are
626 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000627 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000628
Chris Lattnerdd77df32007-04-13 20:30:56 +0000629 // Now that we determined the addressing expression we want to use and know
630 // that we have to sink it into this block. Check to see if we have already
631 // done this for some other load/store instr in this block. If so, reuse the
632 // computation.
633 Value *&SunkAddr = SunkAddrs[Addr];
634 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000635 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000636 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000637 if (SunkAddr->getType() != Addr->getType())
638 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
639 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000640 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000641 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000642 const Type *IntPtrTy =
643 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000644
Chris Lattnerdd77df32007-04-13 20:30:56 +0000645 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000646
647 // Start with the base register. Do this first so that subsequent address
648 // matching finds it last, which will prevent it from trying to match it
649 // as the scaled value in case it happens to be a mul. That would be
650 // problematic if we've sunk a different mul for the scale, because then
651 // we'd end up sinking both muls.
652 if (AddrMode.BaseReg) {
653 Value *V = AddrMode.BaseReg;
654 if (isa<PointerType>(V->getType()))
655 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
656 if (V->getType() != IntPtrTy)
657 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
658 "sunkaddr", InsertPt);
659 Result = V;
660 }
661
662 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000663 if (AddrMode.Scale) {
664 Value *V = AddrMode.ScaledReg;
665 if (V->getType() == IntPtrTy) {
666 // done.
667 } else if (isa<PointerType>(V->getType())) {
668 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
669 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
670 cast<IntegerType>(V->getType())->getBitWidth()) {
671 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
672 } else {
673 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
674 }
675 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000676 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000677 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000678 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000679 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000680 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000681 else
682 Result = V;
683 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000684
Chris Lattnerdd77df32007-04-13 20:30:56 +0000685 // Add in the BaseGV if present.
686 if (AddrMode.BaseGV) {
687 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
688 InsertPt);
689 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000690 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000691 else
692 Result = V;
693 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000694
Chris Lattnerdd77df32007-04-13 20:30:56 +0000695 // Add in the Base Offset if present.
696 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000697 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000698 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000699 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000700 else
701 Result = V;
702 }
703
704 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000705 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000706 else
707 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
708 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000709
Chris Lattner896617b2008-11-26 03:20:37 +0000710 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000711
Chris Lattnerdd77df32007-04-13 20:30:56 +0000712 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000713 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000714 return true;
715}
716
Evan Cheng9bf12b52008-02-26 02:42:37 +0000717/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000718/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000719/// possible / profitable.
720bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
721 DenseMap<Value*,Value*> &SunkAddrs) {
722 bool MadeChange = false;
723 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
724
725 // Do a prepass over the constraints, canonicalizing them, and building up the
726 // ConstraintOperands list.
727 std::vector<InlineAsm::ConstraintInfo>
728 ConstraintInfos = IA->ParseConstraints();
729
730 /// ConstraintOperands - Information about all of the constraints.
731 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
732 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
733 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
734 ConstraintOperands.
735 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
736 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
737
738 // Compute the value type for each operand.
739 switch (OpInfo.Type) {
740 case InlineAsm::isOutput:
741 if (OpInfo.isIndirect)
742 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
743 break;
744 case InlineAsm::isInput:
745 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
746 break;
747 case InlineAsm::isClobber:
748 // Nothing to do.
749 break;
750 }
751
752 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000753 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
754 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000755
Eli Friedman9ec80952008-02-26 18:37:49 +0000756 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
757 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000758 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000759 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000760 }
761 }
762
763 return MadeChange;
764}
765
Dan Gohmanb00f2362009-10-16 20:59:35 +0000766/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
767/// basic block as the load, unless conditions are unfavorable. This allows
768/// SelectionDAG to fold the extend into the load.
769///
770bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
771 // Look for a load being extended.
772 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
773 if (!LI) return false;
774
775 // If they're already in the same block, there's nothing to do.
776 if (LI->getParent() == I->getParent())
777 return false;
778
779 // If the load has other users and the truncate is not free, this probably
780 // isn't worthwhile.
781 if (!LI->hasOneUse() &&
782 TLI && !TLI->isTruncateFree(I->getType(), LI->getType()))
783 return false;
784
785 // Check whether the target supports casts folded into loads.
786 unsigned LType;
787 if (isa<ZExtInst>(I))
788 LType = ISD::ZEXTLOAD;
789 else {
790 assert(isa<SExtInst>(I) && "Unexpected ext type!");
791 LType = ISD::SEXTLOAD;
792 }
793 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
794 return false;
795
796 // Move the extend into the same block as the load, so that SelectionDAG
797 // can fold it.
798 I->removeFromParent();
799 I->insertAfter(LI);
800 return true;
801}
802
Evan Chengbdcb7262007-12-05 23:58:20 +0000803bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
804 BasicBlock *DefBB = I->getParent();
805
806 // If both result of the {s|z}xt and its source are live out, rewrite all
807 // other uses of the source with result of extension.
808 Value *Src = I->getOperand(0);
809 if (Src->hasOneUse())
810 return false;
811
Evan Cheng696e5c02007-12-13 07:50:36 +0000812 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000813 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000814 return false;
815
Evan Cheng772de512007-12-12 00:51:06 +0000816 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000817 // this block.
818 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000819 return false;
820
Evan Chengbdcb7262007-12-05 23:58:20 +0000821 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000822 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000823 UI != E; ++UI) {
824 Instruction *User = cast<Instruction>(*UI);
825
826 // Figure out which BB this ext is used in.
827 BasicBlock *UserBB = User->getParent();
828 if (UserBB == DefBB) continue;
829 DefIsLiveOut = true;
830 break;
831 }
832 if (!DefIsLiveOut)
833 return false;
834
Evan Cheng765dff22007-12-12 02:53:41 +0000835 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000836 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000837 UI != E; ++UI) {
838 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000839 BasicBlock *UserBB = User->getParent();
840 if (UserBB == DefBB) continue;
841 // Be conservative. We don't want this xform to end up introducing
842 // reloads just before load / store instructions.
843 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000844 return false;
845 }
846
Evan Chengbdcb7262007-12-05 23:58:20 +0000847 // InsertedTruncs - Only insert one trunc in each block once.
848 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
849
850 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000851 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000852 UI != E; ++UI) {
853 Use &TheUse = UI.getUse();
854 Instruction *User = cast<Instruction>(*UI);
855
856 // Figure out which BB this ext is used in.
857 BasicBlock *UserBB = User->getParent();
858 if (UserBB == DefBB) continue;
859
860 // Both src and def are live in this block. Rewrite the use.
861 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
862
863 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000864 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000865
Evan Chengbdcb7262007-12-05 23:58:20 +0000866 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
867 }
868
869 // Replace a use of the {s|z}ext source with a use of the result.
870 TheUse = InsertedTrunc;
871
872 MadeChange = true;
873 }
874
875 return MadeChange;
876}
877
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000878// In this pass we look for GEP and cast instructions that are used
879// across basic blocks and rewrite them to improve basic-block-at-a-time
880// selection.
881bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
882 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000883
Evan Chengab631522008-12-19 18:03:11 +0000884 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000885 TerminatorInst *BBTI = BB.getTerminator();
Chris Lattnera4b04212009-10-31 22:04:43 +0000886 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
Evan Chengab631522008-12-19 18:03:11 +0000887 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
888 BasicBlock *SuccBB = BBTI->getSuccessor(i);
889 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
890 SplitEdgeNicely(BBTI, i, BackEdges, this);
891 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000892 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000893
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 // Keep track of non-local addresses that have been sunk into this block.
895 // This allows us to avoid inserting duplicate code for blocks with multiple
896 // load/stores of the same address.
897 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000898
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000899 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
900 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000901
Chris Lattnerdd77df32007-04-13 20:30:56 +0000902 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000903 // If the source of the cast is a constant, then this should have
904 // already been constant folded. The only reason NOT to constant fold
905 // it is if something (e.g. LSR) was careful to place the constant
906 // evaluation in a block other than then one that uses it (e.g. to hoist
907 // the address of globals out of a loop). If this is the case, we don't
908 // want to forward-subst the cast.
909 if (isa<Constant>(CI->getOperand(0)))
910 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Evan Chengbdcb7262007-12-05 23:58:20 +0000912 bool Change = false;
913 if (TLI) {
914 Change = OptimizeNoopCopyExpression(CI, *TLI);
915 MadeChange |= Change;
916 }
917
Dan Gohmanb00f2362009-10-16 20:59:35 +0000918 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
919 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000920 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000921 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000922 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
923 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000924 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
925 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000926 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
927 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000928 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
929 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000930 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
931 SI->getOperand(0)->getType(),
932 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000934 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000935 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000936 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000937 GEPI->getName(), GEPI);
938 GEPI->replaceAllUsesWith(NC);
939 GEPI->eraseFromParent();
940 MadeChange = true;
941 BBI = NC;
942 }
943 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
944 // If we found an inline asm expession, and if the target knows how to
945 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000946 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
947 if (TLI->ExpandInlineAsm(CI)) {
948 BBI = BB.begin();
949 // Avoid processing instructions out of order, which could cause
950 // reuse before a value is defined.
951 SunkAddrs.clear();
952 } else
953 // Sink address computing for memory operands into the block.
954 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
955 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000956 }
957 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000958
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000959 return MadeChange;
960}