blob: 291274d715ef0075cc0927f805ee2ca679d41034 [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 Kramer59957502012-05-05 12:49:22 +000074static cl::opt<bool> EnableSelectToBranch("enable-cgp-select2branch", cl::Hidden,
75 cl::desc("Enable select to branch conversion."));
76
Eric Christopher692bf6b2008-09-24 05:32:41 +000077namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000078 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000079 /// TLI - Keep a pointer of a TargetLowering to consult for determining
80 /// transformation profitability.
81 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000082 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000083 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000084 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000085
86 /// CurInstIterator - As we scan instructions optimizing them, this is the
87 /// next instruction to optimize. Xforms that can invalidate this should
88 /// update it.
89 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000090
Evan Cheng485fafc2011-03-21 01:19:09 +000091 /// Keeps track of non-local addresses that have been sunk into a block.
92 /// This allows us to avoid inserting duplicate code for blocks with
93 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000094 DenseMap<Value*, Value*> SunkAddrs;
95
Devang Patel52e37df2011-03-24 15:35:25 +000096 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000097 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000098 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000099
Benjamin Kramer59957502012-05-05 12:49:22 +0000100 /// OptSize - True if optimizing for size.
101 bool OptSize;
102
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000103 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000104 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000105 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000106 : FunctionPass(ID), TLI(tli) {
107 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
108 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000110
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000112 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000114 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000115 }
116
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000117 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118 bool EliminateMostlyEmptyBlocks(Function &F);
119 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
120 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000121 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000122 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000123 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000124 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000125 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000126 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000127 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000128 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000129 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000130 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000131 };
132}
Devang Patel794fd752007-05-01 21:15:47 +0000133
Devang Patel19974732007-05-03 01:11:54 +0000134char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000135INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
136 "Optimize for code generation", false, false)
137INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
138INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000139 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000140
141FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
142 return new CodeGenPrepare(TLI);
143}
144
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000145bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147
Devang Patel52e37df2011-03-24 15:35:25 +0000148 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000149 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000150 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000151 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000152 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000153
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000154 // First pass, eliminate blocks that contain only PHI nodes and an
155 // unconditional branch.
156 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000157
Devang Patelf56ea612011-08-18 00:50:51 +0000158 // llvm.dbg.value is far away from the value then iSel may not be able
159 // handle it properly. iSel will drop llvm.dbg.value if it can not
160 // find a node corresponding to the value.
161 EverMadeChange |= PlaceDbgValues(F);
162
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000164 while (MadeChange) {
165 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000166 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
167 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000168 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000169 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000170 EverMadeChange |= MadeChange;
171 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000172
173 SunkAddrs.clear();
174
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000175 if (!DisableBranchOpts) {
176 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000177 SmallPtrSet<BasicBlock*, 8> WorkList;
178 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
179 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000180 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000181 if (!MadeChange) continue;
182
183 for (SmallVectorImpl<BasicBlock*>::iterator
184 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
185 if (pred_begin(*II) == pred_end(*II))
186 WorkList.insert(*II);
187 }
188
189 if (!DisableDeleteDeadBlocks)
190 for (SmallPtrSet<BasicBlock*, 8>::iterator
191 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
192 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000193
Evan Cheng485fafc2011-03-21 01:19:09 +0000194 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000195 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000196 EverMadeChange |= MadeChange;
197 }
198
Devang Patel52e37df2011-03-24 15:35:25 +0000199 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000200 DT->DT->recalculate(F);
201
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000202 return EverMadeChange;
203}
204
Dale Johannesen2d697242009-03-27 01:13:37 +0000205/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
206/// debug info directives, and an unconditional branch. Passes before isel
207/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
208/// isel. Start by eliminating these blocks so we can split them the way we
209/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000210bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
211 bool MadeChange = false;
212 // Note that this intentionally skips the entry block.
213 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
214 BasicBlock *BB = I++;
215
216 // If this block doesn't end with an uncond branch, ignore it.
217 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
218 if (!BI || !BI->isUnconditional())
219 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220
Dale Johannesen2d697242009-03-27 01:13:37 +0000221 // If the instruction before the branch (skipping debug info) isn't a phi
222 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000223 BasicBlock::iterator BBI = BI;
224 if (BBI != BB->begin()) {
225 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000226 while (isa<DbgInfoIntrinsic>(BBI)) {
227 if (BBI == BB->begin())
228 break;
229 --BBI;
230 }
231 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
232 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000233 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000234
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000235 // Do not break infinite loops.
236 BasicBlock *DestBB = BI->getSuccessor(0);
237 if (DestBB == BB)
238 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000239
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000240 if (!CanMergeBlocks(BB, DestBB))
241 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000242
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000243 EliminateMostlyEmptyBlock(BB);
244 MadeChange = true;
245 }
246 return MadeChange;
247}
248
249/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
250/// single uncond branch between them, and BB contains no other non-phi
251/// instructions.
252bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
253 const BasicBlock *DestBB) const {
254 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
255 // the successor. If there are more complex condition (e.g. preheaders),
256 // don't mess around with them.
257 BasicBlock::const_iterator BBI = BB->begin();
258 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000259 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 UI != E; ++UI) {
261 const Instruction *User = cast<Instruction>(*UI);
262 if (User->getParent() != DestBB || !isa<PHINode>(User))
263 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000264 // If User is inside DestBB block and it is a PHINode then check
265 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000266 // a complex condition (e.g. preheaders) we want to avoid here.
267 if (User->getParent() == DestBB) {
268 if (const PHINode *UPN = dyn_cast<PHINode>(User))
269 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
270 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
271 if (Insn && Insn->getParent() == BB &&
272 Insn->getParent() != UPN->getIncomingBlock(I))
273 return false;
274 }
275 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 }
277 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000278
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000279 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
280 // and DestBB may have conflicting incoming values for the block. If so, we
281 // can't merge the block.
282 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
283 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000285 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000286 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000287 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
288 // It is faster to get preds from a PHI than with pred_iterator.
289 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
290 BBPreds.insert(BBPN->getIncomingBlock(i));
291 } else {
292 BBPreds.insert(pred_begin(BB), pred_end(BB));
293 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000294
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 // Walk the preds of DestBB.
296 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
297 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
298 if (BBPreds.count(Pred)) { // Common predecessor?
299 BBI = DestBB->begin();
300 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
301 const Value *V1 = PN->getIncomingValueForBlock(Pred);
302 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000303
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000304 // If V2 is a phi node in BB, look up what the mapped value will be.
305 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
306 if (V2PN->getParent() == BB)
307 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000308
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000309 // If there is a conflict, bail out.
310 if (V1 != V2) return false;
311 }
312 }
313 }
314
315 return true;
316}
317
318
319/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
320/// an unconditional branch in it.
321void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
322 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
323 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324
David Greene68d67fd2010-01-05 01:27:11 +0000325 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000326
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000327 // If the destination block has a single pred, then this is a trivial edge,
328 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000329 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000330 if (SinglePred != DestBB) {
331 // Remember if SinglePred was the entry block of the function. If so, we
332 // will need to move BB back to the entry position.
333 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000334 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000335
Chris Lattnerf5102a02008-11-28 19:54:49 +0000336 if (isEntry && BB != &BB->getParent()->getEntryBlock())
337 BB->moveBefore(&BB->getParent()->getEntryBlock());
338
David Greene68d67fd2010-01-05 01:27:11 +0000339 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000340 return;
341 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000342 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000343
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000344 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
345 // to handle the new incoming edges it is about to have.
346 PHINode *PN;
347 for (BasicBlock::iterator BBI = DestBB->begin();
348 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
349 // Remove the incoming value for BB, and remember it.
350 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352 // Two options: either the InVal is a phi node defined in BB or it is some
353 // value that dominates BB.
354 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
355 if (InValPhi && InValPhi->getParent() == BB) {
356 // Add all of the input values of the input PHI as inputs of this phi.
357 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
358 PN->addIncoming(InValPhi->getIncomingValue(i),
359 InValPhi->getIncomingBlock(i));
360 } else {
361 // Otherwise, add one instance of the dominating value for each edge that
362 // we will be adding.
363 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
364 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
365 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
366 } else {
367 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
368 PN->addIncoming(InVal, *PI);
369 }
370 }
371 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000372
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000373 // The PHIs are now updated, change everything that refers to BB to use
374 // DestBB and remove BB.
375 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000376 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000377 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
378 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
379 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
380 DT->changeImmediateDominator(DestBB, NewIDom);
381 DT->eraseNode(BB);
382 }
Evan Cheng04149f72009-12-17 09:39:49 +0000383 if (PFI) {
384 PFI->replaceAllUses(BB, DestBB);
385 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000386 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000387 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000388 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
David Greene68d67fd2010-01-05 01:27:11 +0000390 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000391}
392
Chris Lattnerdd77df32007-04-13 20:30:56 +0000393/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000394/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
395/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000396/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000397///
398/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000399///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000400static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000401 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000402 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
403 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000404
Chris Lattnerdd77df32007-04-13 20:30:56 +0000405 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000406 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000407 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000408
Chris Lattnerdd77df32007-04-13 20:30:56 +0000409 // If this is an extension, it will be a zero or sign extension, which
410 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000411 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerdd77df32007-04-13 20:30:56 +0000413 // If these values will be promoted, find out what they will be promoted
414 // to. This helps us consider truncates on PPC as noop copies when they
415 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000416 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
417 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000418 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000419 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
420 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000421 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Chris Lattnerdd77df32007-04-13 20:30:56 +0000423 // If, after promotion, these are the same types, this is a noop copy.
424 if (SrcVT != DstVT)
425 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000427 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000429 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000430 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000432 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000434 UI != E; ) {
435 Use &TheUse = UI.getUse();
436 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000438 // Figure out which BB this cast is used in. For PHI's this is the
439 // appropriate predecessor block.
440 BasicBlock *UserBB = User->getParent();
441 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000442 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000443 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000445 // Preincrement use iterator so we don't invalidate it.
446 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000448 // If this user is in the same block as the cast, don't change the cast.
449 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000450
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000451 // If we have already inserted a cast into this block, use it.
452 CastInst *&InsertedCast = InsertedCasts[UserBB];
453
454 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000455 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456 InsertedCast =
457 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000458 InsertPt);
459 MadeChange = true;
460 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000464 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000465 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000466
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000467 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000468 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000470 MadeChange = true;
471 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 return MadeChange;
474}
475
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000477/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000478/// a clear win except on targets with multiple condition code registers
479/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000480///
481/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000482static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000483 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Dale Johannesence0b2372007-06-12 16:50:17 +0000485 /// InsertedCmp - Only insert a cmp in each block once.
486 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Dale Johannesence0b2372007-06-12 16:50:17 +0000488 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000490 UI != E; ) {
491 Use &TheUse = UI.getUse();
492 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Dale Johannesence0b2372007-06-12 16:50:17 +0000494 // Preincrement use iterator so we don't invalidate it.
495 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Dale Johannesence0b2372007-06-12 16:50:17 +0000497 // Don't bother for PHI nodes.
498 if (isa<PHINode>(User))
499 continue;
500
501 // Figure out which BB this cmp is used in.
502 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503
Dale Johannesence0b2372007-06-12 16:50:17 +0000504 // If this user is in the same block as the cmp, don't change the cmp.
505 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Dale Johannesence0b2372007-06-12 16:50:17 +0000507 // If we have already inserted a cmp into this block, use it.
508 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
509
510 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000511 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000513 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000514 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 CI->getOperand(1), "", InsertPt);
516 MadeChange = true;
517 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 // Replace a use of the cmp with a use of the new cmp.
520 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000521 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523
Dale Johannesence0b2372007-06-12 16:50:17 +0000524 // If we removed all uses, nuke the cmp.
525 if (CI->use_empty())
526 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 return MadeChange;
529}
530
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000531namespace {
532class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
533protected:
534 void replaceCall(Value *With) {
535 CI->replaceAllUsesWith(With);
536 CI->eraseFromParent();
537 }
538 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000539 if (ConstantInt *SizeCI =
540 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
541 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000542 return false;
543 }
544};
545} // end anonymous namespace
546
Eric Christopher040056f2010-03-11 02:41:03 +0000547bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000548 BasicBlock *BB = CI->getParent();
549
550 // Lower inline assembly if we can.
551 // If we found an inline asm expession, and if the target knows how to
552 // lower it to normal LLVM code, do so now.
553 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
554 if (TLI->ExpandInlineAsm(CI)) {
555 // Avoid invalidating the iterator.
556 CurInstIterator = BB->begin();
557 // Avoid processing instructions out of order, which could cause
558 // reuse before a value is defined.
559 SunkAddrs.clear();
560 return true;
561 }
562 // Sink address computing for memory operands into the block.
563 if (OptimizeInlineAsmInst(CI))
564 return true;
565 }
566
Eric Christopher040056f2010-03-11 02:41:03 +0000567 // Lower all uses of llvm.objectsize.*
568 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
569 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000570 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000571 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000572 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000573
574 // Substituting this can cause recursive simplifications, which can
575 // invalidate our iterator. Use a WeakVH to hold onto it in case this
576 // happens.
577 WeakVH IterHandle(CurInstIterator);
578
Chandler Carruth6b980542012-03-24 21:11:24 +0000579 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
580 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000581
582 // If the iterator instruction was recursively deleted, start over at the
583 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000584 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000585 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000586 SunkAddrs.clear();
587 }
Eric Christopher040056f2010-03-11 02:41:03 +0000588 return true;
589 }
590
Pete Cooperf210b682012-03-13 20:59:56 +0000591 if (II && TLI) {
592 SmallVector<Value*, 2> PtrOps;
593 Type *AccessTy;
594 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
595 while (!PtrOps.empty())
596 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
597 return true;
598 }
599
Eric Christopher040056f2010-03-11 02:41:03 +0000600 // From here on out we're working with named functions.
601 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000602
Eric Christopher040056f2010-03-11 02:41:03 +0000603 // We'll need TargetData from here on out.
604 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
605 if (!TD) return false;
606
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000607 // Lower all default uses of _chk calls. This is very similar
608 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000609 // that have the default "don't know" as the objectsize. Anything else
610 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000611 CodeGenPrepareFortifiedLibCalls Simplifier;
612 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000613}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000614
Evan Cheng485fafc2011-03-21 01:19:09 +0000615/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
616/// instructions to the predecessor to enable tail call optimizations. The
617/// case it is currently looking for is:
618/// bb0:
619/// %tmp0 = tail call i32 @f0()
620/// br label %return
621/// bb1:
622/// %tmp1 = tail call i32 @f1()
623/// br label %return
624/// bb2:
625/// %tmp2 = tail call i32 @f2()
626/// br label %return
627/// return:
628/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
629/// ret i32 %retval
630///
631/// =>
632///
633/// bb0:
634/// %tmp0 = tail call i32 @f0()
635/// ret i32 %tmp0
636/// bb1:
637/// %tmp1 = tail call i32 @f1()
638/// ret i32 %tmp1
639/// bb2:
640/// %tmp2 = tail call i32 @f2()
641/// ret i32 %tmp2
642///
643bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000644 if (!TLI)
645 return false;
646
Evan Cheng485fafc2011-03-21 01:19:09 +0000647 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000648 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
649 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000650 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000651
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000652 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000653 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000654 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000655
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000656 // It's not safe to eliminate the sign / zero extension of the return value.
657 // See llvm::isInTailCallPosition().
658 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000659 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000660 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
661 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000662
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000663 // Make sure there are no instructions between the PHI and return, or that the
664 // return is the first instruction in the block.
665 if (PN) {
666 BasicBlock::iterator BI = BB->begin();
667 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
668 if (&*BI != RI)
669 return false;
670 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000671 BasicBlock::iterator BI = BB->begin();
672 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
673 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000674 return false;
675 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000676
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000677 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
678 /// call.
679 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000680 if (PN) {
681 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
682 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
683 // Make sure the phi value is indeed produced by the tail call.
684 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
685 TLI->mayBeEmittedAsTailCall(CI))
686 TailCalls.push_back(CI);
687 }
688 } else {
689 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
690 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
691 if (!VisitedBBs.insert(*PI))
692 continue;
693
694 BasicBlock::InstListType &InstList = (*PI)->getInstList();
695 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
696 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000697 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
698 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000699 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000700
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000701 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000702 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000703 TailCalls.push_back(CI);
704 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000705 }
706
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000707 bool Changed = false;
708 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
709 CallInst *CI = TailCalls[i];
710 CallSite CS(CI);
711
712 // Conservatively require the attributes of the call to match those of the
713 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000714 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000715 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
716 continue;
717
718 // Make sure the call instruction is followed by an unconditional branch to
719 // the return block.
720 BasicBlock *CallBB = CI->getParent();
721 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
722 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
723 continue;
724
725 // Duplicate the return into CallBB.
726 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000727 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000728 ++NumRetsDup;
729 }
730
731 // If we eliminated all predecessors of the block, delete the block now.
732 if (Changed && pred_begin(BB) == pred_end(BB))
733 BB->eraseFromParent();
734
735 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000736}
737
Chris Lattner88a5c832008-11-25 07:09:13 +0000738//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000739// Memory Optimization
740//===----------------------------------------------------------------------===//
741
Chris Lattnerdd77df32007-04-13 20:30:56 +0000742/// IsNonLocalValue - Return true if the specified values are defined in a
743/// different basic block than BB.
744static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
745 if (Instruction *I = dyn_cast<Instruction>(V))
746 return I->getParent() != BB;
747 return false;
748}
749
Bob Wilson4a8ee232009-12-03 21:47:07 +0000750/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000751/// addressing modes that can do significant amounts of computation. As such,
752/// instruction selection will try to get the load or store to do as much
753/// computation as possible for the program. The problem is that isel can only
754/// see within a single block. As such, we sink as much legal addressing mode
755/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000756///
757/// This method is used to optimize both load/store and inline asms with memory
758/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000759bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000760 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000761 Value *Repl = Addr;
762
Owen Andersond2f41742010-11-19 22:15:03 +0000763 // Try to collapse single-value PHI nodes. This is necessary to undo
764 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000765 SmallVector<Value*, 8> worklist;
766 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000767 worklist.push_back(Addr);
768
769 // Use a worklist to iteratively look through PHI nodes, and ensure that
770 // the addressing mode obtained from the non-PHI roots of the graph
771 // are equivalent.
772 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000773 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000774 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000775 SmallVector<Instruction*, 16> AddrModeInsts;
776 ExtAddrMode AddrMode;
777 while (!worklist.empty()) {
778 Value *V = worklist.back();
779 worklist.pop_back();
780
781 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000782 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000783 Consensus = 0;
784 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000785 }
786
Owen Anderson35bf4d62010-11-27 08:15:55 +0000787 // For a PHI node, push all of its incoming values.
788 if (PHINode *P = dyn_cast<PHINode>(V)) {
789 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
790 worklist.push_back(P->getIncomingValue(i));
791 continue;
792 }
793
794 // For non-PHIs, determine the addressing mode being computed.
795 SmallVector<Instruction*, 16> NewAddrModeInsts;
796 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000797 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000798 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000799
800 // This check is broken into two cases with very similar code to avoid using
801 // getNumUses() as much as possible. Some values have a lot of uses, so
802 // calling getNumUses() unconditionally caused a significant compile-time
803 // regression.
804 if (!Consensus) {
805 Consensus = V;
806 AddrMode = NewAddrMode;
807 AddrModeInsts = NewAddrModeInsts;
808 continue;
809 } else if (NewAddrMode == AddrMode) {
810 if (!IsNumUsesConsensusValid) {
811 NumUsesConsensus = Consensus->getNumUses();
812 IsNumUsesConsensusValid = true;
813 }
814
815 // Ensure that the obtained addressing mode is equivalent to that obtained
816 // for all other roots of the PHI traversal. Also, when choosing one
817 // such root as representative, select the one with the most uses in order
818 // to keep the cost modeling heuristics in AddressingModeMatcher
819 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000820 unsigned NumUses = V->getNumUses();
821 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000822 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000823 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000824 AddrModeInsts = NewAddrModeInsts;
825 }
826 continue;
827 }
828
829 Consensus = 0;
830 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000831 }
832
Owen Anderson35bf4d62010-11-27 08:15:55 +0000833 // If the addressing mode couldn't be determined, or if multiple different
834 // ones were determined, bail out now.
835 if (!Consensus) return false;
836
Chris Lattnerdd77df32007-04-13 20:30:56 +0000837 // Check to see if any of the instructions supersumed by this addr mode are
838 // non-local to I's BB.
839 bool AnyNonLocal = false;
840 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000841 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000842 AnyNonLocal = true;
843 break;
844 }
845 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000846
Chris Lattnerdd77df32007-04-13 20:30:56 +0000847 // If all the instructions matched are already in this BB, don't do anything.
848 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000849 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000850 return false;
851 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000852
Chris Lattnerdd77df32007-04-13 20:30:56 +0000853 // Insert this computation right after this user. Since our caller is
854 // scanning from the top of the BB to the bottom, reuse of the expr are
855 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000856 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000857
Chris Lattnerdd77df32007-04-13 20:30:56 +0000858 // Now that we determined the addressing expression we want to use and know
859 // that we have to sink it into this block. Check to see if we have already
860 // done this for some other load/store instr in this block. If so, reuse the
861 // computation.
862 Value *&SunkAddr = SunkAddrs[Addr];
863 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000864 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000865 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000866 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000867 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000868 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000869 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000870 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000871 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000872 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000873
Chris Lattnerdd77df32007-04-13 20:30:56 +0000874 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000875
876 // Start with the base register. Do this first so that subsequent address
877 // matching finds it last, which will prevent it from trying to match it
878 // as the scaled value in case it happens to be a mul. That would be
879 // problematic if we've sunk a different mul for the scale, because then
880 // we'd end up sinking both muls.
881 if (AddrMode.BaseReg) {
882 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000883 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000884 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000885 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000886 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000887 Result = V;
888 }
889
890 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000891 if (AddrMode.Scale) {
892 Value *V = AddrMode.ScaledReg;
893 if (V->getType() == IntPtrTy) {
894 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000895 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000896 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000897 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
898 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000899 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000900 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000901 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000902 }
903 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000904 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
905 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000906 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000907 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000908 else
909 Result = V;
910 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Chris Lattnerdd77df32007-04-13 20:30:56 +0000912 // Add in the BaseGV if present.
913 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000914 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000915 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000916 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 else
918 Result = V;
919 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000920
Chris Lattnerdd77df32007-04-13 20:30:56 +0000921 // Add in the Base Offset if present.
922 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000923 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000924 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000925 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000926 else
927 Result = V;
928 }
929
930 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000931 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000932 else
Devang Patel2048c372011-09-06 18:49:53 +0000933 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000934 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000935
Owen Andersond2f41742010-11-19 22:15:03 +0000936 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000937
Chris Lattner0403b472011-04-09 07:05:44 +0000938 // If we have no uses, recursively delete the value and all dead instructions
939 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000940 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000941 // This can cause recursive deletion, which can invalidate our iterator.
942 // Use a WeakVH to hold onto it in case this happens.
943 WeakVH IterHandle(CurInstIterator);
944 BasicBlock *BB = CurInstIterator->getParent();
945
Owen Andersond2f41742010-11-19 22:15:03 +0000946 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000947
948 if (IterHandle != CurInstIterator) {
949 // If the iterator instruction was recursively deleted, start over at the
950 // start of the block.
951 CurInstIterator = BB->begin();
952 SunkAddrs.clear();
953 } else {
954 // This address is now available for reassignment, so erase the table
955 // entry; we don't want to match some completely different instruction.
956 SunkAddrs[Addr] = 0;
957 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000958 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000959 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000960 return true;
961}
962
Evan Cheng9bf12b52008-02-26 02:42:37 +0000963/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000964/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000965/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000966bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000967 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000968
Chris Lattner75796092011-01-15 07:14:54 +0000969 TargetLowering::AsmOperandInfoVector
970 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000971 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000972 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
973 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
974
Evan Cheng9bf12b52008-02-26 02:42:37 +0000975 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000976 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000977
Eli Friedman9ec80952008-02-26 18:37:49 +0000978 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
979 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000980 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000981 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000982 } else if (OpInfo.Type == InlineAsm::isInput)
983 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000984 }
985
986 return MadeChange;
987}
988
Dan Gohmanb00f2362009-10-16 20:59:35 +0000989/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
990/// basic block as the load, unless conditions are unfavorable. This allows
991/// SelectionDAG to fold the extend into the load.
992///
993bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
994 // Look for a load being extended.
995 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
996 if (!LI) return false;
997
998 // If they're already in the same block, there's nothing to do.
999 if (LI->getParent() == I->getParent())
1000 return false;
1001
1002 // If the load has other users and the truncate is not free, this probably
1003 // isn't worthwhile.
1004 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001005 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1006 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001007 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001008 return false;
1009
1010 // Check whether the target supports casts folded into loads.
1011 unsigned LType;
1012 if (isa<ZExtInst>(I))
1013 LType = ISD::ZEXTLOAD;
1014 else {
1015 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1016 LType = ISD::SEXTLOAD;
1017 }
1018 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1019 return false;
1020
1021 // Move the extend into the same block as the load, so that SelectionDAG
1022 // can fold it.
1023 I->removeFromParent();
1024 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001025 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001026 return true;
1027}
1028
Evan Chengbdcb7262007-12-05 23:58:20 +00001029bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1030 BasicBlock *DefBB = I->getParent();
1031
Bob Wilson9120f5c2010-09-21 21:44:14 +00001032 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001033 // other uses of the source with result of extension.
1034 Value *Src = I->getOperand(0);
1035 if (Src->hasOneUse())
1036 return false;
1037
Evan Cheng696e5c02007-12-13 07:50:36 +00001038 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001039 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001040 return false;
1041
Evan Cheng772de512007-12-12 00:51:06 +00001042 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001043 // this block.
1044 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001045 return false;
1046
Evan Chengbdcb7262007-12-05 23:58:20 +00001047 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001048 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001049 UI != E; ++UI) {
1050 Instruction *User = cast<Instruction>(*UI);
1051
1052 // Figure out which BB this ext is used in.
1053 BasicBlock *UserBB = User->getParent();
1054 if (UserBB == DefBB) continue;
1055 DefIsLiveOut = true;
1056 break;
1057 }
1058 if (!DefIsLiveOut)
1059 return false;
1060
Evan Cheng765dff22007-12-12 02:53:41 +00001061 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001062 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001063 UI != E; ++UI) {
1064 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001065 BasicBlock *UserBB = User->getParent();
1066 if (UserBB == DefBB) continue;
1067 // Be conservative. We don't want this xform to end up introducing
1068 // reloads just before load / store instructions.
1069 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001070 return false;
1071 }
1072
Evan Chengbdcb7262007-12-05 23:58:20 +00001073 // InsertedTruncs - Only insert one trunc in each block once.
1074 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1075
1076 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001077 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001078 UI != E; ++UI) {
1079 Use &TheUse = UI.getUse();
1080 Instruction *User = cast<Instruction>(*UI);
1081
1082 // Figure out which BB this ext is used in.
1083 BasicBlock *UserBB = User->getParent();
1084 if (UserBB == DefBB) continue;
1085
1086 // Both src and def are live in this block. Rewrite the use.
1087 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1088
1089 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001090 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001091 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1092 }
1093
1094 // Replace a use of the {s|z}ext source with a use of the result.
1095 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001096 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001097 MadeChange = true;
1098 }
1099
1100 return MadeChange;
1101}
1102
Benjamin Kramer59957502012-05-05 12:49:22 +00001103/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1104/// turned into an explicit branch.
1105static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1106 // FIXME: This should use the same heuristics as IfConversion to determine
1107 // whether a select is better represented as a branch. This requires that
1108 // branch probability metadata is preserved for the select, which is not the
1109 // case currently.
1110
1111 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1112
1113 // If the branch is predicted right, an out of order CPU can avoid blocking on
1114 // the compare. Emit cmovs on compares with a memory operand as branches to
1115 // avoid stalls on the load from memory. If the compare has more than one use
1116 // there's probably another cmov or setcc around so it's not worth emitting a
1117 // branch.
1118 if (!Cmp)
1119 return false;
1120
1121 Value *CmpOp0 = Cmp->getOperand(0);
1122 Value *CmpOp1 = Cmp->getOperand(1);
1123
1124 // We check that the memory operand has one use to avoid uses of the loaded
1125 // value directly after the compare, making branches unprofitable.
1126 return Cmp->hasOneUse() &&
1127 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1128 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1129}
1130
1131
1132bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1133 // If we have a SelectInst that will likely profit from branch prediction,
1134 // turn it into a branch.
1135 if (!EnableSelectToBranch || OptSize || !TLI->isPredictableSelectExpensive())
1136 return false;
1137
1138 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1139 !isFormingBranchFromSelectProfitable(SI))
1140 return false;
1141
1142 ModifiedDT = true;
1143
1144 // First, we split the block containing the select into 2 blocks.
1145 BasicBlock *StartBlock = SI->getParent();
1146 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1147 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1148
1149 // Create a new block serving as the landing pad for the branch.
1150 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1151 NextBlock->getParent(), NextBlock);
1152
1153 // Move the unconditional branch from the block with the select in it into our
1154 // landing pad block.
1155 StartBlock->getTerminator()->eraseFromParent();
1156 BranchInst::Create(NextBlock, SmallBlock);
1157
1158 // Insert the real conditional branch based on the original condition.
1159 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1160
1161 // The select itself is replaced with a PHI Node.
1162 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1163 PN->takeName(SI);
1164 PN->addIncoming(SI->getTrueValue(), StartBlock);
1165 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1166 SI->replaceAllUsesWith(PN);
1167 SI->eraseFromParent();
1168
1169 // Instruct OptimizeBlock to skip to the next block.
1170 CurInstIterator = StartBlock->end();
1171 ++NumSelectsExpanded;
1172 return true;
1173}
1174
Cameron Zwarichc0611012011-01-06 02:37:26 +00001175bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001176 if (PHINode *P = dyn_cast<PHINode>(I)) {
1177 // It is possible for very late stage optimizations (such as SimplifyCFG)
1178 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1179 // trivial PHI, go ahead and zap it here.
1180 if (Value *V = SimplifyInstruction(P)) {
1181 P->replaceAllUsesWith(V);
1182 P->eraseFromParent();
1183 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001184 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001185 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001186 return false;
1187 }
1188
1189 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001190 // If the source of the cast is a constant, then this should have
1191 // already been constant folded. The only reason NOT to constant fold
1192 // it is if something (e.g. LSR) was careful to place the constant
1193 // evaluation in a block other than then one that uses it (e.g. to hoist
1194 // the address of globals out of a loop). If this is the case, we don't
1195 // want to forward-subst the cast.
1196 if (isa<Constant>(CI->getOperand(0)))
1197 return false;
1198
Chris Lattner1a8943a2011-01-15 07:29:01 +00001199 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1200 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001201
Chris Lattner1a8943a2011-01-15 07:29:01 +00001202 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1203 bool MadeChange = MoveExtToFormExtLoad(I);
1204 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001205 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001206 return false;
1207 }
1208
1209 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1210 return OptimizeCmpExpression(CI);
1211
1212 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001213 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001214 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1215 return false;
1216 }
1217
1218 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001219 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001220 return OptimizeMemoryInst(I, SI->getOperand(1),
1221 SI->getOperand(0)->getType());
1222 return false;
1223 }
1224
1225 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001226 if (GEPI->hasAllZeroIndices()) {
1227 /// The GEP operand must be a pointer, so must its result -> BitCast
1228 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1229 GEPI->getName(), GEPI);
1230 GEPI->replaceAllUsesWith(NC);
1231 GEPI->eraseFromParent();
1232 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001233 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001234 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001235 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001236 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001237 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001238
1239 if (CallInst *CI = dyn_cast<CallInst>(I))
1240 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001241
Evan Cheng485fafc2011-03-21 01:19:09 +00001242 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1243 return DupRetToEnableTailCallOpts(RI);
1244
Benjamin Kramer59957502012-05-05 12:49:22 +00001245 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1246 return OptimizeSelectInst(SI);
1247
Chris Lattner1a8943a2011-01-15 07:29:01 +00001248 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001249}
1250
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001251// In this pass we look for GEP and cast instructions that are used
1252// across basic blocks and rewrite them to improve basic-block-at-a-time
1253// selection.
1254bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001255 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001256 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001257
Chris Lattner75796092011-01-15 07:14:54 +00001258 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001259 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1260 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001261
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001262 return MadeChange;
1263}
Devang Patelf56ea612011-08-18 00:50:51 +00001264
1265// llvm.dbg.value is far away from the value then iSel may not be able
1266// handle it properly. iSel will drop llvm.dbg.value if it can not
1267// find a node corresponding to the value.
1268bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1269 bool MadeChange = false;
1270 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1271 Instruction *PrevNonDbgInst = NULL;
1272 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1273 Instruction *Insn = BI; ++BI;
1274 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1275 if (!DVI) {
1276 PrevNonDbgInst = Insn;
1277 continue;
1278 }
1279
1280 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1281 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1282 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1283 DVI->removeFromParent();
1284 if (isa<PHINode>(VI))
1285 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1286 else
1287 DVI->insertAfter(VI);
1288 MadeChange = true;
1289 ++NumDbgValueMoved;
1290 }
1291 }
1292 }
1293 return MadeChange;
1294}