blob: f9abfe9802ce48f947cae291e241f02e2849539d [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000025#include "llvm/Analysis/Dominators.h"
Owen Andersond5f86842010-12-23 20:57:35 +000026#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000027#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/Target/TargetData.h"
Chad Rosier618c1db2011-12-01 03:08:23 +000029#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000031#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000033#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000036#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000037#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000038#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000039#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000043#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000044#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000045#include "llvm/Support/IRBuilder.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000046#include "llvm/Support/ValueHandle.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000063
Cameron Zwarich899eaa32011-03-11 21:52:04 +000064static cl::opt<bool> DisableBranchOpts(
65 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
66 cl::desc("Disable branch optimizations in CodeGenPrepare"));
67
Eric Christopher692bf6b2008-09-24 05:32:41 +000068namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000069 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000070 /// TLI - Keep a pointer of a TargetLowering to consult for determining
71 /// transformation profitability.
72 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000073 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000074 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000075 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000076
77 /// CurInstIterator - As we scan instructions optimizing them, this is the
78 /// next instruction to optimize. Xforms that can invalidate this should
79 /// update it.
80 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000081
Evan Cheng485fafc2011-03-21 01:19:09 +000082 /// Keeps track of non-local addresses that have been sunk into a block.
83 /// This allows us to avoid inserting duplicate code for blocks with
84 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000085 DenseMap<Value*, Value*> SunkAddrs;
86
Devang Patel52e37df2011-03-24 15:35:25 +000087 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000088 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000089 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000090
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000091 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000092 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000093 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000094 : FunctionPass(ID), TLI(tli) {
95 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
96 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000097 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000098
Andreas Neustifterad809812009-09-16 09:26:52 +000099 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000100 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000101 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000102 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000103 }
104
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000105 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000106 bool EliminateMostlyEmptyBlocks(Function &F);
107 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
108 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000110 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000111 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000112 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000113 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000114 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000115 bool OptimizeExtUses(Instruction *I);
Evan Cheng485fafc2011-03-21 01:19:09 +0000116 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000117 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 };
119}
Devang Patel794fd752007-05-01 21:15:47 +0000120
Devang Patel19974732007-05-03 01:11:54 +0000121char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000122INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
123 "Optimize for code generation", false, false)
124INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
125INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000126 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000127
128FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
129 return new CodeGenPrepare(TLI);
130}
131
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000133 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000134
Devang Patel52e37df2011-03-24 15:35:25 +0000135 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000136 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000137 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000138 PFI = getAnalysisIfAvailable<ProfileInfo>();
Evan Cheng485fafc2011-03-21 01:19:09 +0000139
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000140 // First pass, eliminate blocks that contain only PHI nodes and an
141 // unconditional branch.
142 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000143
Devang Patelf56ea612011-08-18 00:50:51 +0000144 // llvm.dbg.value is far away from the value then iSel may not be able
145 // handle it properly. iSel will drop llvm.dbg.value if it can not
146 // find a node corresponding to the value.
147 EverMadeChange |= PlaceDbgValues(F);
148
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000149 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000150 while (MadeChange) {
151 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000152 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
153 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000154 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000155 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000156 EverMadeChange |= MadeChange;
157 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000158
159 SunkAddrs.clear();
160
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000161 if (!DisableBranchOpts) {
162 MadeChange = false;
163 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Frits van Bommel5649ba72011-05-22 16:24:18 +0000164 MadeChange |= ConstantFoldTerminator(BB, true);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000165
Evan Cheng485fafc2011-03-21 01:19:09 +0000166 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000167 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000168 EverMadeChange |= MadeChange;
169 }
170
Devang Patel52e37df2011-03-24 15:35:25 +0000171 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000172 DT->DT->recalculate(F);
173
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000174 return EverMadeChange;
175}
176
Dale Johannesen2d697242009-03-27 01:13:37 +0000177/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
178/// debug info directives, and an unconditional branch. Passes before isel
179/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
180/// isel. Start by eliminating these blocks so we can split them the way we
181/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000182bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
183 bool MadeChange = false;
184 // Note that this intentionally skips the entry block.
185 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
186 BasicBlock *BB = I++;
187
188 // If this block doesn't end with an uncond branch, ignore it.
189 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
190 if (!BI || !BI->isUnconditional())
191 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000192
Dale Johannesen2d697242009-03-27 01:13:37 +0000193 // If the instruction before the branch (skipping debug info) isn't a phi
194 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000195 BasicBlock::iterator BBI = BI;
196 if (BBI != BB->begin()) {
197 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000198 while (isa<DbgInfoIntrinsic>(BBI)) {
199 if (BBI == BB->begin())
200 break;
201 --BBI;
202 }
203 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
204 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000206
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000207 // Do not break infinite loops.
208 BasicBlock *DestBB = BI->getSuccessor(0);
209 if (DestBB == BB)
210 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 if (!CanMergeBlocks(BB, DestBB))
213 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000214
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000215 EliminateMostlyEmptyBlock(BB);
216 MadeChange = true;
217 }
218 return MadeChange;
219}
220
221/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
222/// single uncond branch between them, and BB contains no other non-phi
223/// instructions.
224bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
225 const BasicBlock *DestBB) const {
226 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
227 // the successor. If there are more complex condition (e.g. preheaders),
228 // don't mess around with them.
229 BasicBlock::const_iterator BBI = BB->begin();
230 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000231 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000232 UI != E; ++UI) {
233 const Instruction *User = cast<Instruction>(*UI);
234 if (User->getParent() != DestBB || !isa<PHINode>(User))
235 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000236 // If User is inside DestBB block and it is a PHINode then check
237 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000238 // a complex condition (e.g. preheaders) we want to avoid here.
239 if (User->getParent() == DestBB) {
240 if (const PHINode *UPN = dyn_cast<PHINode>(User))
241 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
242 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
243 if (Insn && Insn->getParent() == BB &&
244 Insn->getParent() != UPN->getIncomingBlock(I))
245 return false;
246 }
247 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000248 }
249 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000250
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
252 // and DestBB may have conflicting incoming values for the block. If so, we
253 // can't merge the block.
254 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
255 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000256
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000257 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000258 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
260 // It is faster to get preds from a PHI than with pred_iterator.
261 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
262 BBPreds.insert(BBPN->getIncomingBlock(i));
263 } else {
264 BBPreds.insert(pred_begin(BB), pred_end(BB));
265 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000266
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000267 // Walk the preds of DestBB.
268 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
269 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
270 if (BBPreds.count(Pred)) { // Common predecessor?
271 BBI = DestBB->begin();
272 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
273 const Value *V1 = PN->getIncomingValueForBlock(Pred);
274 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000275
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 // If V2 is a phi node in BB, look up what the mapped value will be.
277 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
278 if (V2PN->getParent() == BB)
279 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000281 // If there is a conflict, bail out.
282 if (V1 != V2) return false;
283 }
284 }
285 }
286
287 return true;
288}
289
290
291/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
292/// an unconditional branch in it.
293void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
294 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
295 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000296
David Greene68d67fd2010-01-05 01:27:11 +0000297 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000298
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000299 // If the destination block has a single pred, then this is a trivial edge,
300 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000301 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000302 if (SinglePred != DestBB) {
303 // Remember if SinglePred was the entry block of the function. If so, we
304 // will need to move BB back to the entry position.
305 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000306 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000307
Chris Lattnerf5102a02008-11-28 19:54:49 +0000308 if (isEntry && BB != &BB->getParent()->getEntryBlock())
309 BB->moveBefore(&BB->getParent()->getEntryBlock());
310
David Greene68d67fd2010-01-05 01:27:11 +0000311 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000312 return;
313 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000314 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000315
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000316 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
317 // to handle the new incoming edges it is about to have.
318 PHINode *PN;
319 for (BasicBlock::iterator BBI = DestBB->begin();
320 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
321 // Remove the incoming value for BB, and remember it.
322 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000323
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000324 // Two options: either the InVal is a phi node defined in BB or it is some
325 // value that dominates BB.
326 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
327 if (InValPhi && InValPhi->getParent() == BB) {
328 // Add all of the input values of the input PHI as inputs of this phi.
329 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
330 PN->addIncoming(InValPhi->getIncomingValue(i),
331 InValPhi->getIncomingBlock(i));
332 } else {
333 // Otherwise, add one instance of the dominating value for each edge that
334 // we will be adding.
335 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
336 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
337 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
338 } else {
339 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
340 PN->addIncoming(InVal, *PI);
341 }
342 }
343 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 // The PHIs are now updated, change everything that refers to BB to use
346 // DestBB and remove BB.
347 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000348 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000349 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
350 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
351 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
352 DT->changeImmediateDominator(DestBB, NewIDom);
353 DT->eraseNode(BB);
354 }
Evan Cheng04149f72009-12-17 09:39:49 +0000355 if (PFI) {
356 PFI->replaceAllUses(BB, DestBB);
357 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000358 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000359 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000360 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000361
David Greene68d67fd2010-01-05 01:27:11 +0000362 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000363}
364
Chris Lattnerdd77df32007-04-13 20:30:56 +0000365/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000366/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
367/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000368/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000369///
370/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000371///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000372static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000374 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
375 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000376
Chris Lattnerdd77df32007-04-13 20:30:56 +0000377 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000378 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000379 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000380
Chris Lattnerdd77df32007-04-13 20:30:56 +0000381 // If this is an extension, it will be a zero or sign extension, which
382 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000383 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000384
Chris Lattnerdd77df32007-04-13 20:30:56 +0000385 // If these values will be promoted, find out what they will be promoted
386 // to. This helps us consider truncates on PPC as noop copies when they
387 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000388 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
389 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000390 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000391 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
392 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000393 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000394
Chris Lattnerdd77df32007-04-13 20:30:56 +0000395 // If, after promotion, these are the same types, this is a noop copy.
396 if (SrcVT != DstVT)
397 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000399 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000400
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000401 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000402 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000404 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000405 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000406 UI != E; ) {
407 Use &TheUse = UI.getUse();
408 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000409
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000410 // Figure out which BB this cast is used in. For PHI's this is the
411 // appropriate predecessor block.
412 BasicBlock *UserBB = User->getParent();
413 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000414 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000415 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000416
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000417 // Preincrement use iterator so we don't invalidate it.
418 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000419
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000420 // If this user is in the same block as the cast, don't change the cast.
421 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 // If we have already inserted a cast into this block, use it.
424 CastInst *&InsertedCast = InsertedCasts[UserBB];
425
426 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000427 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428 InsertedCast =
429 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000430 InsertPt);
431 MadeChange = true;
432 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Dale Johannesence0b2372007-06-12 16:50:17 +0000434 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000435 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000436 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000437 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000440 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000441 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000442 MadeChange = true;
443 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000445 return MadeChange;
446}
447
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000449/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000450/// a clear win except on targets with multiple condition code registers
451/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000452///
453/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000454static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000455 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Dale Johannesence0b2372007-06-12 16:50:17 +0000457 /// InsertedCmp - Only insert a cmp in each block once.
458 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Dale Johannesence0b2372007-06-12 16:50:17 +0000460 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 UI != E; ) {
463 Use &TheUse = UI.getUse();
464 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Dale Johannesence0b2372007-06-12 16:50:17 +0000466 // Preincrement use iterator so we don't invalidate it.
467 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Dale Johannesence0b2372007-06-12 16:50:17 +0000469 // Don't bother for PHI nodes.
470 if (isa<PHINode>(User))
471 continue;
472
473 // Figure out which BB this cmp is used in.
474 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Dale Johannesence0b2372007-06-12 16:50:17 +0000476 // If this user is in the same block as the cmp, don't change the cmp.
477 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Dale Johannesence0b2372007-06-12 16:50:17 +0000479 // If we have already inserted a cmp into this block, use it.
480 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
481
482 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000483 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000485 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000486 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000487 CI->getOperand(1), "", InsertPt);
488 MadeChange = true;
489 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Dale Johannesence0b2372007-06-12 16:50:17 +0000491 // Replace a use of the cmp with a use of the new cmp.
492 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000493 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000494 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Dale Johannesence0b2372007-06-12 16:50:17 +0000496 // If we removed all uses, nuke the cmp.
497 if (CI->use_empty())
498 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499
Dale Johannesence0b2372007-06-12 16:50:17 +0000500 return MadeChange;
501}
502
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000503namespace {
504class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
505protected:
506 void replaceCall(Value *With) {
507 CI->replaceAllUsesWith(With);
508 CI->eraseFromParent();
509 }
510 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000511 if (ConstantInt *SizeCI =
512 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
513 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000514 return false;
515 }
516};
517} // end anonymous namespace
518
Eric Christopher040056f2010-03-11 02:41:03 +0000519bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000520 BasicBlock *BB = CI->getParent();
521
522 // Lower inline assembly if we can.
523 // If we found an inline asm expession, and if the target knows how to
524 // lower it to normal LLVM code, do so now.
525 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
526 if (TLI->ExpandInlineAsm(CI)) {
527 // Avoid invalidating the iterator.
528 CurInstIterator = BB->begin();
529 // Avoid processing instructions out of order, which could cause
530 // reuse before a value is defined.
531 SunkAddrs.clear();
532 return true;
533 }
534 // Sink address computing for memory operands into the block.
535 if (OptimizeInlineAsmInst(CI))
536 return true;
537 }
538
Eric Christopher040056f2010-03-11 02:41:03 +0000539 // Lower all uses of llvm.objectsize.*
540 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
541 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000542 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000543 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000544 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000545
546 // Substituting this can cause recursive simplifications, which can
547 // invalidate our iterator. Use a WeakVH to hold onto it in case this
548 // happens.
549 WeakVH IterHandle(CurInstIterator);
550
Cameron Zwarich680c9622011-03-24 04:52:04 +0000551 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
Chad Rosier618c1db2011-12-01 03:08:23 +0000552 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000553
554 // If the iterator instruction was recursively deleted, start over at the
555 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000556 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000557 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000558 SunkAddrs.clear();
559 }
Eric Christopher040056f2010-03-11 02:41:03 +0000560 return true;
561 }
562
563 // From here on out we're working with named functions.
564 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000565
Eric Christopher040056f2010-03-11 02:41:03 +0000566 // We'll need TargetData from here on out.
567 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
568 if (!TD) return false;
569
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000570 // Lower all default uses of _chk calls. This is very similar
571 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000572 // that have the default "don't know" as the objectsize. Anything else
573 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000574 CodeGenPrepareFortifiedLibCalls Simplifier;
575 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000576}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000577
Evan Cheng485fafc2011-03-21 01:19:09 +0000578/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
579/// instructions to the predecessor to enable tail call optimizations. The
580/// case it is currently looking for is:
581/// bb0:
582/// %tmp0 = tail call i32 @f0()
583/// br label %return
584/// bb1:
585/// %tmp1 = tail call i32 @f1()
586/// br label %return
587/// bb2:
588/// %tmp2 = tail call i32 @f2()
589/// br label %return
590/// return:
591/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
592/// ret i32 %retval
593///
594/// =>
595///
596/// bb0:
597/// %tmp0 = tail call i32 @f0()
598/// ret i32 %tmp0
599/// bb1:
600/// %tmp1 = tail call i32 @f1()
601/// ret i32 %tmp1
602/// bb2:
603/// %tmp2 = tail call i32 @f2()
604/// ret i32 %tmp2
605///
606bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000607 if (!TLI)
608 return false;
609
Evan Cheng485fafc2011-03-21 01:19:09 +0000610 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000611 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
612 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000613 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000614
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000615 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000616 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000617 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000618
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000619 // It's not safe to eliminate the sign / zero extension of the return value.
620 // See llvm::isInTailCallPosition().
621 const Function *F = BB->getParent();
622 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
623 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
624 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000625
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000626 // Make sure there are no instructions between the PHI and return, or that the
627 // return is the first instruction in the block.
628 if (PN) {
629 BasicBlock::iterator BI = BB->begin();
630 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
631 if (&*BI != RI)
632 return false;
633 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000634 BasicBlock::iterator BI = BB->begin();
635 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
636 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000637 return false;
638 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000639
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000640 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
641 /// call.
642 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000643 if (PN) {
644 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
645 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
646 // Make sure the phi value is indeed produced by the tail call.
647 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
648 TLI->mayBeEmittedAsTailCall(CI))
649 TailCalls.push_back(CI);
650 }
651 } else {
652 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
653 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
654 if (!VisitedBBs.insert(*PI))
655 continue;
656
657 BasicBlock::InstListType &InstList = (*PI)->getInstList();
658 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
659 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000660 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
661 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000662 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000663
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000664 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000665 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000666 TailCalls.push_back(CI);
667 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000668 }
669
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000670 bool Changed = false;
671 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
672 CallInst *CI = TailCalls[i];
673 CallSite CS(CI);
674
675 // Conservatively require the attributes of the call to match those of the
676 // return. Ignore noalias because it doesn't affect the call sequence.
677 unsigned CalleeRetAttr = CS.getAttributes().getRetAttributes();
678 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
679 continue;
680
681 // Make sure the call instruction is followed by an unconditional branch to
682 // the return block.
683 BasicBlock *CallBB = CI->getParent();
684 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
685 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
686 continue;
687
688 // Duplicate the return into CallBB.
689 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000690 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000691 ++NumRetsDup;
692 }
693
694 // If we eliminated all predecessors of the block, delete the block now.
695 if (Changed && pred_begin(BB) == pred_end(BB))
696 BB->eraseFromParent();
697
698 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000699}
700
Chris Lattner88a5c832008-11-25 07:09:13 +0000701//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000702// Memory Optimization
703//===----------------------------------------------------------------------===//
704
Chris Lattnerdd77df32007-04-13 20:30:56 +0000705/// IsNonLocalValue - Return true if the specified values are defined in a
706/// different basic block than BB.
707static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
708 if (Instruction *I = dyn_cast<Instruction>(V))
709 return I->getParent() != BB;
710 return false;
711}
712
Bob Wilson4a8ee232009-12-03 21:47:07 +0000713/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000714/// addressing modes that can do significant amounts of computation. As such,
715/// instruction selection will try to get the load or store to do as much
716/// computation as possible for the program. The problem is that isel can only
717/// see within a single block. As such, we sink as much legal addressing mode
718/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000719///
720/// This method is used to optimize both load/store and inline asms with memory
721/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000722bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000723 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000724 Value *Repl = Addr;
725
Owen Andersond2f41742010-11-19 22:15:03 +0000726 // Try to collapse single-value PHI nodes. This is necessary to undo
727 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000728 SmallVector<Value*, 8> worklist;
729 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000730 worklist.push_back(Addr);
731
732 // Use a worklist to iteratively look through PHI nodes, and ensure that
733 // the addressing mode obtained from the non-PHI roots of the graph
734 // are equivalent.
735 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000736 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000737 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000738 SmallVector<Instruction*, 16> AddrModeInsts;
739 ExtAddrMode AddrMode;
740 while (!worklist.empty()) {
741 Value *V = worklist.back();
742 worklist.pop_back();
743
744 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000745 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000746 Consensus = 0;
747 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000748 }
749
Owen Anderson35bf4d62010-11-27 08:15:55 +0000750 // For a PHI node, push all of its incoming values.
751 if (PHINode *P = dyn_cast<PHINode>(V)) {
752 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
753 worklist.push_back(P->getIncomingValue(i));
754 continue;
755 }
756
757 // For non-PHIs, determine the addressing mode being computed.
758 SmallVector<Instruction*, 16> NewAddrModeInsts;
759 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000760 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000761 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000762
763 // This check is broken into two cases with very similar code to avoid using
764 // getNumUses() as much as possible. Some values have a lot of uses, so
765 // calling getNumUses() unconditionally caused a significant compile-time
766 // regression.
767 if (!Consensus) {
768 Consensus = V;
769 AddrMode = NewAddrMode;
770 AddrModeInsts = NewAddrModeInsts;
771 continue;
772 } else if (NewAddrMode == AddrMode) {
773 if (!IsNumUsesConsensusValid) {
774 NumUsesConsensus = Consensus->getNumUses();
775 IsNumUsesConsensusValid = true;
776 }
777
778 // Ensure that the obtained addressing mode is equivalent to that obtained
779 // for all other roots of the PHI traversal. Also, when choosing one
780 // such root as representative, select the one with the most uses in order
781 // to keep the cost modeling heuristics in AddressingModeMatcher
782 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000783 unsigned NumUses = V->getNumUses();
784 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000785 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000786 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000787 AddrModeInsts = NewAddrModeInsts;
788 }
789 continue;
790 }
791
792 Consensus = 0;
793 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000794 }
795
Owen Anderson35bf4d62010-11-27 08:15:55 +0000796 // If the addressing mode couldn't be determined, or if multiple different
797 // ones were determined, bail out now.
798 if (!Consensus) return false;
799
Chris Lattnerdd77df32007-04-13 20:30:56 +0000800 // Check to see if any of the instructions supersumed by this addr mode are
801 // non-local to I's BB.
802 bool AnyNonLocal = false;
803 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000804 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000805 AnyNonLocal = true;
806 break;
807 }
808 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000809
Chris Lattnerdd77df32007-04-13 20:30:56 +0000810 // If all the instructions matched are already in this BB, don't do anything.
811 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000812 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000813 return false;
814 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000815
Chris Lattnerdd77df32007-04-13 20:30:56 +0000816 // Insert this computation right after this user. Since our caller is
817 // scanning from the top of the BB to the bottom, reuse of the expr are
818 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000819 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000820
Chris Lattnerdd77df32007-04-13 20:30:56 +0000821 // Now that we determined the addressing expression we want to use and know
822 // that we have to sink it into this block. Check to see if we have already
823 // done this for some other load/store instr in this block. If so, reuse the
824 // computation.
825 Value *&SunkAddr = SunkAddrs[Addr];
826 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000827 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000828 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000829 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000830 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000831 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000832 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000833 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000834 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000835 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000836
Chris Lattnerdd77df32007-04-13 20:30:56 +0000837 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000838
839 // Start with the base register. Do this first so that subsequent address
840 // matching finds it last, which will prevent it from trying to match it
841 // as the scaled value in case it happens to be a mul. That would be
842 // problematic if we've sunk a different mul for the scale, because then
843 // we'd end up sinking both muls.
844 if (AddrMode.BaseReg) {
845 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000846 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000847 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000848 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000849 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000850 Result = V;
851 }
852
853 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000854 if (AddrMode.Scale) {
855 Value *V = AddrMode.ScaledReg;
856 if (V->getType() == IntPtrTy) {
857 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000858 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000859 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000860 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
861 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000862 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000863 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000864 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 }
866 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000867 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
868 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000869 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000870 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000871 else
872 Result = V;
873 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000874
Chris Lattnerdd77df32007-04-13 20:30:56 +0000875 // Add in the BaseGV if present.
876 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000877 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000878 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000879 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000880 else
881 Result = V;
882 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000883
Chris Lattnerdd77df32007-04-13 20:30:56 +0000884 // Add in the Base Offset if present.
885 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000886 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000887 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000888 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000889 else
890 Result = V;
891 }
892
893 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000894 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000895 else
Devang Patel2048c372011-09-06 18:49:53 +0000896 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000897 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000898
Owen Andersond2f41742010-11-19 22:15:03 +0000899 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000900
Chris Lattner0403b472011-04-09 07:05:44 +0000901 // If we have no uses, recursively delete the value and all dead instructions
902 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000903 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000904 // This can cause recursive deletion, which can invalidate our iterator.
905 // Use a WeakVH to hold onto it in case this happens.
906 WeakVH IterHandle(CurInstIterator);
907 BasicBlock *BB = CurInstIterator->getParent();
908
Owen Andersond2f41742010-11-19 22:15:03 +0000909 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000910
911 if (IterHandle != CurInstIterator) {
912 // If the iterator instruction was recursively deleted, start over at the
913 // start of the block.
914 CurInstIterator = BB->begin();
915 SunkAddrs.clear();
916 } else {
917 // This address is now available for reassignment, so erase the table
918 // entry; we don't want to match some completely different instruction.
919 SunkAddrs[Addr] = 0;
920 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000921 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000922 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 return true;
924}
925
Evan Cheng9bf12b52008-02-26 02:42:37 +0000926/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000927/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000928/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000929bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000930 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000931
Chris Lattner75796092011-01-15 07:14:54 +0000932 TargetLowering::AsmOperandInfoVector
933 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000934 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000935 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
936 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
937
Evan Cheng9bf12b52008-02-26 02:42:37 +0000938 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000939 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000940
Eli Friedman9ec80952008-02-26 18:37:49 +0000941 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
942 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000943 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000944 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000945 } else if (OpInfo.Type == InlineAsm::isInput)
946 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000947 }
948
949 return MadeChange;
950}
951
Dan Gohmanb00f2362009-10-16 20:59:35 +0000952/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
953/// basic block as the load, unless conditions are unfavorable. This allows
954/// SelectionDAG to fold the extend into the load.
955///
956bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
957 // Look for a load being extended.
958 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
959 if (!LI) return false;
960
961 // If they're already in the same block, there's nothing to do.
962 if (LI->getParent() == I->getParent())
963 return false;
964
965 // If the load has other users and the truncate is not free, this probably
966 // isn't worthwhile.
967 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000968 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
969 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000970 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000971 return false;
972
973 // Check whether the target supports casts folded into loads.
974 unsigned LType;
975 if (isa<ZExtInst>(I))
976 LType = ISD::ZEXTLOAD;
977 else {
978 assert(isa<SExtInst>(I) && "Unexpected ext type!");
979 LType = ISD::SEXTLOAD;
980 }
981 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
982 return false;
983
984 // Move the extend into the same block as the load, so that SelectionDAG
985 // can fold it.
986 I->removeFromParent();
987 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000988 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000989 return true;
990}
991
Evan Chengbdcb7262007-12-05 23:58:20 +0000992bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
993 BasicBlock *DefBB = I->getParent();
994
Bob Wilson9120f5c2010-09-21 21:44:14 +0000995 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000996 // other uses of the source with result of extension.
997 Value *Src = I->getOperand(0);
998 if (Src->hasOneUse())
999 return false;
1000
Evan Cheng696e5c02007-12-13 07:50:36 +00001001 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001002 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001003 return false;
1004
Evan Cheng772de512007-12-12 00:51:06 +00001005 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001006 // this block.
1007 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001008 return false;
1009
Evan Chengbdcb7262007-12-05 23:58:20 +00001010 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001011 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001012 UI != E; ++UI) {
1013 Instruction *User = cast<Instruction>(*UI);
1014
1015 // Figure out which BB this ext is used in.
1016 BasicBlock *UserBB = User->getParent();
1017 if (UserBB == DefBB) continue;
1018 DefIsLiveOut = true;
1019 break;
1020 }
1021 if (!DefIsLiveOut)
1022 return false;
1023
Evan Cheng765dff22007-12-12 02:53:41 +00001024 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001025 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001026 UI != E; ++UI) {
1027 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001028 BasicBlock *UserBB = User->getParent();
1029 if (UserBB == DefBB) continue;
1030 // Be conservative. We don't want this xform to end up introducing
1031 // reloads just before load / store instructions.
1032 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001033 return false;
1034 }
1035
Evan Chengbdcb7262007-12-05 23:58:20 +00001036 // InsertedTruncs - Only insert one trunc in each block once.
1037 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1038
1039 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001040 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001041 UI != E; ++UI) {
1042 Use &TheUse = UI.getUse();
1043 Instruction *User = cast<Instruction>(*UI);
1044
1045 // Figure out which BB this ext is used in.
1046 BasicBlock *UserBB = User->getParent();
1047 if (UserBB == DefBB) continue;
1048
1049 // Both src and def are live in this block. Rewrite the use.
1050 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1051
1052 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001053 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001054 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1055 }
1056
1057 // Replace a use of the {s|z}ext source with a use of the result.
1058 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001059 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001060 MadeChange = true;
1061 }
1062
1063 return MadeChange;
1064}
1065
Cameron Zwarichc0611012011-01-06 02:37:26 +00001066bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001067 if (PHINode *P = dyn_cast<PHINode>(I)) {
1068 // It is possible for very late stage optimizations (such as SimplifyCFG)
1069 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1070 // trivial PHI, go ahead and zap it here.
1071 if (Value *V = SimplifyInstruction(P)) {
1072 P->replaceAllUsesWith(V);
1073 P->eraseFromParent();
1074 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001075 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001076 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001077 return false;
1078 }
1079
1080 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001081 // If the source of the cast is a constant, then this should have
1082 // already been constant folded. The only reason NOT to constant fold
1083 // it is if something (e.g. LSR) was careful to place the constant
1084 // evaluation in a block other than then one that uses it (e.g. to hoist
1085 // the address of globals out of a loop). If this is the case, we don't
1086 // want to forward-subst the cast.
1087 if (isa<Constant>(CI->getOperand(0)))
1088 return false;
1089
Chris Lattner1a8943a2011-01-15 07:29:01 +00001090 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1091 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001092
Chris Lattner1a8943a2011-01-15 07:29:01 +00001093 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1094 bool MadeChange = MoveExtToFormExtLoad(I);
1095 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001096 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001097 return false;
1098 }
1099
1100 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1101 return OptimizeCmpExpression(CI);
1102
1103 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001104 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001105 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1106 return false;
1107 }
1108
1109 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001110 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001111 return OptimizeMemoryInst(I, SI->getOperand(1),
1112 SI->getOperand(0)->getType());
1113 return false;
1114 }
1115
1116 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001117 if (GEPI->hasAllZeroIndices()) {
1118 /// The GEP operand must be a pointer, so must its result -> BitCast
1119 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1120 GEPI->getName(), GEPI);
1121 GEPI->replaceAllUsesWith(NC);
1122 GEPI->eraseFromParent();
1123 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001124 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001125 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001126 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001127 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001128 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001129
1130 if (CallInst *CI = dyn_cast<CallInst>(I))
1131 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001132
Evan Cheng485fafc2011-03-21 01:19:09 +00001133 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1134 return DupRetToEnableTailCallOpts(RI);
1135
Chris Lattner1a8943a2011-01-15 07:29:01 +00001136 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001137}
1138
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001139// In this pass we look for GEP and cast instructions that are used
1140// across basic blocks and rewrite them to improve basic-block-at-a-time
1141// selection.
1142bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001143 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001144 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001145
Chris Lattner75796092011-01-15 07:14:54 +00001146 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001147 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1148 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001149
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001150 return MadeChange;
1151}
Devang Patelf56ea612011-08-18 00:50:51 +00001152
1153// llvm.dbg.value is far away from the value then iSel may not be able
1154// handle it properly. iSel will drop llvm.dbg.value if it can not
1155// find a node corresponding to the value.
1156bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1157 bool MadeChange = false;
1158 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1159 Instruction *PrevNonDbgInst = NULL;
1160 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1161 Instruction *Insn = BI; ++BI;
1162 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1163 if (!DVI) {
1164 PrevNonDbgInst = Insn;
1165 continue;
1166 }
1167
1168 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1169 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1170 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1171 DVI->removeFromParent();
1172 if (isa<PHINode>(VI))
1173 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1174 else
1175 DVI->insertAfter(VI);
1176 MadeChange = true;
1177 ++NumDbgValueMoved;
1178 }
1179 }
1180 }
1181 return MadeChange;
1182}