blob: aad3a924f14a4d969100e8958b4eb7bda7edaed2 [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
582 // From here on out we're working with named functions.
583 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000584
Eric Christopher040056f2010-03-11 02:41:03 +0000585 // We'll need TargetData from here on out.
586 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
587 if (!TD) return false;
588
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000589 // Lower all default uses of _chk calls. This is very similar
590 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000591 // that have the default "don't know" as the objectsize. Anything else
592 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000593 CodeGenPrepareFortifiedLibCalls Simplifier;
594 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000595}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000596
Evan Cheng485fafc2011-03-21 01:19:09 +0000597/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
598/// instructions to the predecessor to enable tail call optimizations. The
599/// case it is currently looking for is:
600/// bb0:
601/// %tmp0 = tail call i32 @f0()
602/// br label %return
603/// bb1:
604/// %tmp1 = tail call i32 @f1()
605/// br label %return
606/// bb2:
607/// %tmp2 = tail call i32 @f2()
608/// br label %return
609/// return:
610/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
611/// ret i32 %retval
612///
613/// =>
614///
615/// bb0:
616/// %tmp0 = tail call i32 @f0()
617/// ret i32 %tmp0
618/// bb1:
619/// %tmp1 = tail call i32 @f1()
620/// ret i32 %tmp1
621/// bb2:
622/// %tmp2 = tail call i32 @f2()
623/// ret i32 %tmp2
624///
625bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000626 if (!TLI)
627 return false;
628
Evan Cheng485fafc2011-03-21 01:19:09 +0000629 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000630 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
631 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000632 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000633
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000634 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000635 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000636 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000637
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000638 // It's not safe to eliminate the sign / zero extension of the return value.
639 // See llvm::isInTailCallPosition().
640 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000641 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000642 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
643 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000644
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000645 // Make sure there are no instructions between the PHI and return, or that the
646 // return is the first instruction in the block.
647 if (PN) {
648 BasicBlock::iterator BI = BB->begin();
649 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
650 if (&*BI != RI)
651 return false;
652 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000653 BasicBlock::iterator BI = BB->begin();
654 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
655 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000656 return false;
657 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000658
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000659 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
660 /// call.
661 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000662 if (PN) {
663 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
664 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
665 // Make sure the phi value is indeed produced by the tail call.
666 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
667 TLI->mayBeEmittedAsTailCall(CI))
668 TailCalls.push_back(CI);
669 }
670 } else {
671 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
672 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
673 if (!VisitedBBs.insert(*PI))
674 continue;
675
676 BasicBlock::InstListType &InstList = (*PI)->getInstList();
677 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
678 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000679 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
680 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000681 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000682
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000683 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000684 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000685 TailCalls.push_back(CI);
686 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000687 }
688
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000689 bool Changed = false;
690 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
691 CallInst *CI = TailCalls[i];
692 CallSite CS(CI);
693
694 // Conservatively require the attributes of the call to match those of the
695 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000696 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000697 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
698 continue;
699
700 // Make sure the call instruction is followed by an unconditional branch to
701 // the return block.
702 BasicBlock *CallBB = CI->getParent();
703 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
704 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
705 continue;
706
707 // Duplicate the return into CallBB.
708 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000709 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000710 ++NumRetsDup;
711 }
712
713 // If we eliminated all predecessors of the block, delete the block now.
714 if (Changed && pred_begin(BB) == pred_end(BB))
715 BB->eraseFromParent();
716
717 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000718}
719
Chris Lattner88a5c832008-11-25 07:09:13 +0000720//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000721// Memory Optimization
722//===----------------------------------------------------------------------===//
723
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724/// IsNonLocalValue - Return true if the specified values are defined in a
725/// different basic block than BB.
726static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
727 if (Instruction *I = dyn_cast<Instruction>(V))
728 return I->getParent() != BB;
729 return false;
730}
731
Bob Wilson4a8ee232009-12-03 21:47:07 +0000732/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000733/// addressing modes that can do significant amounts of computation. As such,
734/// instruction selection will try to get the load or store to do as much
735/// computation as possible for the program. The problem is that isel can only
736/// see within a single block. As such, we sink as much legal addressing mode
737/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000738///
739/// This method is used to optimize both load/store and inline asms with memory
740/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000741bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000742 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000743 Value *Repl = Addr;
744
Owen Andersond2f41742010-11-19 22:15:03 +0000745 // Try to collapse single-value PHI nodes. This is necessary to undo
746 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000747 SmallVector<Value*, 8> worklist;
748 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000749 worklist.push_back(Addr);
750
751 // Use a worklist to iteratively look through PHI nodes, and ensure that
752 // the addressing mode obtained from the non-PHI roots of the graph
753 // are equivalent.
754 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000755 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000756 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000757 SmallVector<Instruction*, 16> AddrModeInsts;
758 ExtAddrMode AddrMode;
759 while (!worklist.empty()) {
760 Value *V = worklist.back();
761 worklist.pop_back();
762
763 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000764 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000765 Consensus = 0;
766 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000767 }
768
Owen Anderson35bf4d62010-11-27 08:15:55 +0000769 // For a PHI node, push all of its incoming values.
770 if (PHINode *P = dyn_cast<PHINode>(V)) {
771 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
772 worklist.push_back(P->getIncomingValue(i));
773 continue;
774 }
775
776 // For non-PHIs, determine the addressing mode being computed.
777 SmallVector<Instruction*, 16> NewAddrModeInsts;
778 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000779 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000780 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000781
782 // This check is broken into two cases with very similar code to avoid using
783 // getNumUses() as much as possible. Some values have a lot of uses, so
784 // calling getNumUses() unconditionally caused a significant compile-time
785 // regression.
786 if (!Consensus) {
787 Consensus = V;
788 AddrMode = NewAddrMode;
789 AddrModeInsts = NewAddrModeInsts;
790 continue;
791 } else if (NewAddrMode == AddrMode) {
792 if (!IsNumUsesConsensusValid) {
793 NumUsesConsensus = Consensus->getNumUses();
794 IsNumUsesConsensusValid = true;
795 }
796
797 // Ensure that the obtained addressing mode is equivalent to that obtained
798 // for all other roots of the PHI traversal. Also, when choosing one
799 // such root as representative, select the one with the most uses in order
800 // to keep the cost modeling heuristics in AddressingModeMatcher
801 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000802 unsigned NumUses = V->getNumUses();
803 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000804 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000805 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000806 AddrModeInsts = NewAddrModeInsts;
807 }
808 continue;
809 }
810
811 Consensus = 0;
812 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000813 }
814
Owen Anderson35bf4d62010-11-27 08:15:55 +0000815 // If the addressing mode couldn't be determined, or if multiple different
816 // ones were determined, bail out now.
817 if (!Consensus) return false;
818
Chris Lattnerdd77df32007-04-13 20:30:56 +0000819 // Check to see if any of the instructions supersumed by this addr mode are
820 // non-local to I's BB.
821 bool AnyNonLocal = false;
822 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000823 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000824 AnyNonLocal = true;
825 break;
826 }
827 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000828
Chris Lattnerdd77df32007-04-13 20:30:56 +0000829 // If all the instructions matched are already in this BB, don't do anything.
830 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000831 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000832 return false;
833 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000834
Chris Lattnerdd77df32007-04-13 20:30:56 +0000835 // Insert this computation right after this user. Since our caller is
836 // scanning from the top of the BB to the bottom, reuse of the expr are
837 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000838 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000839
Chris Lattnerdd77df32007-04-13 20:30:56 +0000840 // Now that we determined the addressing expression we want to use and know
841 // that we have to sink it into this block. Check to see if we have already
842 // done this for some other load/store instr in this block. If so, reuse the
843 // computation.
844 Value *&SunkAddr = SunkAddrs[Addr];
845 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000846 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000847 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000848 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000849 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000850 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000851 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000852 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000853 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000854 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000855
Chris Lattnerdd77df32007-04-13 20:30:56 +0000856 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000857
858 // Start with the base register. Do this first so that subsequent address
859 // matching finds it last, which will prevent it from trying to match it
860 // as the scaled value in case it happens to be a mul. That would be
861 // problematic if we've sunk a different mul for the scale, because then
862 // we'd end up sinking both muls.
863 if (AddrMode.BaseReg) {
864 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000865 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000866 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000867 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000868 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000869 Result = V;
870 }
871
872 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000873 if (AddrMode.Scale) {
874 Value *V = AddrMode.ScaledReg;
875 if (V->getType() == IntPtrTy) {
876 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000877 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000878 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000879 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
880 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000881 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000883 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000884 }
885 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000886 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
887 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000888 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000889 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000890 else
891 Result = V;
892 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000893
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 // Add in the BaseGV if present.
895 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000896 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "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 Base Offset if present.
904 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000905 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
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 }
911
912 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000913 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000914 else
Devang Patel2048c372011-09-06 18:49:53 +0000915 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000916 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000917
Owen Andersond2f41742010-11-19 22:15:03 +0000918 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000919
Chris Lattner0403b472011-04-09 07:05:44 +0000920 // If we have no uses, recursively delete the value and all dead instructions
921 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000922 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000923 // This can cause recursive deletion, which can invalidate our iterator.
924 // Use a WeakVH to hold onto it in case this happens.
925 WeakVH IterHandle(CurInstIterator);
926 BasicBlock *BB = CurInstIterator->getParent();
927
Owen Andersond2f41742010-11-19 22:15:03 +0000928 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000929
930 if (IterHandle != CurInstIterator) {
931 // If the iterator instruction was recursively deleted, start over at the
932 // start of the block.
933 CurInstIterator = BB->begin();
934 SunkAddrs.clear();
935 } else {
936 // This address is now available for reassignment, so erase the table
937 // entry; we don't want to match some completely different instruction.
938 SunkAddrs[Addr] = 0;
939 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000940 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000941 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000942 return true;
943}
944
Evan Cheng9bf12b52008-02-26 02:42:37 +0000945/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000946/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000947/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000948bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000949 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000950
Chris Lattner75796092011-01-15 07:14:54 +0000951 TargetLowering::AsmOperandInfoVector
952 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000953 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000954 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
955 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
956
Evan Cheng9bf12b52008-02-26 02:42:37 +0000957 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000958 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000959
Eli Friedman9ec80952008-02-26 18:37:49 +0000960 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
961 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000962 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000963 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000964 } else if (OpInfo.Type == InlineAsm::isInput)
965 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000966 }
967
968 return MadeChange;
969}
970
Dan Gohmanb00f2362009-10-16 20:59:35 +0000971/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
972/// basic block as the load, unless conditions are unfavorable. This allows
973/// SelectionDAG to fold the extend into the load.
974///
975bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
976 // Look for a load being extended.
977 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
978 if (!LI) return false;
979
980 // If they're already in the same block, there's nothing to do.
981 if (LI->getParent() == I->getParent())
982 return false;
983
984 // If the load has other users and the truncate is not free, this probably
985 // isn't worthwhile.
986 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000987 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
988 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000989 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000990 return false;
991
992 // Check whether the target supports casts folded into loads.
993 unsigned LType;
994 if (isa<ZExtInst>(I))
995 LType = ISD::ZEXTLOAD;
996 else {
997 assert(isa<SExtInst>(I) && "Unexpected ext type!");
998 LType = ISD::SEXTLOAD;
999 }
1000 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1001 return false;
1002
1003 // Move the extend into the same block as the load, so that SelectionDAG
1004 // can fold it.
1005 I->removeFromParent();
1006 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001007 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001008 return true;
1009}
1010
Evan Chengbdcb7262007-12-05 23:58:20 +00001011bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1012 BasicBlock *DefBB = I->getParent();
1013
Bob Wilson9120f5c2010-09-21 21:44:14 +00001014 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001015 // other uses of the source with result of extension.
1016 Value *Src = I->getOperand(0);
1017 if (Src->hasOneUse())
1018 return false;
1019
Evan Cheng696e5c02007-12-13 07:50:36 +00001020 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001021 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001022 return false;
1023
Evan Cheng772de512007-12-12 00:51:06 +00001024 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001025 // this block.
1026 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001027 return false;
1028
Evan Chengbdcb7262007-12-05 23:58:20 +00001029 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001030 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001031 UI != E; ++UI) {
1032 Instruction *User = cast<Instruction>(*UI);
1033
1034 // Figure out which BB this ext is used in.
1035 BasicBlock *UserBB = User->getParent();
1036 if (UserBB == DefBB) continue;
1037 DefIsLiveOut = true;
1038 break;
1039 }
1040 if (!DefIsLiveOut)
1041 return false;
1042
Evan Cheng765dff22007-12-12 02:53:41 +00001043 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001044 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001045 UI != E; ++UI) {
1046 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001047 BasicBlock *UserBB = User->getParent();
1048 if (UserBB == DefBB) continue;
1049 // Be conservative. We don't want this xform to end up introducing
1050 // reloads just before load / store instructions.
1051 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001052 return false;
1053 }
1054
Evan Chengbdcb7262007-12-05 23:58:20 +00001055 // InsertedTruncs - Only insert one trunc in each block once.
1056 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1057
1058 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001059 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001060 UI != E; ++UI) {
1061 Use &TheUse = UI.getUse();
1062 Instruction *User = cast<Instruction>(*UI);
1063
1064 // Figure out which BB this ext is used in.
1065 BasicBlock *UserBB = User->getParent();
1066 if (UserBB == DefBB) continue;
1067
1068 // Both src and def are live in this block. Rewrite the use.
1069 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1070
1071 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001072 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001073 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1074 }
1075
1076 // Replace a use of the {s|z}ext source with a use of the result.
1077 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001078 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001079 MadeChange = true;
1080 }
1081
1082 return MadeChange;
1083}
1084
Cameron Zwarichc0611012011-01-06 02:37:26 +00001085bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001086 if (PHINode *P = dyn_cast<PHINode>(I)) {
1087 // It is possible for very late stage optimizations (such as SimplifyCFG)
1088 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1089 // trivial PHI, go ahead and zap it here.
1090 if (Value *V = SimplifyInstruction(P)) {
1091 P->replaceAllUsesWith(V);
1092 P->eraseFromParent();
1093 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001094 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001095 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001096 return false;
1097 }
1098
1099 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001100 // If the source of the cast is a constant, then this should have
1101 // already been constant folded. The only reason NOT to constant fold
1102 // it is if something (e.g. LSR) was careful to place the constant
1103 // evaluation in a block other than then one that uses it (e.g. to hoist
1104 // the address of globals out of a loop). If this is the case, we don't
1105 // want to forward-subst the cast.
1106 if (isa<Constant>(CI->getOperand(0)))
1107 return false;
1108
Chris Lattner1a8943a2011-01-15 07:29:01 +00001109 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1110 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001111
Chris Lattner1a8943a2011-01-15 07:29:01 +00001112 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1113 bool MadeChange = MoveExtToFormExtLoad(I);
1114 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001115 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001116 return false;
1117 }
1118
1119 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1120 return OptimizeCmpExpression(CI);
1121
1122 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001123 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001124 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1125 return false;
1126 }
1127
1128 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001129 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001130 return OptimizeMemoryInst(I, SI->getOperand(1),
1131 SI->getOperand(0)->getType());
1132 return false;
1133 }
1134
1135 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001136 if (GEPI->hasAllZeroIndices()) {
1137 /// The GEP operand must be a pointer, so must its result -> BitCast
1138 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1139 GEPI->getName(), GEPI);
1140 GEPI->replaceAllUsesWith(NC);
1141 GEPI->eraseFromParent();
1142 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001143 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001144 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001145 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001146 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001147 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001148
1149 if (CallInst *CI = dyn_cast<CallInst>(I))
1150 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001151
Evan Cheng485fafc2011-03-21 01:19:09 +00001152 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1153 return DupRetToEnableTailCallOpts(RI);
1154
Chris Lattner1a8943a2011-01-15 07:29:01 +00001155 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001156}
1157
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001158// In this pass we look for GEP and cast instructions that are used
1159// across basic blocks and rewrite them to improve basic-block-at-a-time
1160// selection.
1161bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001162 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001163 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001164
Chris Lattner75796092011-01-15 07:14:54 +00001165 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001166 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1167 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001168
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001169 return MadeChange;
1170}
Devang Patelf56ea612011-08-18 00:50:51 +00001171
1172// llvm.dbg.value is far away from the value then iSel may not be able
1173// handle it properly. iSel will drop llvm.dbg.value if it can not
1174// find a node corresponding to the value.
1175bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1176 bool MadeChange = false;
1177 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1178 Instruction *PrevNonDbgInst = NULL;
1179 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1180 Instruction *Insn = BI; ++BI;
1181 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1182 if (!DVI) {
1183 PrevNonDbgInst = Insn;
1184 continue;
1185 }
1186
1187 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1188 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1189 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1190 DVI->removeFromParent();
1191 if (isa<PHINode>(VI))
1192 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1193 else
1194 DVI->insertAfter(VI);
1195 MadeChange = true;
1196 ++NumDbgValueMoved;
1197 }
1198 }
1199 }
1200 return MadeChange;
1201}