blob: 24d64b50c2a50ca55aecb7f61946394eeb62baa7 [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");
Benjamin Kramer59957502012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000064
Cameron Zwarich899eaa32011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Bill Wendlinge3e394d2012-03-04 10:46:01 +000069// FIXME: Remove this abomination once all of the tests pass without it!
70static cl::opt<bool> DisableDeleteDeadBlocks(
71 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
73
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000074static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000077
Eric Christopher692bf6b2008-09-24 05:32:41 +000078namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000079 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 /// TLI - Keep a pointer of a TargetLowering to consult for determining
81 /// transformation profitability.
82 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000083 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000084 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000085 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000086
87 /// CurInstIterator - As we scan instructions optimizing them, this is the
88 /// next instruction to optimize. Xforms that can invalidate this should
89 /// update it.
90 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000091
Evan Cheng485fafc2011-03-21 01:19:09 +000092 /// Keeps track of non-local addresses that have been sunk into a block.
93 /// This allows us to avoid inserting duplicate code for blocks with
94 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000095 DenseMap<Value*, Value*> SunkAddrs;
96
Devang Patel52e37df2011-03-24 15:35:25 +000097 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000098 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000099 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +0000100
Benjamin Kramer59957502012-05-05 12:49:22 +0000101 /// OptSize - True if optimizing for size.
102 bool OptSize;
103
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000105 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000106 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000107 : FunctionPass(ID), TLI(tli) {
108 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
109 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000111
Andreas Neustifterad809812009-09-16 09:26:52 +0000112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000113 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000114 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000115 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000116 }
117
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000122 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000123 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000125 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000126 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000127 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000128 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000129 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000130 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000131 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132 };
133}
Devang Patel794fd752007-05-01 21:15:47 +0000134
Devang Patel19974732007-05-03 01:11:54 +0000135char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000136INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000140 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000141
142FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
144}
145
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Devang Patel52e37df2011-03-24 15:35:25 +0000149 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000150 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000151 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000152 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000153 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000154
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000155 // First pass, eliminate blocks that contain only PHI nodes and an
156 // unconditional branch.
157 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000158
Devang Patelf56ea612011-08-18 00:50:51 +0000159 // llvm.dbg.value is far away from the value then iSel may not be able
160 // handle it properly. iSel will drop llvm.dbg.value if it can not
161 // find a node corresponding to the value.
162 EverMadeChange |= PlaceDbgValues(F);
163
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000165 while (MadeChange) {
166 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000167 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
168 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000169 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000170 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000171 EverMadeChange |= MadeChange;
172 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000173
174 SunkAddrs.clear();
175
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000176 if (!DisableBranchOpts) {
177 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000178 SmallPtrSet<BasicBlock*, 8> WorkList;
179 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
180 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000181 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000182 if (!MadeChange) continue;
183
184 for (SmallVectorImpl<BasicBlock*>::iterator
185 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
186 if (pred_begin(*II) == pred_end(*II))
187 WorkList.insert(*II);
188 }
189
190 if (!DisableDeleteDeadBlocks)
191 for (SmallPtrSet<BasicBlock*, 8>::iterator
192 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
193 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000194
Evan Cheng485fafc2011-03-21 01:19:09 +0000195 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000196 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000197 EverMadeChange |= MadeChange;
198 }
199
Devang Patel52e37df2011-03-24 15:35:25 +0000200 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000201 DT->DT->recalculate(F);
202
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000203 return EverMadeChange;
204}
205
Dale Johannesen2d697242009-03-27 01:13:37 +0000206/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
207/// debug info directives, and an unconditional branch. Passes before isel
208/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
209/// isel. Start by eliminating these blocks so we can split them the way we
210/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000211bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
212 bool MadeChange = false;
213 // Note that this intentionally skips the entry block.
214 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
215 BasicBlock *BB = I++;
216
217 // If this block doesn't end with an uncond branch, ignore it.
218 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
219 if (!BI || !BI->isUnconditional())
220 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Dale Johannesen2d697242009-03-27 01:13:37 +0000222 // If the instruction before the branch (skipping debug info) isn't a phi
223 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000224 BasicBlock::iterator BBI = BI;
225 if (BBI != BB->begin()) {
226 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000227 while (isa<DbgInfoIntrinsic>(BBI)) {
228 if (BBI == BB->begin())
229 break;
230 --BBI;
231 }
232 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
233 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000235
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000236 // Do not break infinite loops.
237 BasicBlock *DestBB = BI->getSuccessor(0);
238 if (DestBB == BB)
239 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000240
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 if (!CanMergeBlocks(BB, DestBB))
242 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000243
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000244 EliminateMostlyEmptyBlock(BB);
245 MadeChange = true;
246 }
247 return MadeChange;
248}
249
250/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
251/// single uncond branch between them, and BB contains no other non-phi
252/// instructions.
253bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
254 const BasicBlock *DestBB) const {
255 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
256 // the successor. If there are more complex condition (e.g. preheaders),
257 // don't mess around with them.
258 BasicBlock::const_iterator BBI = BB->begin();
259 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000260 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 UI != E; ++UI) {
262 const Instruction *User = cast<Instruction>(*UI);
263 if (User->getParent() != DestBB || !isa<PHINode>(User))
264 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000265 // If User is inside DestBB block and it is a PHINode then check
266 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000267 // a complex condition (e.g. preheaders) we want to avoid here.
268 if (User->getParent() == DestBB) {
269 if (const PHINode *UPN = dyn_cast<PHINode>(User))
270 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
271 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
272 if (Insn && Insn->getParent() == BB &&
273 Insn->getParent() != UPN->getIncomingBlock(I))
274 return false;
275 }
276 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000277 }
278 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
281 // and DestBB may have conflicting incoming values for the block. If so, we
282 // can't merge the block.
283 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
284 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000287 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
289 // It is faster to get preds from a PHI than with pred_iterator.
290 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
291 BBPreds.insert(BBPN->getIncomingBlock(i));
292 } else {
293 BBPreds.insert(pred_begin(BB), pred_end(BB));
294 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000295
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000296 // Walk the preds of DestBB.
297 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
298 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
299 if (BBPreds.count(Pred)) { // Common predecessor?
300 BBI = DestBB->begin();
301 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
302 const Value *V1 = PN->getIncomingValueForBlock(Pred);
303 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000305 // If V2 is a phi node in BB, look up what the mapped value will be.
306 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
307 if (V2PN->getParent() == BB)
308 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000310 // If there is a conflict, bail out.
311 if (V1 != V2) return false;
312 }
313 }
314 }
315
316 return true;
317}
318
319
320/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
321/// an unconditional branch in it.
322void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
323 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
324 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000325
David Greene68d67fd2010-01-05 01:27:11 +0000326 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000327
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000328 // If the destination block has a single pred, then this is a trivial edge,
329 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000330 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000331 if (SinglePred != DestBB) {
332 // Remember if SinglePred was the entry block of the function. If so, we
333 // will need to move BB back to the entry position.
334 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000335 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000336
Chris Lattnerf5102a02008-11-28 19:54:49 +0000337 if (isEntry && BB != &BB->getParent()->getEntryBlock())
338 BB->moveBefore(&BB->getParent()->getEntryBlock());
339
David Greene68d67fd2010-01-05 01:27:11 +0000340 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000341 return;
342 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
346 // to handle the new incoming edges it is about to have.
347 PHINode *PN;
348 for (BasicBlock::iterator BBI = DestBB->begin();
349 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
350 // Remove the incoming value for BB, and remember it.
351 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000352
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000353 // Two options: either the InVal is a phi node defined in BB or it is some
354 // value that dominates BB.
355 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
356 if (InValPhi && InValPhi->getParent() == BB) {
357 // Add all of the input values of the input PHI as inputs of this phi.
358 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
359 PN->addIncoming(InValPhi->getIncomingValue(i),
360 InValPhi->getIncomingBlock(i));
361 } else {
362 // Otherwise, add one instance of the dominating value for each edge that
363 // we will be adding.
364 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
365 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
366 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
367 } else {
368 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
369 PN->addIncoming(InVal, *PI);
370 }
371 }
372 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000374 // The PHIs are now updated, change everything that refers to BB to use
375 // DestBB and remove BB.
376 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000377 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000378 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
379 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
380 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
381 DT->changeImmediateDominator(DestBB, NewIDom);
382 DT->eraseNode(BB);
383 }
Evan Cheng04149f72009-12-17 09:39:49 +0000384 if (PFI) {
385 PFI->replaceAllUses(BB, DestBB);
386 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000387 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000388 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000389 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000390
David Greene68d67fd2010-01-05 01:27:11 +0000391 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000392}
393
Chris Lattnerdd77df32007-04-13 20:30:56 +0000394/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000395/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
396/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000397/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000398///
399/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000400///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000401static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000403 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
404 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000405
Chris Lattnerdd77df32007-04-13 20:30:56 +0000406 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000407 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000408 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000409
Chris Lattnerdd77df32007-04-13 20:30:56 +0000410 // If this is an extension, it will be a zero or sign extension, which
411 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000412 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000413
Chris Lattnerdd77df32007-04-13 20:30:56 +0000414 // If these values will be promoted, find out what they will be promoted
415 // to. This helps us consider truncates on PPC as noop copies when they
416 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000417 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
418 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000419 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000420 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
421 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000422 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000423
Chris Lattnerdd77df32007-04-13 20:30:56 +0000424 // If, after promotion, these are the same types, this is a noop copy.
425 if (SrcVT != DstVT)
426 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000427
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000428 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000430 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000431 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000433 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000435 UI != E; ) {
436 Use &TheUse = UI.getUse();
437 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 // Figure out which BB this cast is used in. For PHI's this is the
440 // appropriate predecessor block.
441 BasicBlock *UserBB = User->getParent();
442 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000443 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000444 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000446 // Preincrement use iterator so we don't invalidate it.
447 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000449 // If this user is in the same block as the cast, don't change the cast.
450 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 // If we have already inserted a cast into this block, use it.
453 CastInst *&InsertedCast = InsertedCasts[UserBB];
454
455 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000456 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000457 InsertedCast =
458 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 InsertPt);
460 MadeChange = true;
461 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Dale Johannesence0b2372007-06-12 16:50:17 +0000463 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000464 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000465 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000467
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000469 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000471 MadeChange = true;
472 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 return MadeChange;
475}
476
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000478/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000479/// a clear win except on targets with multiple condition code registers
480/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000481///
482/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000483static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Dale Johannesence0b2372007-06-12 16:50:17 +0000486 /// InsertedCmp - Only insert a cmp in each block once.
487 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000491 UI != E; ) {
492 Use &TheUse = UI.getUse();
493 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Dale Johannesence0b2372007-06-12 16:50:17 +0000495 // Preincrement use iterator so we don't invalidate it.
496 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Dale Johannesence0b2372007-06-12 16:50:17 +0000498 // Don't bother for PHI nodes.
499 if (isa<PHINode>(User))
500 continue;
501
502 // Figure out which BB this cmp is used in.
503 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Dale Johannesence0b2372007-06-12 16:50:17 +0000505 // If this user is in the same block as the cmp, don't change the cmp.
506 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 // If we have already inserted a cmp into this block, use it.
509 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
510
511 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000512 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000514 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000515 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000516 CI->getOperand(1), "", InsertPt);
517 MadeChange = true;
518 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
Dale Johannesence0b2372007-06-12 16:50:17 +0000520 // Replace a use of the cmp with a use of the new cmp.
521 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000522 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 // If we removed all uses, nuke the cmp.
526 if (CI->use_empty())
527 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 return MadeChange;
530}
531
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000532namespace {
533class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
534protected:
535 void replaceCall(Value *With) {
536 CI->replaceAllUsesWith(With);
537 CI->eraseFromParent();
538 }
539 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000540 if (ConstantInt *SizeCI =
541 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
542 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000543 return false;
544 }
545};
546} // end anonymous namespace
547
Eric Christopher040056f2010-03-11 02:41:03 +0000548bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000549 BasicBlock *BB = CI->getParent();
550
551 // Lower inline assembly if we can.
552 // If we found an inline asm expession, and if the target knows how to
553 // lower it to normal LLVM code, do so now.
554 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
555 if (TLI->ExpandInlineAsm(CI)) {
556 // Avoid invalidating the iterator.
557 CurInstIterator = BB->begin();
558 // Avoid processing instructions out of order, which could cause
559 // reuse before a value is defined.
560 SunkAddrs.clear();
561 return true;
562 }
563 // Sink address computing for memory operands into the block.
564 if (OptimizeInlineAsmInst(CI))
565 return true;
566 }
567
Eric Christopher040056f2010-03-11 02:41:03 +0000568 // Lower all uses of llvm.objectsize.*
569 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
570 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000571 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000572 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000573 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000574
575 // Substituting this can cause recursive simplifications, which can
576 // invalidate our iterator. Use a WeakVH to hold onto it in case this
577 // happens.
578 WeakVH IterHandle(CurInstIterator);
579
Chandler Carruth6b980542012-03-24 21:11:24 +0000580 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
581 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000582
583 // If the iterator instruction was recursively deleted, start over at the
584 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000585 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000586 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000587 SunkAddrs.clear();
588 }
Eric Christopher040056f2010-03-11 02:41:03 +0000589 return true;
590 }
591
Pete Cooperf210b682012-03-13 20:59:56 +0000592 if (II && TLI) {
593 SmallVector<Value*, 2> PtrOps;
594 Type *AccessTy;
595 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
596 while (!PtrOps.empty())
597 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
598 return true;
599 }
600
Eric Christopher040056f2010-03-11 02:41:03 +0000601 // From here on out we're working with named functions.
602 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000603
Eric Christopher040056f2010-03-11 02:41:03 +0000604 // We'll need TargetData from here on out.
605 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
606 if (!TD) return false;
607
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000608 // Lower all default uses of _chk calls. This is very similar
609 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000610 // that have the default "don't know" as the objectsize. Anything else
611 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000612 CodeGenPrepareFortifiedLibCalls Simplifier;
613 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000614}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000615
Evan Cheng485fafc2011-03-21 01:19:09 +0000616/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
617/// instructions to the predecessor to enable tail call optimizations. The
618/// case it is currently looking for is:
619/// bb0:
620/// %tmp0 = tail call i32 @f0()
621/// br label %return
622/// bb1:
623/// %tmp1 = tail call i32 @f1()
624/// br label %return
625/// bb2:
626/// %tmp2 = tail call i32 @f2()
627/// br label %return
628/// return:
629/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
630/// ret i32 %retval
631///
632/// =>
633///
634/// bb0:
635/// %tmp0 = tail call i32 @f0()
636/// ret i32 %tmp0
637/// bb1:
638/// %tmp1 = tail call i32 @f1()
639/// ret i32 %tmp1
640/// bb2:
641/// %tmp2 = tail call i32 @f2()
642/// ret i32 %tmp2
643///
644bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000645 if (!TLI)
646 return false;
647
Evan Cheng485fafc2011-03-21 01:19:09 +0000648 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000649 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
650 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000651 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000652
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000653 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000654 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000655 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000656
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000657 // It's not safe to eliminate the sign / zero extension of the return value.
658 // See llvm::isInTailCallPosition().
659 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000660 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000661 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
662 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000663
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000664 // Make sure there are no instructions between the PHI and return, or that the
665 // return is the first instruction in the block.
666 if (PN) {
667 BasicBlock::iterator BI = BB->begin();
668 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
669 if (&*BI != RI)
670 return false;
671 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000672 BasicBlock::iterator BI = BB->begin();
673 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
674 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000675 return false;
676 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000677
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000678 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
679 /// call.
680 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000681 if (PN) {
682 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
683 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
684 // Make sure the phi value is indeed produced by the tail call.
685 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
686 TLI->mayBeEmittedAsTailCall(CI))
687 TailCalls.push_back(CI);
688 }
689 } else {
690 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
691 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
692 if (!VisitedBBs.insert(*PI))
693 continue;
694
695 BasicBlock::InstListType &InstList = (*PI)->getInstList();
696 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
697 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000698 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
699 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000700 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000701
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000702 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000703 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000704 TailCalls.push_back(CI);
705 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000706 }
707
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000708 bool Changed = false;
709 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
710 CallInst *CI = TailCalls[i];
711 CallSite CS(CI);
712
713 // Conservatively require the attributes of the call to match those of the
714 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000715 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000716 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
717 continue;
718
719 // Make sure the call instruction is followed by an unconditional branch to
720 // the return block.
721 BasicBlock *CallBB = CI->getParent();
722 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
723 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
724 continue;
725
726 // Duplicate the return into CallBB.
727 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000728 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000729 ++NumRetsDup;
730 }
731
732 // If we eliminated all predecessors of the block, delete the block now.
733 if (Changed && pred_begin(BB) == pred_end(BB))
734 BB->eraseFromParent();
735
736 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000737}
738
Chris Lattner88a5c832008-11-25 07:09:13 +0000739//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000740// Memory Optimization
741//===----------------------------------------------------------------------===//
742
Chris Lattnerdd77df32007-04-13 20:30:56 +0000743/// IsNonLocalValue - Return true if the specified values are defined in a
744/// different basic block than BB.
745static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
746 if (Instruction *I = dyn_cast<Instruction>(V))
747 return I->getParent() != BB;
748 return false;
749}
750
Bob Wilson4a8ee232009-12-03 21:47:07 +0000751/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000752/// addressing modes that can do significant amounts of computation. As such,
753/// instruction selection will try to get the load or store to do as much
754/// computation as possible for the program. The problem is that isel can only
755/// see within a single block. As such, we sink as much legal addressing mode
756/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000757///
758/// This method is used to optimize both load/store and inline asms with memory
759/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000760bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000761 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000762 Value *Repl = Addr;
763
Owen Andersond2f41742010-11-19 22:15:03 +0000764 // Try to collapse single-value PHI nodes. This is necessary to undo
765 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000766 SmallVector<Value*, 8> worklist;
767 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000768 worklist.push_back(Addr);
769
770 // Use a worklist to iteratively look through PHI nodes, and ensure that
771 // the addressing mode obtained from the non-PHI roots of the graph
772 // are equivalent.
773 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000774 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000775 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000776 SmallVector<Instruction*, 16> AddrModeInsts;
777 ExtAddrMode AddrMode;
778 while (!worklist.empty()) {
779 Value *V = worklist.back();
780 worklist.pop_back();
781
782 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000783 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000784 Consensus = 0;
785 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000786 }
787
Owen Anderson35bf4d62010-11-27 08:15:55 +0000788 // For a PHI node, push all of its incoming values.
789 if (PHINode *P = dyn_cast<PHINode>(V)) {
790 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
791 worklist.push_back(P->getIncomingValue(i));
792 continue;
793 }
794
795 // For non-PHIs, determine the addressing mode being computed.
796 SmallVector<Instruction*, 16> NewAddrModeInsts;
797 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000798 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000799 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000800
801 // This check is broken into two cases with very similar code to avoid using
802 // getNumUses() as much as possible. Some values have a lot of uses, so
803 // calling getNumUses() unconditionally caused a significant compile-time
804 // regression.
805 if (!Consensus) {
806 Consensus = V;
807 AddrMode = NewAddrMode;
808 AddrModeInsts = NewAddrModeInsts;
809 continue;
810 } else if (NewAddrMode == AddrMode) {
811 if (!IsNumUsesConsensusValid) {
812 NumUsesConsensus = Consensus->getNumUses();
813 IsNumUsesConsensusValid = true;
814 }
815
816 // Ensure that the obtained addressing mode is equivalent to that obtained
817 // for all other roots of the PHI traversal. Also, when choosing one
818 // such root as representative, select the one with the most uses in order
819 // to keep the cost modeling heuristics in AddressingModeMatcher
820 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000821 unsigned NumUses = V->getNumUses();
822 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000823 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000824 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000825 AddrModeInsts = NewAddrModeInsts;
826 }
827 continue;
828 }
829
830 Consensus = 0;
831 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000832 }
833
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 // If the addressing mode couldn't be determined, or if multiple different
835 // ones were determined, bail out now.
836 if (!Consensus) return false;
837
Chris Lattnerdd77df32007-04-13 20:30:56 +0000838 // Check to see if any of the instructions supersumed by this addr mode are
839 // non-local to I's BB.
840 bool AnyNonLocal = false;
841 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000842 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000843 AnyNonLocal = true;
844 break;
845 }
846 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000847
Chris Lattnerdd77df32007-04-13 20:30:56 +0000848 // If all the instructions matched are already in this BB, don't do anything.
849 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000850 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000851 return false;
852 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000853
Chris Lattnerdd77df32007-04-13 20:30:56 +0000854 // Insert this computation right after this user. Since our caller is
855 // scanning from the top of the BB to the bottom, reuse of the expr are
856 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000857 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000858
Chris Lattnerdd77df32007-04-13 20:30:56 +0000859 // Now that we determined the addressing expression we want to use and know
860 // that we have to sink it into this block. Check to see if we have already
861 // done this for some other load/store instr in this block. If so, reuse the
862 // computation.
863 Value *&SunkAddr = SunkAddrs[Addr];
864 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000865 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000866 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000867 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000868 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000869 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000870 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000871 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000872 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000873 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000874
Chris Lattnerdd77df32007-04-13 20:30:56 +0000875 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000876
877 // Start with the base register. Do this first so that subsequent address
878 // matching finds it last, which will prevent it from trying to match it
879 // as the scaled value in case it happens to be a mul. That would be
880 // problematic if we've sunk a different mul for the scale, because then
881 // we'd end up sinking both muls.
882 if (AddrMode.BaseReg) {
883 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000884 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000885 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000886 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000887 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000888 Result = V;
889 }
890
891 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000892 if (AddrMode.Scale) {
893 Value *V = AddrMode.ScaledReg;
894 if (V->getType() == IntPtrTy) {
895 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000896 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000897 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
899 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000900 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000901 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000902 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 }
904 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000905 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
906 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000907 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000908 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000909 else
910 Result = V;
911 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000912
Chris Lattnerdd77df32007-04-13 20:30:56 +0000913 // Add in the BaseGV if present.
914 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000915 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000916 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000917 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 else
919 Result = V;
920 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000921
Chris Lattnerdd77df32007-04-13 20:30:56 +0000922 // Add in the Base Offset if present.
923 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000924 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000926 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000927 else
928 Result = V;
929 }
930
931 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000932 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 else
Devang Patel2048c372011-09-06 18:49:53 +0000934 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000935 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000936
Owen Andersond2f41742010-11-19 22:15:03 +0000937 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000938
Chris Lattner0403b472011-04-09 07:05:44 +0000939 // If we have no uses, recursively delete the value and all dead instructions
940 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000941 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000942 // This can cause recursive deletion, which can invalidate our iterator.
943 // Use a WeakVH to hold onto it in case this happens.
944 WeakVH IterHandle(CurInstIterator);
945 BasicBlock *BB = CurInstIterator->getParent();
946
Owen Andersond2f41742010-11-19 22:15:03 +0000947 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000948
949 if (IterHandle != CurInstIterator) {
950 // If the iterator instruction was recursively deleted, start over at the
951 // start of the block.
952 CurInstIterator = BB->begin();
953 SunkAddrs.clear();
954 } else {
955 // This address is now available for reassignment, so erase the table
956 // entry; we don't want to match some completely different instruction.
957 SunkAddrs[Addr] = 0;
958 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000959 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000960 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000961 return true;
962}
963
Evan Cheng9bf12b52008-02-26 02:42:37 +0000964/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000965/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000966/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000967bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000968 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000969
Chris Lattner75796092011-01-15 07:14:54 +0000970 TargetLowering::AsmOperandInfoVector
971 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000972 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000973 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
974 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
975
Evan Cheng9bf12b52008-02-26 02:42:37 +0000976 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000977 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000978
Eli Friedman9ec80952008-02-26 18:37:49 +0000979 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
980 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000981 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000982 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000983 } else if (OpInfo.Type == InlineAsm::isInput)
984 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000985 }
986
987 return MadeChange;
988}
989
Dan Gohmanb00f2362009-10-16 20:59:35 +0000990/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
991/// basic block as the load, unless conditions are unfavorable. This allows
992/// SelectionDAG to fold the extend into the load.
993///
994bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
995 // Look for a load being extended.
996 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
997 if (!LI) return false;
998
999 // If they're already in the same block, there's nothing to do.
1000 if (LI->getParent() == I->getParent())
1001 return false;
1002
1003 // If the load has other users and the truncate is not free, this probably
1004 // isn't worthwhile.
1005 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001006 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1007 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001008 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001009 return false;
1010
1011 // Check whether the target supports casts folded into loads.
1012 unsigned LType;
1013 if (isa<ZExtInst>(I))
1014 LType = ISD::ZEXTLOAD;
1015 else {
1016 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1017 LType = ISD::SEXTLOAD;
1018 }
1019 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1020 return false;
1021
1022 // Move the extend into the same block as the load, so that SelectionDAG
1023 // can fold it.
1024 I->removeFromParent();
1025 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001026 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001027 return true;
1028}
1029
Evan Chengbdcb7262007-12-05 23:58:20 +00001030bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1031 BasicBlock *DefBB = I->getParent();
1032
Bob Wilson9120f5c2010-09-21 21:44:14 +00001033 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001034 // other uses of the source with result of extension.
1035 Value *Src = I->getOperand(0);
1036 if (Src->hasOneUse())
1037 return false;
1038
Evan Cheng696e5c02007-12-13 07:50:36 +00001039 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001040 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001041 return false;
1042
Evan Cheng772de512007-12-12 00:51:06 +00001043 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001044 // this block.
1045 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001046 return false;
1047
Evan Chengbdcb7262007-12-05 23:58:20 +00001048 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001049 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001050 UI != E; ++UI) {
1051 Instruction *User = cast<Instruction>(*UI);
1052
1053 // Figure out which BB this ext is used in.
1054 BasicBlock *UserBB = User->getParent();
1055 if (UserBB == DefBB) continue;
1056 DefIsLiveOut = true;
1057 break;
1058 }
1059 if (!DefIsLiveOut)
1060 return false;
1061
Evan Cheng765dff22007-12-12 02:53:41 +00001062 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001063 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001064 UI != E; ++UI) {
1065 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001066 BasicBlock *UserBB = User->getParent();
1067 if (UserBB == DefBB) continue;
1068 // Be conservative. We don't want this xform to end up introducing
1069 // reloads just before load / store instructions.
1070 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001071 return false;
1072 }
1073
Evan Chengbdcb7262007-12-05 23:58:20 +00001074 // InsertedTruncs - Only insert one trunc in each block once.
1075 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1076
1077 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001078 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001079 UI != E; ++UI) {
1080 Use &TheUse = UI.getUse();
1081 Instruction *User = cast<Instruction>(*UI);
1082
1083 // Figure out which BB this ext is used in.
1084 BasicBlock *UserBB = User->getParent();
1085 if (UserBB == DefBB) continue;
1086
1087 // Both src and def are live in this block. Rewrite the use.
1088 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1089
1090 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001091 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001092 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1093 }
1094
1095 // Replace a use of the {s|z}ext source with a use of the result.
1096 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001097 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001098 MadeChange = true;
1099 }
1100
1101 return MadeChange;
1102}
1103
Benjamin Kramer59957502012-05-05 12:49:22 +00001104/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1105/// turned into an explicit branch.
1106static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1107 // FIXME: This should use the same heuristics as IfConversion to determine
1108 // whether a select is better represented as a branch. This requires that
1109 // branch probability metadata is preserved for the select, which is not the
1110 // case currently.
1111
1112 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1113
1114 // If the branch is predicted right, an out of order CPU can avoid blocking on
1115 // the compare. Emit cmovs on compares with a memory operand as branches to
1116 // avoid stalls on the load from memory. If the compare has more than one use
1117 // there's probably another cmov or setcc around so it's not worth emitting a
1118 // branch.
1119 if (!Cmp)
1120 return false;
1121
1122 Value *CmpOp0 = Cmp->getOperand(0);
1123 Value *CmpOp1 = Cmp->getOperand(1);
1124
1125 // We check that the memory operand has one use to avoid uses of the loaded
1126 // value directly after the compare, making branches unprofitable.
1127 return Cmp->hasOneUse() &&
1128 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1129 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1130}
1131
1132
1133bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1134 // If we have a SelectInst that will likely profit from branch prediction,
1135 // turn it into a branch.
Benjamin Kramer77c4ef82012-05-06 14:25:16 +00001136 if (DisableSelectToBranch || OptSize || !TLI->isPredictableSelectExpensive())
Benjamin Kramer59957502012-05-05 12:49:22 +00001137 return false;
1138
1139 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1140 !isFormingBranchFromSelectProfitable(SI))
1141 return false;
1142
1143 ModifiedDT = true;
1144
1145 // First, we split the block containing the select into 2 blocks.
1146 BasicBlock *StartBlock = SI->getParent();
1147 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1148 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1149
1150 // Create a new block serving as the landing pad for the branch.
1151 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1152 NextBlock->getParent(), NextBlock);
1153
1154 // Move the unconditional branch from the block with the select in it into our
1155 // landing pad block.
1156 StartBlock->getTerminator()->eraseFromParent();
1157 BranchInst::Create(NextBlock, SmallBlock);
1158
1159 // Insert the real conditional branch based on the original condition.
1160 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1161
1162 // The select itself is replaced with a PHI Node.
1163 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1164 PN->takeName(SI);
1165 PN->addIncoming(SI->getTrueValue(), StartBlock);
1166 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1167 SI->replaceAllUsesWith(PN);
1168 SI->eraseFromParent();
1169
1170 // Instruct OptimizeBlock to skip to the next block.
1171 CurInstIterator = StartBlock->end();
1172 ++NumSelectsExpanded;
1173 return true;
1174}
1175
Cameron Zwarichc0611012011-01-06 02:37:26 +00001176bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001177 if (PHINode *P = dyn_cast<PHINode>(I)) {
1178 // It is possible for very late stage optimizations (such as SimplifyCFG)
1179 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1180 // trivial PHI, go ahead and zap it here.
1181 if (Value *V = SimplifyInstruction(P)) {
1182 P->replaceAllUsesWith(V);
1183 P->eraseFromParent();
1184 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001185 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001186 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001187 return false;
1188 }
1189
1190 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001191 // If the source of the cast is a constant, then this should have
1192 // already been constant folded. The only reason NOT to constant fold
1193 // it is if something (e.g. LSR) was careful to place the constant
1194 // evaluation in a block other than then one that uses it (e.g. to hoist
1195 // the address of globals out of a loop). If this is the case, we don't
1196 // want to forward-subst the cast.
1197 if (isa<Constant>(CI->getOperand(0)))
1198 return false;
1199
Chris Lattner1a8943a2011-01-15 07:29:01 +00001200 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1201 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001202
Chris Lattner1a8943a2011-01-15 07:29:01 +00001203 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1204 bool MadeChange = MoveExtToFormExtLoad(I);
1205 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001206 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001207 return false;
1208 }
1209
1210 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1211 return OptimizeCmpExpression(CI);
1212
1213 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001214 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001215 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1216 return false;
1217 }
1218
1219 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001220 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001221 return OptimizeMemoryInst(I, SI->getOperand(1),
1222 SI->getOperand(0)->getType());
1223 return false;
1224 }
1225
1226 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001227 if (GEPI->hasAllZeroIndices()) {
1228 /// The GEP operand must be a pointer, so must its result -> BitCast
1229 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1230 GEPI->getName(), GEPI);
1231 GEPI->replaceAllUsesWith(NC);
1232 GEPI->eraseFromParent();
1233 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001234 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001235 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001236 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001237 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001238 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001239
1240 if (CallInst *CI = dyn_cast<CallInst>(I))
1241 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001242
Evan Cheng485fafc2011-03-21 01:19:09 +00001243 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1244 return DupRetToEnableTailCallOpts(RI);
1245
Benjamin Kramer59957502012-05-05 12:49:22 +00001246 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1247 return OptimizeSelectInst(SI);
1248
Chris Lattner1a8943a2011-01-15 07:29:01 +00001249 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001250}
1251
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001252// In this pass we look for GEP and cast instructions that are used
1253// across basic blocks and rewrite them to improve basic-block-at-a-time
1254// selection.
1255bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001256 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001257 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001258
Chris Lattner75796092011-01-15 07:14:54 +00001259 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001260 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1261 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001262
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001263 return MadeChange;
1264}
Devang Patelf56ea612011-08-18 00:50:51 +00001265
1266// llvm.dbg.value is far away from the value then iSel may not be able
1267// handle it properly. iSel will drop llvm.dbg.value if it can not
1268// find a node corresponding to the value.
1269bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1270 bool MadeChange = false;
1271 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1272 Instruction *PrevNonDbgInst = NULL;
1273 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1274 Instruction *Insn = BI; ++BI;
1275 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1276 if (!DVI) {
1277 PrevNonDbgInst = Insn;
1278 continue;
1279 }
1280
1281 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1282 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1283 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1284 DVI->removeFromParent();
1285 if (isa<PHINode>(VI))
1286 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1287 else
1288 DVI->insertAfter(VI);
1289 MadeChange = true;
1290 ++NumDbgValueMoved;
1291 }
1292 }
1293 }
1294 return MadeChange;
1295}