blob: 020ec57a43d113eee250bb33fd4b2b187d741672 [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"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000025#include "llvm/Analysis/Dominators.h"
Owen Andersond5f86842010-12-23 20:57:35 +000026#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000027#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/Target/TargetData.h"
Chad Rosier618c1db2011-12-01 03:08:23 +000029#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000031#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000033#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000036#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000037#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000038#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000039#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000043#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000044#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000045#include "llvm/Support/IRBuilder.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000046#include "llvm/Support/ValueHandle.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000063
Cameron Zwarich899eaa32011-03-11 21:52:04 +000064static cl::opt<bool> DisableBranchOpts(
65 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
66 cl::desc("Disable branch optimizations in CodeGenPrepare"));
67
Bill Wendlinge3e394d2012-03-04 10:46:01 +000068// FIXME: Remove this abomination once all of the tests pass without it!
69static cl::opt<bool> DisableDeleteDeadBlocks(
70 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
71 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
72
Eric Christopher692bf6b2008-09-24 05:32:41 +000073namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000074 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000075 /// TLI - Keep a pointer of a TargetLowering to consult for determining
76 /// transformation profitability.
77 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000078 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000079 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000080 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000081
82 /// CurInstIterator - As we scan instructions optimizing them, this is the
83 /// next instruction to optimize. Xforms that can invalidate this should
84 /// update it.
85 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000086
Evan Cheng485fafc2011-03-21 01:19:09 +000087 /// Keeps track of non-local addresses that have been sunk into a block.
88 /// This allows us to avoid inserting duplicate code for blocks with
89 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000090 DenseMap<Value*, Value*> SunkAddrs;
91
Devang Patel52e37df2011-03-24 15:35:25 +000092 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000093 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000094 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000095
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000096 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000097 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000098 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000099 : FunctionPass(ID), TLI(tli) {
100 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
101 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000102 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000103
Andreas Neustifterad809812009-09-16 09:26:52 +0000104 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000105 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000106 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000107 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000108 }
109
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000111 bool EliminateMostlyEmptyBlocks(Function &F);
112 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
113 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000114 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000115 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000116 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000117 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000118 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000119 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000120 bool OptimizeExtUses(Instruction *I);
Evan Cheng485fafc2011-03-21 01:19:09 +0000121 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000122 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000123 };
124}
Devang Patel794fd752007-05-01 21:15:47 +0000125
Devang Patel19974732007-05-03 01:11:54 +0000126char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000127INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
128 "Optimize for code generation", false, false)
129INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
130INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000131 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132
133FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
134 return new CodeGenPrepare(TLI);
135}
136
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000137bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000138 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000139
Devang Patel52e37df2011-03-24 15:35:25 +0000140 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000141 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000142 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000143 PFI = getAnalysisIfAvailable<ProfileInfo>();
Evan Cheng485fafc2011-03-21 01:19:09 +0000144
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000145 // First pass, eliminate blocks that contain only PHI nodes and an
146 // unconditional branch.
147 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Devang Patelf56ea612011-08-18 00:50:51 +0000149 // llvm.dbg.value is far away from the value then iSel may not be able
150 // handle it properly. iSel will drop llvm.dbg.value if it can not
151 // find a node corresponding to the value.
152 EverMadeChange |= PlaceDbgValues(F);
153
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000154 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000155 while (MadeChange) {
156 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000157 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
158 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000159 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000160 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000161 EverMadeChange |= MadeChange;
162 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000163
164 SunkAddrs.clear();
165
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000166 if (!DisableBranchOpts) {
167 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000168 SmallPtrSet<BasicBlock*, 8> WorkList;
169 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
170 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000171 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000172 if (!MadeChange) continue;
173
174 for (SmallVectorImpl<BasicBlock*>::iterator
175 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
176 if (pred_begin(*II) == pred_end(*II))
177 WorkList.insert(*II);
178 }
179
180 if (!DisableDeleteDeadBlocks)
181 for (SmallPtrSet<BasicBlock*, 8>::iterator
182 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
183 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000184
Evan Cheng485fafc2011-03-21 01:19:09 +0000185 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000186 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000187 EverMadeChange |= MadeChange;
188 }
189
Devang Patel52e37df2011-03-24 15:35:25 +0000190 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000191 DT->DT->recalculate(F);
192
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000193 return EverMadeChange;
194}
195
Dale Johannesen2d697242009-03-27 01:13:37 +0000196/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
197/// debug info directives, and an unconditional branch. Passes before isel
198/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
199/// isel. Start by eliminating these blocks so we can split them the way we
200/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000201bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
202 bool MadeChange = false;
203 // Note that this intentionally skips the entry block.
204 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
205 BasicBlock *BB = I++;
206
207 // If this block doesn't end with an uncond branch, ignore it.
208 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
209 if (!BI || !BI->isUnconditional())
210 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Dale Johannesen2d697242009-03-27 01:13:37 +0000212 // If the instruction before the branch (skipping debug info) isn't a phi
213 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000214 BasicBlock::iterator BBI = BI;
215 if (BBI != BB->begin()) {
216 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000217 while (isa<DbgInfoIntrinsic>(BBI)) {
218 if (BBI == BB->begin())
219 break;
220 --BBI;
221 }
222 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
223 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000225
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000226 // Do not break infinite loops.
227 BasicBlock *DestBB = BI->getSuccessor(0);
228 if (DestBB == BB)
229 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000230
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000231 if (!CanMergeBlocks(BB, DestBB))
232 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000233
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 EliminateMostlyEmptyBlock(BB);
235 MadeChange = true;
236 }
237 return MadeChange;
238}
239
240/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
241/// single uncond branch between them, and BB contains no other non-phi
242/// instructions.
243bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
244 const BasicBlock *DestBB) const {
245 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
246 // the successor. If there are more complex condition (e.g. preheaders),
247 // don't mess around with them.
248 BasicBlock::const_iterator BBI = BB->begin();
249 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000250 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 UI != E; ++UI) {
252 const Instruction *User = cast<Instruction>(*UI);
253 if (User->getParent() != DestBB || !isa<PHINode>(User))
254 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000255 // If User is inside DestBB block and it is a PHINode then check
256 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000257 // a complex condition (e.g. preheaders) we want to avoid here.
258 if (User->getParent() == DestBB) {
259 if (const PHINode *UPN = dyn_cast<PHINode>(User))
260 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
261 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
262 if (Insn && Insn->getParent() == BB &&
263 Insn->getParent() != UPN->getIncomingBlock(I))
264 return false;
265 }
266 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000267 }
268 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000269
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
271 // and DestBB may have conflicting incoming values for the block. If so, we
272 // can't merge the block.
273 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
274 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000275
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000277 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000278 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
279 // It is faster to get preds from a PHI than with pred_iterator.
280 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
281 BBPreds.insert(BBPN->getIncomingBlock(i));
282 } else {
283 BBPreds.insert(pred_begin(BB), pred_end(BB));
284 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 // Walk the preds of DestBB.
287 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
288 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
289 if (BBPreds.count(Pred)) { // Common predecessor?
290 BBI = DestBB->begin();
291 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
292 const Value *V1 = PN->getIncomingValueForBlock(Pred);
293 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000294
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 // If V2 is a phi node in BB, look up what the mapped value will be.
296 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
297 if (V2PN->getParent() == BB)
298 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 // If there is a conflict, bail out.
301 if (V1 != V2) return false;
302 }
303 }
304 }
305
306 return true;
307}
308
309
310/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
311/// an unconditional branch in it.
312void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
313 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
314 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000315
David Greene68d67fd2010-01-05 01:27:11 +0000316 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000317
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000318 // If the destination block has a single pred, then this is a trivial edge,
319 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000320 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000321 if (SinglePred != DestBB) {
322 // Remember if SinglePred was the entry block of the function. If so, we
323 // will need to move BB back to the entry position.
324 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000325 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000326
Chris Lattnerf5102a02008-11-28 19:54:49 +0000327 if (isEntry && BB != &BB->getParent()->getEntryBlock())
328 BB->moveBefore(&BB->getParent()->getEntryBlock());
329
David Greene68d67fd2010-01-05 01:27:11 +0000330 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000331 return;
332 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000333 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000334
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000335 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
336 // to handle the new incoming edges it is about to have.
337 PHINode *PN;
338 for (BasicBlock::iterator BBI = DestBB->begin();
339 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
340 // Remove the incoming value for BB, and remember it.
341 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000342
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 // Two options: either the InVal is a phi node defined in BB or it is some
344 // value that dominates BB.
345 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
346 if (InValPhi && InValPhi->getParent() == BB) {
347 // Add all of the input values of the input PHI as inputs of this phi.
348 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
349 PN->addIncoming(InValPhi->getIncomingValue(i),
350 InValPhi->getIncomingBlock(i));
351 } else {
352 // Otherwise, add one instance of the dominating value for each edge that
353 // we will be adding.
354 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
355 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
356 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
357 } else {
358 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
359 PN->addIncoming(InVal, *PI);
360 }
361 }
362 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000364 // The PHIs are now updated, change everything that refers to BB to use
365 // DestBB and remove BB.
366 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000367 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000368 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
369 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
370 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
371 DT->changeImmediateDominator(DestBB, NewIDom);
372 DT->eraseNode(BB);
373 }
Evan Cheng04149f72009-12-17 09:39:49 +0000374 if (PFI) {
375 PFI->replaceAllUses(BB, DestBB);
376 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000377 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000378 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000379 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000380
David Greene68d67fd2010-01-05 01:27:11 +0000381 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000382}
383
Chris Lattnerdd77df32007-04-13 20:30:56 +0000384/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000385/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
386/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000387/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000388///
389/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000390///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000391static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000393 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
394 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Chris Lattnerdd77df32007-04-13 20:30:56 +0000396 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000397 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000398 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000399
Chris Lattnerdd77df32007-04-13 20:30:56 +0000400 // If this is an extension, it will be a zero or sign extension, which
401 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000402 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403
Chris Lattnerdd77df32007-04-13 20:30:56 +0000404 // If these values will be promoted, find out what they will be promoted
405 // to. This helps us consider truncates on PPC as noop copies when they
406 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000407 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
408 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000409 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000410 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
411 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000412 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000413
Chris Lattnerdd77df32007-04-13 20:30:56 +0000414 // If, after promotion, these are the same types, this is a noop copy.
415 if (SrcVT != DstVT)
416 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000417
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000418 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000419
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000420 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000421 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000424 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000425 UI != E; ) {
426 Use &TheUse = UI.getUse();
427 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000429 // Figure out which BB this cast is used in. For PHI's this is the
430 // appropriate predecessor block.
431 BasicBlock *UserBB = User->getParent();
432 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000433 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000434 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000436 // Preincrement use iterator so we don't invalidate it.
437 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 // If this user is in the same block as the cast, don't change the cast.
440 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000442 // If we have already inserted a cast into this block, use it.
443 CastInst *&InsertedCast = InsertedCasts[UserBB];
444
445 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000446 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447 InsertedCast =
448 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000449 InsertPt);
450 MadeChange = true;
451 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000455 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000458 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000459 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000460 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000461 MadeChange = true;
462 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000464 return MadeChange;
465}
466
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000468/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000469/// a clear win except on targets with multiple condition code registers
470/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000471///
472/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000473static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000474 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Dale Johannesence0b2372007-06-12 16:50:17 +0000476 /// InsertedCmp - Only insert a cmp in each block once.
477 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Dale Johannesence0b2372007-06-12 16:50:17 +0000479 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000481 UI != E; ) {
482 Use &TheUse = UI.getUse();
483 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Dale Johannesence0b2372007-06-12 16:50:17 +0000485 // Preincrement use iterator so we don't invalidate it.
486 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Dale Johannesence0b2372007-06-12 16:50:17 +0000488 // Don't bother for PHI nodes.
489 if (isa<PHINode>(User))
490 continue;
491
492 // Figure out which BB this cmp is used in.
493 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Dale Johannesence0b2372007-06-12 16:50:17 +0000495 // If this user is in the same block as the cmp, don't change the cmp.
496 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Dale Johannesence0b2372007-06-12 16:50:17 +0000498 // If we have already inserted a cmp into this block, use it.
499 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
500
501 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000502 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000504 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000505 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 CI->getOperand(1), "", InsertPt);
507 MadeChange = true;
508 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 // Replace a use of the cmp with a use of the new cmp.
511 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000512 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000513 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 // If we removed all uses, nuke the cmp.
516 if (CI->use_empty())
517 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 return MadeChange;
520}
521
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000522namespace {
523class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
524protected:
525 void replaceCall(Value *With) {
526 CI->replaceAllUsesWith(With);
527 CI->eraseFromParent();
528 }
529 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000530 if (ConstantInt *SizeCI =
531 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
532 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000533 return false;
534 }
535};
536} // end anonymous namespace
537
Eric Christopher040056f2010-03-11 02:41:03 +0000538bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000539 BasicBlock *BB = CI->getParent();
540
541 // Lower inline assembly if we can.
542 // If we found an inline asm expession, and if the target knows how to
543 // lower it to normal LLVM code, do so now.
544 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
545 if (TLI->ExpandInlineAsm(CI)) {
546 // Avoid invalidating the iterator.
547 CurInstIterator = BB->begin();
548 // Avoid processing instructions out of order, which could cause
549 // reuse before a value is defined.
550 SunkAddrs.clear();
551 return true;
552 }
553 // Sink address computing for memory operands into the block.
554 if (OptimizeInlineAsmInst(CI))
555 return true;
556 }
557
Eric Christopher040056f2010-03-11 02:41:03 +0000558 // Lower all uses of llvm.objectsize.*
559 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
560 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000561 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000562 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000563 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000564
565 // Substituting this can cause recursive simplifications, which can
566 // invalidate our iterator. Use a WeakVH to hold onto it in case this
567 // happens.
568 WeakVH IterHandle(CurInstIterator);
569
Cameron Zwarich680c9622011-03-24 04:52:04 +0000570 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
Chad Rosier618c1db2011-12-01 03:08:23 +0000571 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000572
573 // If the iterator instruction was recursively deleted, start over at the
574 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000575 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000576 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000577 SunkAddrs.clear();
578 }
Eric Christopher040056f2010-03-11 02:41:03 +0000579 return true;
580 }
581
Pete Cooperf210b682012-03-13 20:59:56 +0000582 if (II && TLI) {
583 SmallVector<Value*, 2> PtrOps;
584 Type *AccessTy;
585 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
586 while (!PtrOps.empty())
587 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
588 return true;
589 }
590
Eric Christopher040056f2010-03-11 02:41:03 +0000591 // From here on out we're working with named functions.
592 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000593
Eric Christopher040056f2010-03-11 02:41:03 +0000594 // We'll need TargetData from here on out.
595 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
596 if (!TD) return false;
597
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000598 // Lower all default uses of _chk calls. This is very similar
599 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000600 // that have the default "don't know" as the objectsize. Anything else
601 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000602 CodeGenPrepareFortifiedLibCalls Simplifier;
603 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000604}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000605
Evan Cheng485fafc2011-03-21 01:19:09 +0000606/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
607/// instructions to the predecessor to enable tail call optimizations. The
608/// case it is currently looking for is:
609/// bb0:
610/// %tmp0 = tail call i32 @f0()
611/// br label %return
612/// bb1:
613/// %tmp1 = tail call i32 @f1()
614/// br label %return
615/// bb2:
616/// %tmp2 = tail call i32 @f2()
617/// br label %return
618/// return:
619/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
620/// ret i32 %retval
621///
622/// =>
623///
624/// bb0:
625/// %tmp0 = tail call i32 @f0()
626/// ret i32 %tmp0
627/// bb1:
628/// %tmp1 = tail call i32 @f1()
629/// ret i32 %tmp1
630/// bb2:
631/// %tmp2 = tail call i32 @f2()
632/// ret i32 %tmp2
633///
634bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000635 if (!TLI)
636 return false;
637
Evan Cheng485fafc2011-03-21 01:19:09 +0000638 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000639 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
640 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000641 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000642
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000643 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000644 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000645 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000646
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000647 // It's not safe to eliminate the sign / zero extension of the return value.
648 // See llvm::isInTailCallPosition().
649 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000650 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000651 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
652 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000653
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000654 // Make sure there are no instructions between the PHI and return, or that the
655 // return is the first instruction in the block.
656 if (PN) {
657 BasicBlock::iterator BI = BB->begin();
658 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
659 if (&*BI != RI)
660 return false;
661 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000662 BasicBlock::iterator BI = BB->begin();
663 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
664 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000665 return false;
666 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000667
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000668 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
669 /// call.
670 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000671 if (PN) {
672 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
673 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
674 // Make sure the phi value is indeed produced by the tail call.
675 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
676 TLI->mayBeEmittedAsTailCall(CI))
677 TailCalls.push_back(CI);
678 }
679 } else {
680 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
681 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
682 if (!VisitedBBs.insert(*PI))
683 continue;
684
685 BasicBlock::InstListType &InstList = (*PI)->getInstList();
686 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
687 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000688 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
689 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000690 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000691
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000692 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000693 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000694 TailCalls.push_back(CI);
695 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000696 }
697
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000698 bool Changed = false;
699 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
700 CallInst *CI = TailCalls[i];
701 CallSite CS(CI);
702
703 // Conservatively require the attributes of the call to match those of the
704 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000705 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000706 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
707 continue;
708
709 // Make sure the call instruction is followed by an unconditional branch to
710 // the return block.
711 BasicBlock *CallBB = CI->getParent();
712 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
713 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
714 continue;
715
716 // Duplicate the return into CallBB.
717 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000718 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000719 ++NumRetsDup;
720 }
721
722 // If we eliminated all predecessors of the block, delete the block now.
723 if (Changed && pred_begin(BB) == pred_end(BB))
724 BB->eraseFromParent();
725
726 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000727}
728
Chris Lattner88a5c832008-11-25 07:09:13 +0000729//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000730// Memory Optimization
731//===----------------------------------------------------------------------===//
732
Chris Lattnerdd77df32007-04-13 20:30:56 +0000733/// IsNonLocalValue - Return true if the specified values are defined in a
734/// different basic block than BB.
735static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
736 if (Instruction *I = dyn_cast<Instruction>(V))
737 return I->getParent() != BB;
738 return false;
739}
740
Bob Wilson4a8ee232009-12-03 21:47:07 +0000741/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000742/// addressing modes that can do significant amounts of computation. As such,
743/// instruction selection will try to get the load or store to do as much
744/// computation as possible for the program. The problem is that isel can only
745/// see within a single block. As such, we sink as much legal addressing mode
746/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000747///
748/// This method is used to optimize both load/store and inline asms with memory
749/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000750bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000751 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000752 Value *Repl = Addr;
753
Owen Andersond2f41742010-11-19 22:15:03 +0000754 // Try to collapse single-value PHI nodes. This is necessary to undo
755 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000756 SmallVector<Value*, 8> worklist;
757 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000758 worklist.push_back(Addr);
759
760 // Use a worklist to iteratively look through PHI nodes, and ensure that
761 // the addressing mode obtained from the non-PHI roots of the graph
762 // are equivalent.
763 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000764 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000765 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000766 SmallVector<Instruction*, 16> AddrModeInsts;
767 ExtAddrMode AddrMode;
768 while (!worklist.empty()) {
769 Value *V = worklist.back();
770 worklist.pop_back();
771
772 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000773 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000774 Consensus = 0;
775 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000776 }
777
Owen Anderson35bf4d62010-11-27 08:15:55 +0000778 // For a PHI node, push all of its incoming values.
779 if (PHINode *P = dyn_cast<PHINode>(V)) {
780 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
781 worklist.push_back(P->getIncomingValue(i));
782 continue;
783 }
784
785 // For non-PHIs, determine the addressing mode being computed.
786 SmallVector<Instruction*, 16> NewAddrModeInsts;
787 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000788 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000789 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000790
791 // This check is broken into two cases with very similar code to avoid using
792 // getNumUses() as much as possible. Some values have a lot of uses, so
793 // calling getNumUses() unconditionally caused a significant compile-time
794 // regression.
795 if (!Consensus) {
796 Consensus = V;
797 AddrMode = NewAddrMode;
798 AddrModeInsts = NewAddrModeInsts;
799 continue;
800 } else if (NewAddrMode == AddrMode) {
801 if (!IsNumUsesConsensusValid) {
802 NumUsesConsensus = Consensus->getNumUses();
803 IsNumUsesConsensusValid = true;
804 }
805
806 // Ensure that the obtained addressing mode is equivalent to that obtained
807 // for all other roots of the PHI traversal. Also, when choosing one
808 // such root as representative, select the one with the most uses in order
809 // to keep the cost modeling heuristics in AddressingModeMatcher
810 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000811 unsigned NumUses = V->getNumUses();
812 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000813 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000814 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000815 AddrModeInsts = NewAddrModeInsts;
816 }
817 continue;
818 }
819
820 Consensus = 0;
821 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000822 }
823
Owen Anderson35bf4d62010-11-27 08:15:55 +0000824 // If the addressing mode couldn't be determined, or if multiple different
825 // ones were determined, bail out now.
826 if (!Consensus) return false;
827
Chris Lattnerdd77df32007-04-13 20:30:56 +0000828 // Check to see if any of the instructions supersumed by this addr mode are
829 // non-local to I's BB.
830 bool AnyNonLocal = false;
831 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000832 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000833 AnyNonLocal = true;
834 break;
835 }
836 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000837
Chris Lattnerdd77df32007-04-13 20:30:56 +0000838 // If all the instructions matched are already in this BB, don't do anything.
839 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000840 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000841 return false;
842 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000843
Chris Lattnerdd77df32007-04-13 20:30:56 +0000844 // Insert this computation right after this user. Since our caller is
845 // scanning from the top of the BB to the bottom, reuse of the expr are
846 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000847 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000848
Chris Lattnerdd77df32007-04-13 20:30:56 +0000849 // Now that we determined the addressing expression we want to use and know
850 // that we have to sink it into this block. Check to see if we have already
851 // done this for some other load/store instr in this block. If so, reuse the
852 // computation.
853 Value *&SunkAddr = SunkAddrs[Addr];
854 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000855 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000856 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000857 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000858 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000859 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000860 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000861 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000862 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000863 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000864
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000866
867 // Start with the base register. Do this first so that subsequent address
868 // matching finds it last, which will prevent it from trying to match it
869 // as the scaled value in case it happens to be a mul. That would be
870 // problematic if we've sunk a different mul for the scale, because then
871 // we'd end up sinking both muls.
872 if (AddrMode.BaseReg) {
873 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000874 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000875 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000876 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000877 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000878 Result = V;
879 }
880
881 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 if (AddrMode.Scale) {
883 Value *V = AddrMode.ScaledReg;
884 if (V->getType() == IntPtrTy) {
885 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000886 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000887 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000888 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
889 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000890 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000891 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000892 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000893 }
894 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000895 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
896 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000897 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000898 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000899 else
900 Result = V;
901 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000902
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 // Add in the BaseGV if present.
904 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000905 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000906 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000907 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000908 else
909 Result = V;
910 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Chris Lattnerdd77df32007-04-13 20:30:56 +0000912 // Add in the Base Offset if present.
913 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000914 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000915 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000916 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 else
918 Result = V;
919 }
920
921 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000922 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 else
Devang Patel2048c372011-09-06 18:49:53 +0000924 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000926
Owen Andersond2f41742010-11-19 22:15:03 +0000927 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000928
Chris Lattner0403b472011-04-09 07:05:44 +0000929 // If we have no uses, recursively delete the value and all dead instructions
930 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000931 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000932 // This can cause recursive deletion, which can invalidate our iterator.
933 // Use a WeakVH to hold onto it in case this happens.
934 WeakVH IterHandle(CurInstIterator);
935 BasicBlock *BB = CurInstIterator->getParent();
936
Owen Andersond2f41742010-11-19 22:15:03 +0000937 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000938
939 if (IterHandle != CurInstIterator) {
940 // If the iterator instruction was recursively deleted, start over at the
941 // start of the block.
942 CurInstIterator = BB->begin();
943 SunkAddrs.clear();
944 } else {
945 // This address is now available for reassignment, so erase the table
946 // entry; we don't want to match some completely different instruction.
947 SunkAddrs[Addr] = 0;
948 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000949 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000950 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000951 return true;
952}
953
Evan Cheng9bf12b52008-02-26 02:42:37 +0000954/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000955/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000956/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000957bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000958 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000959
Chris Lattner75796092011-01-15 07:14:54 +0000960 TargetLowering::AsmOperandInfoVector
961 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000962 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000963 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
964 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
965
Evan Cheng9bf12b52008-02-26 02:42:37 +0000966 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000967 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000968
Eli Friedman9ec80952008-02-26 18:37:49 +0000969 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
970 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000971 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000972 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000973 } else if (OpInfo.Type == InlineAsm::isInput)
974 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000975 }
976
977 return MadeChange;
978}
979
Dan Gohmanb00f2362009-10-16 20:59:35 +0000980/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
981/// basic block as the load, unless conditions are unfavorable. This allows
982/// SelectionDAG to fold the extend into the load.
983///
984bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
985 // Look for a load being extended.
986 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
987 if (!LI) return false;
988
989 // If they're already in the same block, there's nothing to do.
990 if (LI->getParent() == I->getParent())
991 return false;
992
993 // If the load has other users and the truncate is not free, this probably
994 // isn't worthwhile.
995 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000996 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
997 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000998 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000999 return false;
1000
1001 // Check whether the target supports casts folded into loads.
1002 unsigned LType;
1003 if (isa<ZExtInst>(I))
1004 LType = ISD::ZEXTLOAD;
1005 else {
1006 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1007 LType = ISD::SEXTLOAD;
1008 }
1009 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1010 return false;
1011
1012 // Move the extend into the same block as the load, so that SelectionDAG
1013 // can fold it.
1014 I->removeFromParent();
1015 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001016 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001017 return true;
1018}
1019
Evan Chengbdcb7262007-12-05 23:58:20 +00001020bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1021 BasicBlock *DefBB = I->getParent();
1022
Bob Wilson9120f5c2010-09-21 21:44:14 +00001023 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001024 // other uses of the source with result of extension.
1025 Value *Src = I->getOperand(0);
1026 if (Src->hasOneUse())
1027 return false;
1028
Evan Cheng696e5c02007-12-13 07:50:36 +00001029 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001030 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001031 return false;
1032
Evan Cheng772de512007-12-12 00:51:06 +00001033 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001034 // this block.
1035 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001036 return false;
1037
Evan Chengbdcb7262007-12-05 23:58:20 +00001038 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001039 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001040 UI != E; ++UI) {
1041 Instruction *User = cast<Instruction>(*UI);
1042
1043 // Figure out which BB this ext is used in.
1044 BasicBlock *UserBB = User->getParent();
1045 if (UserBB == DefBB) continue;
1046 DefIsLiveOut = true;
1047 break;
1048 }
1049 if (!DefIsLiveOut)
1050 return false;
1051
Evan Cheng765dff22007-12-12 02:53:41 +00001052 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001053 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001054 UI != E; ++UI) {
1055 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001056 BasicBlock *UserBB = User->getParent();
1057 if (UserBB == DefBB) continue;
1058 // Be conservative. We don't want this xform to end up introducing
1059 // reloads just before load / store instructions.
1060 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001061 return false;
1062 }
1063
Evan Chengbdcb7262007-12-05 23:58:20 +00001064 // InsertedTruncs - Only insert one trunc in each block once.
1065 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1066
1067 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001068 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001069 UI != E; ++UI) {
1070 Use &TheUse = UI.getUse();
1071 Instruction *User = cast<Instruction>(*UI);
1072
1073 // Figure out which BB this ext is used in.
1074 BasicBlock *UserBB = User->getParent();
1075 if (UserBB == DefBB) continue;
1076
1077 // Both src and def are live in this block. Rewrite the use.
1078 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1079
1080 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001081 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001082 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1083 }
1084
1085 // Replace a use of the {s|z}ext source with a use of the result.
1086 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001087 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001088 MadeChange = true;
1089 }
1090
1091 return MadeChange;
1092}
1093
Cameron Zwarichc0611012011-01-06 02:37:26 +00001094bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001095 if (PHINode *P = dyn_cast<PHINode>(I)) {
1096 // It is possible for very late stage optimizations (such as SimplifyCFG)
1097 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1098 // trivial PHI, go ahead and zap it here.
1099 if (Value *V = SimplifyInstruction(P)) {
1100 P->replaceAllUsesWith(V);
1101 P->eraseFromParent();
1102 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001103 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001104 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001105 return false;
1106 }
1107
1108 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001109 // If the source of the cast is a constant, then this should have
1110 // already been constant folded. The only reason NOT to constant fold
1111 // it is if something (e.g. LSR) was careful to place the constant
1112 // evaluation in a block other than then one that uses it (e.g. to hoist
1113 // the address of globals out of a loop). If this is the case, we don't
1114 // want to forward-subst the cast.
1115 if (isa<Constant>(CI->getOperand(0)))
1116 return false;
1117
Chris Lattner1a8943a2011-01-15 07:29:01 +00001118 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1119 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001120
Chris Lattner1a8943a2011-01-15 07:29:01 +00001121 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1122 bool MadeChange = MoveExtToFormExtLoad(I);
1123 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001124 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001125 return false;
1126 }
1127
1128 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1129 return OptimizeCmpExpression(CI);
1130
1131 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001132 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001133 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1134 return false;
1135 }
1136
1137 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001138 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001139 return OptimizeMemoryInst(I, SI->getOperand(1),
1140 SI->getOperand(0)->getType());
1141 return false;
1142 }
1143
1144 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001145 if (GEPI->hasAllZeroIndices()) {
1146 /// The GEP operand must be a pointer, so must its result -> BitCast
1147 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1148 GEPI->getName(), GEPI);
1149 GEPI->replaceAllUsesWith(NC);
1150 GEPI->eraseFromParent();
1151 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001152 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001153 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001154 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001155 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001156 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001157
1158 if (CallInst *CI = dyn_cast<CallInst>(I))
1159 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001160
Evan Cheng485fafc2011-03-21 01:19:09 +00001161 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1162 return DupRetToEnableTailCallOpts(RI);
1163
Chris Lattner1a8943a2011-01-15 07:29:01 +00001164 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001165}
1166
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001167// In this pass we look for GEP and cast instructions that are used
1168// across basic blocks and rewrite them to improve basic-block-at-a-time
1169// selection.
1170bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001171 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001172 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001173
Chris Lattner75796092011-01-15 07:14:54 +00001174 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001175 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1176 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001177
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001178 return MadeChange;
1179}
Devang Patelf56ea612011-08-18 00:50:51 +00001180
1181// llvm.dbg.value is far away from the value then iSel may not be able
1182// handle it properly. iSel will drop llvm.dbg.value if it can not
1183// find a node corresponding to the value.
1184bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1185 bool MadeChange = false;
1186 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1187 Instruction *PrevNonDbgInst = NULL;
1188 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1189 Instruction *Insn = BI; ++BI;
1190 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1191 if (!DVI) {
1192 PrevNonDbgInst = Insn;
1193 continue;
1194 }
1195
1196 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1197 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1198 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1199 DVI->removeFromParent();
1200 if (isa<PHINode>(VI))
1201 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1202 else
1203 DVI->insertAfter(VI);
1204 MadeChange = true;
1205 ++NumDbgValueMoved;
1206 }
1207 }
1208 }
1209 return MadeChange;
1210}