blob: f8f18b217355efb9c026387e24fab00cd6ecb7e6 [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"
29#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000030#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000032#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000035#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000036#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000037#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000038#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000039#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000040#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000041#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000042#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000043#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000044#include "llvm/Support/IRBuilder.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000045#include "llvm/Support/ValueHandle.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000047using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048
Cameron Zwarich31ff1332011-01-05 17:27:27 +000049STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000050STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53 "sunken Cmps");
54STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55 "of sunken Casts");
56STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000058STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000061STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000062
Cameron Zwarich899eaa32011-03-11 21:52:04 +000063static cl::opt<bool> DisableBranchOpts(
64 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
65 cl::desc("Disable branch optimizations in CodeGenPrepare"));
66
Eric Christopher692bf6b2008-09-24 05:32:41 +000067namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000068 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000069 /// TLI - Keep a pointer of a TargetLowering to consult for determining
70 /// transformation profitability.
71 const TargetLowering *TLI;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000072 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000073 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000074
75 /// CurInstIterator - As we scan instructions optimizing them, this is the
76 /// next instruction to optimize. Xforms that can invalidate this should
77 /// update it.
78 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000079
Evan Cheng485fafc2011-03-21 01:19:09 +000080 /// Keeps track of non-local addresses that have been sunk into a block.
81 /// This allows us to avoid inserting duplicate code for blocks with
82 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000083 DenseMap<Value*, Value*> SunkAddrs;
84
Devang Patel52e37df2011-03-24 15:35:25 +000085 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000086 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000087 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000088
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000089 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000090 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000091 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000092 : FunctionPass(ID), TLI(tli) {
93 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
94 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000095 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000096
Andreas Neustifterad809812009-09-16 09:26:52 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000098 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000099 AU.addPreserved<ProfileInfo>();
100 }
101
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000102 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000103 bool EliminateMostlyEmptyBlocks(Function &F);
104 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
105 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000106 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000107 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000108 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000109 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000110 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000111 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000112 bool OptimizeExtUses(Instruction *I);
Evan Cheng485fafc2011-03-21 01:19:09 +0000113 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000114 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 };
116}
Devang Patel794fd752007-05-01 21:15:47 +0000117
Devang Patel19974732007-05-03 01:11:54 +0000118char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000119INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000120 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000121
122FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
123 return new CodeGenPrepare(TLI);
124}
125
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000126bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000127 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000128
Devang Patel52e37df2011-03-24 15:35:25 +0000129 ModifiedDT = false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000130 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000131 PFI = getAnalysisIfAvailable<ProfileInfo>();
Evan Cheng485fafc2011-03-21 01:19:09 +0000132
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000133 // First pass, eliminate blocks that contain only PHI nodes and an
134 // unconditional branch.
135 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000136
Devang Patelf56ea612011-08-18 00:50:51 +0000137 // llvm.dbg.value is far away from the value then iSel may not be able
138 // handle it properly. iSel will drop llvm.dbg.value if it can not
139 // find a node corresponding to the value.
140 EverMadeChange |= PlaceDbgValues(F);
141
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000143 while (MadeChange) {
144 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000145 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
146 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000148 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000149 EverMadeChange |= MadeChange;
150 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000151
152 SunkAddrs.clear();
153
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000154 if (!DisableBranchOpts) {
155 MadeChange = false;
156 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Frits van Bommel5649ba72011-05-22 16:24:18 +0000157 MadeChange |= ConstantFoldTerminator(BB, true);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000158
Evan Cheng485fafc2011-03-21 01:19:09 +0000159 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000160 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000161 EverMadeChange |= MadeChange;
162 }
163
Devang Patel52e37df2011-03-24 15:35:25 +0000164 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000165 DT->DT->recalculate(F);
166
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000167 return EverMadeChange;
168}
169
Dale Johannesen2d697242009-03-27 01:13:37 +0000170/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
171/// debug info directives, and an unconditional branch. Passes before isel
172/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
173/// isel. Start by eliminating these blocks so we can split them the way we
174/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000175bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
176 bool MadeChange = false;
177 // Note that this intentionally skips the entry block.
178 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
179 BasicBlock *BB = I++;
180
181 // If this block doesn't end with an uncond branch, ignore it.
182 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
183 if (!BI || !BI->isUnconditional())
184 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000185
Dale Johannesen2d697242009-03-27 01:13:37 +0000186 // If the instruction before the branch (skipping debug info) isn't a phi
187 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000188 BasicBlock::iterator BBI = BI;
189 if (BBI != BB->begin()) {
190 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000191 while (isa<DbgInfoIntrinsic>(BBI)) {
192 if (BBI == BB->begin())
193 break;
194 --BBI;
195 }
196 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
197 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000198 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000199
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000200 // Do not break infinite loops.
201 BasicBlock *DestBB = BI->getSuccessor(0);
202 if (DestBB == BB)
203 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000204
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 if (!CanMergeBlocks(BB, DestBB))
206 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000207
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000208 EliminateMostlyEmptyBlock(BB);
209 MadeChange = true;
210 }
211 return MadeChange;
212}
213
214/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
215/// single uncond branch between them, and BB contains no other non-phi
216/// instructions.
217bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
218 const BasicBlock *DestBB) const {
219 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
220 // the successor. If there are more complex condition (e.g. preheaders),
221 // don't mess around with them.
222 BasicBlock::const_iterator BBI = BB->begin();
223 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000224 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000225 UI != E; ++UI) {
226 const Instruction *User = cast<Instruction>(*UI);
227 if (User->getParent() != DestBB || !isa<PHINode>(User))
228 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000229 // If User is inside DestBB block and it is a PHINode then check
230 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000231 // a complex condition (e.g. preheaders) we want to avoid here.
232 if (User->getParent() == DestBB) {
233 if (const PHINode *UPN = dyn_cast<PHINode>(User))
234 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
235 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
236 if (Insn && Insn->getParent() == BB &&
237 Insn->getParent() != UPN->getIncomingBlock(I))
238 return false;
239 }
240 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 }
242 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000243
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000244 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
245 // and DestBB may have conflicting incoming values for the block. If so, we
246 // can't merge the block.
247 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
248 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000249
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000250 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000251 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000252 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
253 // It is faster to get preds from a PHI than with pred_iterator.
254 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
255 BBPreds.insert(BBPN->getIncomingBlock(i));
256 } else {
257 BBPreds.insert(pred_begin(BB), pred_end(BB));
258 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // Walk the preds of DestBB.
261 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
262 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
263 if (BBPreds.count(Pred)) { // Common predecessor?
264 BBI = DestBB->begin();
265 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
266 const Value *V1 = PN->getIncomingValueForBlock(Pred);
267 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000268
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 // If V2 is a phi node in BB, look up what the mapped value will be.
270 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
271 if (V2PN->getParent() == BB)
272 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000273
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 // If there is a conflict, bail out.
275 if (V1 != V2) return false;
276 }
277 }
278 }
279
280 return true;
281}
282
283
284/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
285/// an unconditional branch in it.
286void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
287 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
288 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000289
David Greene68d67fd2010-01-05 01:27:11 +0000290 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000291
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 // If the destination block has a single pred, then this is a trivial edge,
293 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000294 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000295 if (SinglePred != DestBB) {
296 // Remember if SinglePred was the entry block of the function. If so, we
297 // will need to move BB back to the entry position.
298 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000299 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000300
Chris Lattnerf5102a02008-11-28 19:54:49 +0000301 if (isEntry && BB != &BB->getParent()->getEntryBlock())
302 BB->moveBefore(&BB->getParent()->getEntryBlock());
303
David Greene68d67fd2010-01-05 01:27:11 +0000304 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000305 return;
306 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000308
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000309 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
310 // to handle the new incoming edges it is about to have.
311 PHINode *PN;
312 for (BasicBlock::iterator BBI = DestBB->begin();
313 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
314 // Remove the incoming value for BB, and remember it.
315 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000316
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000317 // Two options: either the InVal is a phi node defined in BB or it is some
318 // value that dominates BB.
319 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
320 if (InValPhi && InValPhi->getParent() == BB) {
321 // Add all of the input values of the input PHI as inputs of this phi.
322 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
323 PN->addIncoming(InValPhi->getIncomingValue(i),
324 InValPhi->getIncomingBlock(i));
325 } else {
326 // Otherwise, add one instance of the dominating value for each edge that
327 // we will be adding.
328 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
329 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
330 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
331 } else {
332 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
333 PN->addIncoming(InVal, *PI);
334 }
335 }
336 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338 // The PHIs are now updated, change everything that refers to BB to use
339 // DestBB and remove BB.
340 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000341 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000342 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
343 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
344 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
345 DT->changeImmediateDominator(DestBB, NewIDom);
346 DT->eraseNode(BB);
347 }
Evan Cheng04149f72009-12-17 09:39:49 +0000348 if (PFI) {
349 PFI->replaceAllUses(BB, DestBB);
350 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000351 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000353 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
David Greene68d67fd2010-01-05 01:27:11 +0000355 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000356}
357
Chris Lattnerdd77df32007-04-13 20:30:56 +0000358/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000359/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
360/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000361/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000362///
363/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000364///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000365static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000366 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000367 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
368 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000369
Chris Lattnerdd77df32007-04-13 20:30:56 +0000370 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000371 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000372 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000373
Chris Lattnerdd77df32007-04-13 20:30:56 +0000374 // If this is an extension, it will be a zero or sign extension, which
375 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000376 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000377
Chris Lattnerdd77df32007-04-13 20:30:56 +0000378 // If these values will be promoted, find out what they will be promoted
379 // to. This helps us consider truncates on PPC as noop copies when they
380 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000381 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
382 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000383 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000384 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
385 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000386 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000387
Chris Lattnerdd77df32007-04-13 20:30:56 +0000388 // If, after promotion, these are the same types, this is a noop copy.
389 if (SrcVT != DstVT)
390 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000392 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000393
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000394 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000395 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000396
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000397 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000398 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000399 UI != E; ) {
400 Use &TheUse = UI.getUse();
401 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 // Figure out which BB this cast is used in. For PHI's this is the
404 // appropriate predecessor block.
405 BasicBlock *UserBB = User->getParent();
406 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000407 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000408 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000409
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000410 // Preincrement use iterator so we don't invalidate it.
411 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000413 // If this user is in the same block as the cast, don't change the cast.
414 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000416 // If we have already inserted a cast into this block, use it.
417 CastInst *&InsertedCast = InsertedCasts[UserBB];
418
419 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000420 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421 InsertedCast =
422 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 InsertPt);
424 MadeChange = true;
425 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Dale Johannesence0b2372007-06-12 16:50:17 +0000427 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000428 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000429 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000430 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000432 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000433 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000434 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000435 MadeChange = true;
436 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000437
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000438 return MadeChange;
439}
440
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000442/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000443/// a clear win except on targets with multiple condition code registers
444/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000445///
446/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000447static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000448 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 /// InsertedCmp - Only insert a cmp in each block once.
451 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000454 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000455 UI != E; ) {
456 Use &TheUse = UI.getUse();
457 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Dale Johannesence0b2372007-06-12 16:50:17 +0000459 // Preincrement use iterator so we don't invalidate it.
460 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 // Don't bother for PHI nodes.
463 if (isa<PHINode>(User))
464 continue;
465
466 // Figure out which BB this cmp is used in.
467 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Dale Johannesence0b2372007-06-12 16:50:17 +0000469 // If this user is in the same block as the cmp, don't change the cmp.
470 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Dale Johannesence0b2372007-06-12 16:50:17 +0000472 // If we have already inserted a cmp into this block, use it.
473 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
474
475 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000476 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000478 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000479 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000480 CI->getOperand(1), "", InsertPt);
481 MadeChange = true;
482 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Dale Johannesence0b2372007-06-12 16:50:17 +0000484 // Replace a use of the cmp with a use of the new cmp.
485 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000486 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000487 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 // If we removed all uses, nuke the cmp.
490 if (CI->use_empty())
491 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Dale Johannesence0b2372007-06-12 16:50:17 +0000493 return MadeChange;
494}
495
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000496namespace {
497class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
498protected:
499 void replaceCall(Value *With) {
500 CI->replaceAllUsesWith(With);
501 CI->eraseFromParent();
502 }
503 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000504 if (ConstantInt *SizeCI =
505 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
506 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000507 return false;
508 }
509};
510} // end anonymous namespace
511
Eric Christopher040056f2010-03-11 02:41:03 +0000512bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000513 BasicBlock *BB = CI->getParent();
514
515 // Lower inline assembly if we can.
516 // If we found an inline asm expession, and if the target knows how to
517 // lower it to normal LLVM code, do so now.
518 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
519 if (TLI->ExpandInlineAsm(CI)) {
520 // Avoid invalidating the iterator.
521 CurInstIterator = BB->begin();
522 // Avoid processing instructions out of order, which could cause
523 // reuse before a value is defined.
524 SunkAddrs.clear();
525 return true;
526 }
527 // Sink address computing for memory operands into the block.
528 if (OptimizeInlineAsmInst(CI))
529 return true;
530 }
531
Eric Christopher040056f2010-03-11 02:41:03 +0000532 // Lower all uses of llvm.objectsize.*
533 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
534 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000535 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000536 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000537 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000538
539 // Substituting this can cause recursive simplifications, which can
540 // invalidate our iterator. Use a WeakVH to hold onto it in case this
541 // happens.
542 WeakVH IterHandle(CurInstIterator);
543
Cameron Zwarich680c9622011-03-24 04:52:04 +0000544 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
Devang Patel52e37df2011-03-24 15:35:25 +0000545 ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000546
547 // If the iterator instruction was recursively deleted, start over at the
548 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000549 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000550 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000551 SunkAddrs.clear();
552 }
Eric Christopher040056f2010-03-11 02:41:03 +0000553 return true;
554 }
555
556 // From here on out we're working with named functions.
557 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000558
Eric Christopher040056f2010-03-11 02:41:03 +0000559 // We'll need TargetData from here on out.
560 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
561 if (!TD) return false;
562
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000563 // Lower all default uses of _chk calls. This is very similar
564 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000565 // that have the default "don't know" as the objectsize. Anything else
566 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000567 CodeGenPrepareFortifiedLibCalls Simplifier;
568 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000569}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000570
Evan Cheng485fafc2011-03-21 01:19:09 +0000571/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
572/// instructions to the predecessor to enable tail call optimizations. The
573/// case it is currently looking for is:
574/// bb0:
575/// %tmp0 = tail call i32 @f0()
576/// br label %return
577/// bb1:
578/// %tmp1 = tail call i32 @f1()
579/// br label %return
580/// bb2:
581/// %tmp2 = tail call i32 @f2()
582/// br label %return
583/// return:
584/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
585/// ret i32 %retval
586///
587/// =>
588///
589/// bb0:
590/// %tmp0 = tail call i32 @f0()
591/// ret i32 %tmp0
592/// bb1:
593/// %tmp1 = tail call i32 @f1()
594/// ret i32 %tmp1
595/// bb2:
596/// %tmp2 = tail call i32 @f2()
597/// ret i32 %tmp2
598///
599bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000600 if (!TLI)
601 return false;
602
Evan Cheng485fafc2011-03-21 01:19:09 +0000603 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000604 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
605 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000606 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000607
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000608 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000609 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000610 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000611
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000612 // It's not safe to eliminate the sign / zero extension of the return value.
613 // See llvm::isInTailCallPosition().
614 const Function *F = BB->getParent();
615 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
616 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
617 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000618
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000619 // Make sure there are no instructions between the PHI and return, or that the
620 // return is the first instruction in the block.
621 if (PN) {
622 BasicBlock::iterator BI = BB->begin();
623 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
624 if (&*BI != RI)
625 return false;
626 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000627 BasicBlock::iterator BI = BB->begin();
628 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
629 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000630 return false;
631 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000632
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000633 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
634 /// call.
635 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000636 if (PN) {
637 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
638 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
639 // Make sure the phi value is indeed produced by the tail call.
640 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
641 TLI->mayBeEmittedAsTailCall(CI))
642 TailCalls.push_back(CI);
643 }
644 } else {
645 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
646 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
647 if (!VisitedBBs.insert(*PI))
648 continue;
649
650 BasicBlock::InstListType &InstList = (*PI)->getInstList();
651 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
652 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000653 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
654 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000655 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000656
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000657 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000658 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000659 TailCalls.push_back(CI);
660 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000661 }
662
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000663 bool Changed = false;
664 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
665 CallInst *CI = TailCalls[i];
666 CallSite CS(CI);
667
668 // Conservatively require the attributes of the call to match those of the
669 // return. Ignore noalias because it doesn't affect the call sequence.
670 unsigned CalleeRetAttr = CS.getAttributes().getRetAttributes();
671 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
672 continue;
673
674 // Make sure the call instruction is followed by an unconditional branch to
675 // the return block.
676 BasicBlock *CallBB = CI->getParent();
677 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
678 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
679 continue;
680
681 // Duplicate the return into CallBB.
682 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000683 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000684 ++NumRetsDup;
685 }
686
687 // If we eliminated all predecessors of the block, delete the block now.
688 if (Changed && pred_begin(BB) == pred_end(BB))
689 BB->eraseFromParent();
690
691 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000692}
693
Chris Lattner88a5c832008-11-25 07:09:13 +0000694//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000695// Memory Optimization
696//===----------------------------------------------------------------------===//
697
Chris Lattnerdd77df32007-04-13 20:30:56 +0000698/// IsNonLocalValue - Return true if the specified values are defined in a
699/// different basic block than BB.
700static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
701 if (Instruction *I = dyn_cast<Instruction>(V))
702 return I->getParent() != BB;
703 return false;
704}
705
Bob Wilson4a8ee232009-12-03 21:47:07 +0000706/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707/// addressing modes that can do significant amounts of computation. As such,
708/// instruction selection will try to get the load or store to do as much
709/// computation as possible for the program. The problem is that isel can only
710/// see within a single block. As such, we sink as much legal addressing mode
711/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000712///
713/// This method is used to optimize both load/store and inline asms with memory
714/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000715bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000716 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000717 Value *Repl = Addr;
718
Owen Andersond2f41742010-11-19 22:15:03 +0000719 // Try to collapse single-value PHI nodes. This is necessary to undo
720 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000721 SmallVector<Value*, 8> worklist;
722 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000723 worklist.push_back(Addr);
724
725 // Use a worklist to iteratively look through PHI nodes, and ensure that
726 // the addressing mode obtained from the non-PHI roots of the graph
727 // are equivalent.
728 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000729 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000730 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000731 SmallVector<Instruction*, 16> AddrModeInsts;
732 ExtAddrMode AddrMode;
733 while (!worklist.empty()) {
734 Value *V = worklist.back();
735 worklist.pop_back();
736
737 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000738 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000739 Consensus = 0;
740 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000741 }
742
Owen Anderson35bf4d62010-11-27 08:15:55 +0000743 // For a PHI node, push all of its incoming values.
744 if (PHINode *P = dyn_cast<PHINode>(V)) {
745 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
746 worklist.push_back(P->getIncomingValue(i));
747 continue;
748 }
749
750 // For non-PHIs, determine the addressing mode being computed.
751 SmallVector<Instruction*, 16> NewAddrModeInsts;
752 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000753 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000754 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000755
756 // This check is broken into two cases with very similar code to avoid using
757 // getNumUses() as much as possible. Some values have a lot of uses, so
758 // calling getNumUses() unconditionally caused a significant compile-time
759 // regression.
760 if (!Consensus) {
761 Consensus = V;
762 AddrMode = NewAddrMode;
763 AddrModeInsts = NewAddrModeInsts;
764 continue;
765 } else if (NewAddrMode == AddrMode) {
766 if (!IsNumUsesConsensusValid) {
767 NumUsesConsensus = Consensus->getNumUses();
768 IsNumUsesConsensusValid = true;
769 }
770
771 // Ensure that the obtained addressing mode is equivalent to that obtained
772 // for all other roots of the PHI traversal. Also, when choosing one
773 // such root as representative, select the one with the most uses in order
774 // to keep the cost modeling heuristics in AddressingModeMatcher
775 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000776 unsigned NumUses = V->getNumUses();
777 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000778 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000779 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000780 AddrModeInsts = NewAddrModeInsts;
781 }
782 continue;
783 }
784
785 Consensus = 0;
786 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000787 }
788
Owen Anderson35bf4d62010-11-27 08:15:55 +0000789 // If the addressing mode couldn't be determined, or if multiple different
790 // ones were determined, bail out now.
791 if (!Consensus) return false;
792
Chris Lattnerdd77df32007-04-13 20:30:56 +0000793 // Check to see if any of the instructions supersumed by this addr mode are
794 // non-local to I's BB.
795 bool AnyNonLocal = false;
796 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000797 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000798 AnyNonLocal = true;
799 break;
800 }
801 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000802
Chris Lattnerdd77df32007-04-13 20:30:56 +0000803 // If all the instructions matched are already in this BB, don't do anything.
804 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000805 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000806 return false;
807 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000808
Chris Lattnerdd77df32007-04-13 20:30:56 +0000809 // Insert this computation right after this user. Since our caller is
810 // scanning from the top of the BB to the bottom, reuse of the expr are
811 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000812 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000813
Chris Lattnerdd77df32007-04-13 20:30:56 +0000814 // Now that we determined the addressing expression we want to use and know
815 // that we have to sink it into this block. Check to see if we have already
816 // done this for some other load/store instr in this block. If so, reuse the
817 // computation.
818 Value *&SunkAddr = SunkAddrs[Addr];
819 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000820 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000821 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000822 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000823 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000824 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000825 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000826 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000827 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000828 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000829
Chris Lattnerdd77df32007-04-13 20:30:56 +0000830 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000831
832 // Start with the base register. Do this first so that subsequent address
833 // matching finds it last, which will prevent it from trying to match it
834 // as the scaled value in case it happens to be a mul. That would be
835 // problematic if we've sunk a different mul for the scale, because then
836 // we'd end up sinking both muls.
837 if (AddrMode.BaseReg) {
838 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000839 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000840 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000841 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000842 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000843 Result = V;
844 }
845
846 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000847 if (AddrMode.Scale) {
848 Value *V = AddrMode.ScaledReg;
849 if (V->getType() == IntPtrTy) {
850 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000851 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000852 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000853 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
854 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000855 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000856 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000857 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000858 }
859 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000860 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
861 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000862 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000863 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 else
865 Result = V;
866 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000867
Chris Lattnerdd77df32007-04-13 20:30:56 +0000868 // Add in the BaseGV if present.
869 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000870 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000871 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000872 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000873 else
874 Result = V;
875 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000876
Chris Lattnerdd77df32007-04-13 20:30:56 +0000877 // Add in the Base Offset if present.
878 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000879 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000880 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000881 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000882 else
883 Result = V;
884 }
885
886 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000887 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000888 else
Devang Patel2048c372011-09-06 18:49:53 +0000889 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000890 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000891
Owen Andersond2f41742010-11-19 22:15:03 +0000892 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000893
Chris Lattner0403b472011-04-09 07:05:44 +0000894 // If we have no uses, recursively delete the value and all dead instructions
895 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000896 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000897 // This can cause recursive deletion, which can invalidate our iterator.
898 // Use a WeakVH to hold onto it in case this happens.
899 WeakVH IterHandle(CurInstIterator);
900 BasicBlock *BB = CurInstIterator->getParent();
901
Owen Andersond2f41742010-11-19 22:15:03 +0000902 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000903
904 if (IterHandle != CurInstIterator) {
905 // If the iterator instruction was recursively deleted, start over at the
906 // start of the block.
907 CurInstIterator = BB->begin();
908 SunkAddrs.clear();
909 } else {
910 // This address is now available for reassignment, so erase the table
911 // entry; we don't want to match some completely different instruction.
912 SunkAddrs[Addr] = 0;
913 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000914 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000915 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000916 return true;
917}
918
Evan Cheng9bf12b52008-02-26 02:42:37 +0000919/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000920/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000921/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000922bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000923 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000924
Chris Lattner75796092011-01-15 07:14:54 +0000925 TargetLowering::AsmOperandInfoVector
926 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000927 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000928 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
929 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
930
Evan Cheng9bf12b52008-02-26 02:42:37 +0000931 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000932 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000933
Eli Friedman9ec80952008-02-26 18:37:49 +0000934 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
935 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000936 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000937 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000938 } else if (OpInfo.Type == InlineAsm::isInput)
939 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000940 }
941
942 return MadeChange;
943}
944
Dan Gohmanb00f2362009-10-16 20:59:35 +0000945/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
946/// basic block as the load, unless conditions are unfavorable. This allows
947/// SelectionDAG to fold the extend into the load.
948///
949bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
950 // Look for a load being extended.
951 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
952 if (!LI) return false;
953
954 // If they're already in the same block, there's nothing to do.
955 if (LI->getParent() == I->getParent())
956 return false;
957
958 // If the load has other users and the truncate is not free, this probably
959 // isn't worthwhile.
960 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000961 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
962 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000963 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000964 return false;
965
966 // Check whether the target supports casts folded into loads.
967 unsigned LType;
968 if (isa<ZExtInst>(I))
969 LType = ISD::ZEXTLOAD;
970 else {
971 assert(isa<SExtInst>(I) && "Unexpected ext type!");
972 LType = ISD::SEXTLOAD;
973 }
974 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
975 return false;
976
977 // Move the extend into the same block as the load, so that SelectionDAG
978 // can fold it.
979 I->removeFromParent();
980 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000981 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000982 return true;
983}
984
Evan Chengbdcb7262007-12-05 23:58:20 +0000985bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
986 BasicBlock *DefBB = I->getParent();
987
Bob Wilson9120f5c2010-09-21 21:44:14 +0000988 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000989 // other uses of the source with result of extension.
990 Value *Src = I->getOperand(0);
991 if (Src->hasOneUse())
992 return false;
993
Evan Cheng696e5c02007-12-13 07:50:36 +0000994 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000995 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000996 return false;
997
Evan Cheng772de512007-12-12 00:51:06 +0000998 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000999 // this block.
1000 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001001 return false;
1002
Evan Chengbdcb7262007-12-05 23:58:20 +00001003 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001004 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001005 UI != E; ++UI) {
1006 Instruction *User = cast<Instruction>(*UI);
1007
1008 // Figure out which BB this ext is used in.
1009 BasicBlock *UserBB = User->getParent();
1010 if (UserBB == DefBB) continue;
1011 DefIsLiveOut = true;
1012 break;
1013 }
1014 if (!DefIsLiveOut)
1015 return false;
1016
Evan Cheng765dff22007-12-12 02:53:41 +00001017 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001018 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001019 UI != E; ++UI) {
1020 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001021 BasicBlock *UserBB = User->getParent();
1022 if (UserBB == DefBB) continue;
1023 // Be conservative. We don't want this xform to end up introducing
1024 // reloads just before load / store instructions.
1025 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001026 return false;
1027 }
1028
Evan Chengbdcb7262007-12-05 23:58:20 +00001029 // InsertedTruncs - Only insert one trunc in each block once.
1030 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1031
1032 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001033 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001034 UI != E; ++UI) {
1035 Use &TheUse = UI.getUse();
1036 Instruction *User = cast<Instruction>(*UI);
1037
1038 // Figure out which BB this ext is used in.
1039 BasicBlock *UserBB = User->getParent();
1040 if (UserBB == DefBB) continue;
1041
1042 // Both src and def are live in this block. Rewrite the use.
1043 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1044
1045 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001046 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001047 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1048 }
1049
1050 // Replace a use of the {s|z}ext source with a use of the result.
1051 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001052 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001053 MadeChange = true;
1054 }
1055
1056 return MadeChange;
1057}
1058
Cameron Zwarichc0611012011-01-06 02:37:26 +00001059bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001060 if (PHINode *P = dyn_cast<PHINode>(I)) {
1061 // It is possible for very late stage optimizations (such as SimplifyCFG)
1062 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1063 // trivial PHI, go ahead and zap it here.
1064 if (Value *V = SimplifyInstruction(P)) {
1065 P->replaceAllUsesWith(V);
1066 P->eraseFromParent();
1067 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001068 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001069 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001070 return false;
1071 }
1072
1073 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001074 // If the source of the cast is a constant, then this should have
1075 // already been constant folded. The only reason NOT to constant fold
1076 // it is if something (e.g. LSR) was careful to place the constant
1077 // evaluation in a block other than then one that uses it (e.g. to hoist
1078 // the address of globals out of a loop). If this is the case, we don't
1079 // want to forward-subst the cast.
1080 if (isa<Constant>(CI->getOperand(0)))
1081 return false;
1082
Chris Lattner1a8943a2011-01-15 07:29:01 +00001083 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1084 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001085
Chris Lattner1a8943a2011-01-15 07:29:01 +00001086 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1087 bool MadeChange = MoveExtToFormExtLoad(I);
1088 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001089 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001090 return false;
1091 }
1092
1093 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1094 return OptimizeCmpExpression(CI);
1095
1096 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001097 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001098 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1099 return false;
1100 }
1101
1102 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001103 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001104 return OptimizeMemoryInst(I, SI->getOperand(1),
1105 SI->getOperand(0)->getType());
1106 return false;
1107 }
1108
1109 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001110 if (GEPI->hasAllZeroIndices()) {
1111 /// The GEP operand must be a pointer, so must its result -> BitCast
1112 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1113 GEPI->getName(), GEPI);
1114 GEPI->replaceAllUsesWith(NC);
1115 GEPI->eraseFromParent();
1116 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001117 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001118 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001119 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001120 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001121 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001122
1123 if (CallInst *CI = dyn_cast<CallInst>(I))
1124 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001125
Evan Cheng485fafc2011-03-21 01:19:09 +00001126 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1127 return DupRetToEnableTailCallOpts(RI);
1128
Chris Lattner1a8943a2011-01-15 07:29:01 +00001129 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001130}
1131
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001132// In this pass we look for GEP and cast instructions that are used
1133// across basic blocks and rewrite them to improve basic-block-at-a-time
1134// selection.
1135bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001136 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001137 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001138
Chris Lattner75796092011-01-15 07:14:54 +00001139 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001140 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1141 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001142
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001143 return MadeChange;
1144}
Devang Patelf56ea612011-08-18 00:50:51 +00001145
1146// llvm.dbg.value is far away from the value then iSel may not be able
1147// handle it properly. iSel will drop llvm.dbg.value if it can not
1148// find a node corresponding to the value.
1149bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1150 bool MadeChange = false;
1151 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1152 Instruction *PrevNonDbgInst = NULL;
1153 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1154 Instruction *Insn = BI; ++BI;
1155 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1156 if (!DVI) {
1157 PrevNonDbgInst = Insn;
1158 continue;
1159 }
1160
1161 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1162 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1163 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1164 DVI->removeFromParent();
1165 if (isa<PHINode>(VI))
1166 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1167 else
1168 DVI->insertAfter(VI);
1169 MadeChange = true;
1170 ++NumDbgValueMoved;
1171 }
1172 }
1173 }
1174 return MadeChange;
1175}