blob: fb4e8a4c9d89ccdd0b2bd62be2d91f296e92cb3d [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");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000061
Cameron Zwarich899eaa32011-03-11 21:52:04 +000062static cl::opt<bool> DisableBranchOpts(
63 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
64 cl::desc("Disable branch optimizations in CodeGenPrepare"));
65
Eric Christopher692bf6b2008-09-24 05:32:41 +000066namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000067 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000068 /// TLI - Keep a pointer of a TargetLowering to consult for determining
69 /// transformation profitability.
70 const TargetLowering *TLI;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000071 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000072 ProfileInfo *PFI;
Chris Lattner75796092011-01-15 07:14:54 +000073
74 /// CurInstIterator - As we scan instructions optimizing them, this is the
75 /// next instruction to optimize. Xforms that can invalidate this should
76 /// update it.
77 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000078
Evan Cheng485fafc2011-03-21 01:19:09 +000079 /// Keeps track of non-local addresses that have been sunk into a block.
80 /// This allows us to avoid inserting duplicate code for blocks with
81 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000082 DenseMap<Value*, Value*> SunkAddrs;
83
Devang Patel52e37df2011-03-24 15:35:25 +000084 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000085 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000086 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000087
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000088 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000089 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000090 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000091 : FunctionPass(ID), TLI(tli) {
92 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
93 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000094 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000095
Andreas Neustifterad809812009-09-16 09:26:52 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000097 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000098 AU.addPreserved<ProfileInfo>();
99 }
100
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000102 bool EliminateMostlyEmptyBlocks(Function &F);
103 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
104 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000105 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000106 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000107 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000108 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000109 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000110 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000111 bool OptimizeExtUses(Instruction *I);
Evan Cheng485fafc2011-03-21 01:19:09 +0000112 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000113 };
114}
Devang Patel794fd752007-05-01 21:15:47 +0000115
Devang Patel19974732007-05-03 01:11:54 +0000116char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000117INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000118 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000119
120FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
121 return new CodeGenPrepare(TLI);
122}
123
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000124bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000125 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000126
Devang Patel52e37df2011-03-24 15:35:25 +0000127 ModifiedDT = false;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000128 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000129 PFI = getAnalysisIfAvailable<ProfileInfo>();
Evan Cheng485fafc2011-03-21 01:19:09 +0000130
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000131 // First pass, eliminate blocks that contain only PHI nodes and an
132 // unconditional branch.
133 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000134
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000135 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000136 while (MadeChange) {
137 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000138 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
139 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000140 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000141 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000142 EverMadeChange |= MadeChange;
143 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000144
145 SunkAddrs.clear();
146
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000147 if (!DisableBranchOpts) {
148 MadeChange = false;
149 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Frits van Bommel5649ba72011-05-22 16:24:18 +0000150 MadeChange |= ConstantFoldTerminator(BB, true);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000151
Evan Cheng485fafc2011-03-21 01:19:09 +0000152 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000153 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000154 EverMadeChange |= MadeChange;
155 }
156
Devang Patel52e37df2011-03-24 15:35:25 +0000157 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000158 DT->DT->recalculate(F);
159
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000160 return EverMadeChange;
161}
162
Dale Johannesen2d697242009-03-27 01:13:37 +0000163/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
164/// debug info directives, and an unconditional branch. Passes before isel
165/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
166/// isel. Start by eliminating these blocks so we can split them the way we
167/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000168bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
169 bool MadeChange = false;
170 // Note that this intentionally skips the entry block.
171 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
172 BasicBlock *BB = I++;
173
174 // If this block doesn't end with an uncond branch, ignore it.
175 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
176 if (!BI || !BI->isUnconditional())
177 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000178
Dale Johannesen2d697242009-03-27 01:13:37 +0000179 // If the instruction before the branch (skipping debug info) isn't a phi
180 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000181 BasicBlock::iterator BBI = BI;
182 if (BBI != BB->begin()) {
183 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000184 while (isa<DbgInfoIntrinsic>(BBI)) {
185 if (BBI == BB->begin())
186 break;
187 --BBI;
188 }
189 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
190 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000191 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000192
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000193 // Do not break infinite loops.
194 BasicBlock *DestBB = BI->getSuccessor(0);
195 if (DestBB == BB)
196 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000197
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000198 if (!CanMergeBlocks(BB, DestBB))
199 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000200
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000201 EliminateMostlyEmptyBlock(BB);
202 MadeChange = true;
203 }
204 return MadeChange;
205}
206
207/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
208/// single uncond branch between them, and BB contains no other non-phi
209/// instructions.
210bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
211 const BasicBlock *DestBB) const {
212 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
213 // the successor. If there are more complex condition (e.g. preheaders),
214 // don't mess around with them.
215 BasicBlock::const_iterator BBI = BB->begin();
216 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000217 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000218 UI != E; ++UI) {
219 const Instruction *User = cast<Instruction>(*UI);
220 if (User->getParent() != DestBB || !isa<PHINode>(User))
221 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000222 // If User is inside DestBB block and it is a PHINode then check
223 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000224 // a complex condition (e.g. preheaders) we want to avoid here.
225 if (User->getParent() == DestBB) {
226 if (const PHINode *UPN = dyn_cast<PHINode>(User))
227 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
228 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
229 if (Insn && Insn->getParent() == BB &&
230 Insn->getParent() != UPN->getIncomingBlock(I))
231 return false;
232 }
233 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 }
235 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000236
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
238 // and DestBB may have conflicting incoming values for the block. If so, we
239 // can't merge the block.
240 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
241 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000242
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000243 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000244 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000245 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
246 // It is faster to get preds from a PHI than with pred_iterator.
247 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
248 BBPreds.insert(BBPN->getIncomingBlock(i));
249 } else {
250 BBPreds.insert(pred_begin(BB), pred_end(BB));
251 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000252
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000253 // Walk the preds of DestBB.
254 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
255 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
256 if (BBPreds.count(Pred)) { // Common predecessor?
257 BBI = DestBB->begin();
258 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
259 const Value *V1 = PN->getIncomingValueForBlock(Pred);
260 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000261
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000262 // If V2 is a phi node in BB, look up what the mapped value will be.
263 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
264 if (V2PN->getParent() == BB)
265 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000266
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000267 // If there is a conflict, bail out.
268 if (V1 != V2) return false;
269 }
270 }
271 }
272
273 return true;
274}
275
276
277/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
278/// an unconditional branch in it.
279void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
280 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
281 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000282
David Greene68d67fd2010-01-05 01:27:11 +0000283 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000284
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000285 // If the destination block has a single pred, then this is a trivial edge,
286 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000287 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000288 if (SinglePred != DestBB) {
289 // Remember if SinglePred was the entry block of the function. If so, we
290 // will need to move BB back to the entry position.
291 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000292 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000293
Chris Lattnerf5102a02008-11-28 19:54:49 +0000294 if (isEntry && BB != &BB->getParent()->getEntryBlock())
295 BB->moveBefore(&BB->getParent()->getEntryBlock());
296
David Greene68d67fd2010-01-05 01:27:11 +0000297 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000298 return;
299 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000301
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000302 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
303 // to handle the new incoming edges it is about to have.
304 PHINode *PN;
305 for (BasicBlock::iterator BBI = DestBB->begin();
306 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
307 // Remove the incoming value for BB, and remember it.
308 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000310 // Two options: either the InVal is a phi node defined in BB or it is some
311 // value that dominates BB.
312 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
313 if (InValPhi && InValPhi->getParent() == BB) {
314 // Add all of the input values of the input PHI as inputs of this phi.
315 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
316 PN->addIncoming(InValPhi->getIncomingValue(i),
317 InValPhi->getIncomingBlock(i));
318 } else {
319 // Otherwise, add one instance of the dominating value for each edge that
320 // we will be adding.
321 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
322 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
323 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
324 } else {
325 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
326 PN->addIncoming(InVal, *PI);
327 }
328 }
329 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000330
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000331 // The PHIs are now updated, change everything that refers to BB to use
332 // DestBB and remove BB.
333 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000334 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000335 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
336 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
337 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
338 DT->changeImmediateDominator(DestBB, NewIDom);
339 DT->eraseNode(BB);
340 }
Evan Cheng04149f72009-12-17 09:39:49 +0000341 if (PFI) {
342 PFI->replaceAllUses(BB, DestBB);
343 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000344 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000346 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000347
David Greene68d67fd2010-01-05 01:27:11 +0000348 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000349}
350
Chris Lattnerdd77df32007-04-13 20:30:56 +0000351/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000352/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
353/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000354/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000355///
356/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000357///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000358static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000359 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000360 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
361 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000362
Chris Lattnerdd77df32007-04-13 20:30:56 +0000363 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000364 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000365 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000366
Chris Lattnerdd77df32007-04-13 20:30:56 +0000367 // If this is an extension, it will be a zero or sign extension, which
368 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000369 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000370
Chris Lattnerdd77df32007-04-13 20:30:56 +0000371 // If these values will be promoted, find out what they will be promoted
372 // to. This helps us consider truncates on PPC as noop copies when they
373 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000374 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
375 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000376 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000377 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
378 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000379 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000380
Chris Lattnerdd77df32007-04-13 20:30:56 +0000381 // If, after promotion, these are the same types, this is a noop copy.
382 if (SrcVT != DstVT)
383 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000384
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000385 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000387 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000388 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000390 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000392 UI != E; ) {
393 Use &TheUse = UI.getUse();
394 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000396 // Figure out which BB this cast is used in. For PHI's this is the
397 // appropriate predecessor block.
398 BasicBlock *UserBB = User->getParent();
399 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000400 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000401 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000402
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000403 // Preincrement use iterator so we don't invalidate it.
404 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000405
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000406 // If this user is in the same block as the cast, don't change the cast.
407 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000408
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000409 // If we have already inserted a cast into this block, use it.
410 CastInst *&InsertedCast = InsertedCasts[UserBB];
411
412 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000413 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Bill Wendling1178fb42011-08-15 18:21:07 +0000414 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
416 InsertedCast =
417 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000418 InsertPt);
419 MadeChange = true;
420 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421
Dale Johannesence0b2372007-06-12 16:50:17 +0000422 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000424 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000425 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000427 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000428 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000429 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000430 MadeChange = true;
431 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000433 return MadeChange;
434}
435
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000437/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000438/// a clear win except on targets with multiple condition code registers
439/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000440///
441/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000442static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000443 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Dale Johannesence0b2372007-06-12 16:50:17 +0000445 /// InsertedCmp - Only insert a cmp in each block once.
446 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Dale Johannesence0b2372007-06-12 16:50:17 +0000448 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 UI != E; ) {
451 Use &TheUse = UI.getUse();
452 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Dale Johannesence0b2372007-06-12 16:50:17 +0000454 // Preincrement use iterator so we don't invalidate it.
455 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Dale Johannesence0b2372007-06-12 16:50:17 +0000457 // Don't bother for PHI nodes.
458 if (isa<PHINode>(User))
459 continue;
460
461 // Figure out which BB this cmp is used in.
462 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000463
Dale Johannesence0b2372007-06-12 16:50:17 +0000464 // If this user is in the same block as the cmp, don't change the cmp.
465 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000466
Dale Johannesence0b2372007-06-12 16:50:17 +0000467 // If we have already inserted a cmp into this block, use it.
468 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
469
470 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000471 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Bill Wendling5e38c472011-08-15 23:19:54 +0000472 if (isa<LandingPadInst>(InsertPt)) ++InsertPt; // Skip landingpad inst.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000474 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000475 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000476 CI->getOperand(1), "", InsertPt);
477 MadeChange = true;
478 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
Dale Johannesence0b2372007-06-12 16:50:17 +0000480 // Replace a use of the cmp with a use of the new cmp.
481 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000482 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000483 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Dale Johannesence0b2372007-06-12 16:50:17 +0000485 // If we removed all uses, nuke the cmp.
486 if (CI->use_empty())
487 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Dale Johannesence0b2372007-06-12 16:50:17 +0000489 return MadeChange;
490}
491
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000492namespace {
493class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
494protected:
495 void replaceCall(Value *With) {
496 CI->replaceAllUsesWith(With);
497 CI->eraseFromParent();
498 }
499 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000500 if (ConstantInt *SizeCI =
501 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
502 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000503 return false;
504 }
505};
506} // end anonymous namespace
507
Eric Christopher040056f2010-03-11 02:41:03 +0000508bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000509 BasicBlock *BB = CI->getParent();
510
511 // Lower inline assembly if we can.
512 // If we found an inline asm expession, and if the target knows how to
513 // lower it to normal LLVM code, do so now.
514 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
515 if (TLI->ExpandInlineAsm(CI)) {
516 // Avoid invalidating the iterator.
517 CurInstIterator = BB->begin();
518 // Avoid processing instructions out of order, which could cause
519 // reuse before a value is defined.
520 SunkAddrs.clear();
521 return true;
522 }
523 // Sink address computing for memory operands into the block.
524 if (OptimizeInlineAsmInst(CI))
525 return true;
526 }
527
Eric Christopher040056f2010-03-11 02:41:03 +0000528 // Lower all uses of llvm.objectsize.*
529 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
530 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000531 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000532 Type *ReturnTy = CI->getType();
Eric Christopher040056f2010-03-11 02:41:03 +0000533 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000534
535 // Substituting this can cause recursive simplifications, which can
536 // invalidate our iterator. Use a WeakVH to hold onto it in case this
537 // happens.
538 WeakVH IterHandle(CurInstIterator);
539
Cameron Zwarich680c9622011-03-24 04:52:04 +0000540 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
Devang Patel52e37df2011-03-24 15:35:25 +0000541 ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000542
543 // If the iterator instruction was recursively deleted, start over at the
544 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000545 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000546 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000547 SunkAddrs.clear();
548 }
Eric Christopher040056f2010-03-11 02:41:03 +0000549 return true;
550 }
551
552 // From here on out we're working with named functions.
553 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000554
555 // llvm.dbg.value is far away from the value then iSel may not be able
556 // handle it properly. iSel will drop llvm.dbg.value if it can not
557 // find a node corresponding to the value.
558 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(CI))
559 if (Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()))
Chandler Carruthb29c1d72011-05-26 23:37:58 +0000560 if (!VI->isTerminator() &&
561 (DVI->getParent() != VI->getParent() || DT->dominates(DVI, VI))) {
Devang Patel97de92c2011-05-26 21:51:06 +0000562 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
563 DVI->removeFromParent();
Bill Wendling5e38c472011-08-15 23:19:54 +0000564 if (isa<PHINode>(VI)) {
565 BasicBlock::iterator InsertPt = VI->getParent()->getFirstNonPHI();
566 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
567 DVI->insertBefore(InsertPt);
568 } else {
Devang Patel9dd19662011-05-26 22:43:14 +0000569 DVI->insertAfter(VI);
Bill Wendling5e38c472011-08-15 23:19:54 +0000570 }
Devang Patel97de92c2011-05-26 21:51:06 +0000571 return true;
572 }
573
Eric Christopher040056f2010-03-11 02:41:03 +0000574 // We'll need TargetData from here on out.
575 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
576 if (!TD) return false;
577
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000578 // Lower all default uses of _chk calls. This is very similar
579 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000580 // that have the default "don't know" as the objectsize. Anything else
581 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000582 CodeGenPrepareFortifiedLibCalls Simplifier;
583 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000584}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000585
Evan Cheng485fafc2011-03-21 01:19:09 +0000586/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
587/// instructions to the predecessor to enable tail call optimizations. The
588/// case it is currently looking for is:
589/// bb0:
590/// %tmp0 = tail call i32 @f0()
591/// br label %return
592/// bb1:
593/// %tmp1 = tail call i32 @f1()
594/// br label %return
595/// bb2:
596/// %tmp2 = tail call i32 @f2()
597/// br label %return
598/// return:
599/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
600/// ret i32 %retval
601///
602/// =>
603///
604/// bb0:
605/// %tmp0 = tail call i32 @f0()
606/// ret i32 %tmp0
607/// bb1:
608/// %tmp1 = tail call i32 @f1()
609/// ret i32 %tmp1
610/// bb2:
611/// %tmp2 = tail call i32 @f2()
612/// ret i32 %tmp2
613///
614bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000615 if (!TLI)
616 return false;
617
Evan Cheng485fafc2011-03-21 01:19:09 +0000618 Value *V = RI->getReturnValue();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000619 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
620 if (V && !PN)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000621 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000622
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000623 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000624 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000625 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000626
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000627 // It's not safe to eliminate the sign / zero extension of the return value.
628 // See llvm::isInTailCallPosition().
629 const Function *F = BB->getParent();
630 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
631 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
632 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000633
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000634 // Make sure there are no instructions between the PHI and return, or that the
635 // return is the first instruction in the block.
636 if (PN) {
637 BasicBlock::iterator BI = BB->begin();
638 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
639 if (&*BI != RI)
640 return false;
641 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000642 BasicBlock::iterator BI = BB->begin();
643 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
644 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000645 return false;
646 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000647
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000648 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
649 /// call.
650 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000651 if (PN) {
652 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
653 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
654 // Make sure the phi value is indeed produced by the tail call.
655 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
656 TLI->mayBeEmittedAsTailCall(CI))
657 TailCalls.push_back(CI);
658 }
659 } else {
660 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
661 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
662 if (!VisitedBBs.insert(*PI))
663 continue;
664
665 BasicBlock::InstListType &InstList = (*PI)->getInstList();
666 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
667 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000668 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
669 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000670 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000671
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000672 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000673 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000674 TailCalls.push_back(CI);
675 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000676 }
677
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000678 bool Changed = false;
679 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
680 CallInst *CI = TailCalls[i];
681 CallSite CS(CI);
682
683 // Conservatively require the attributes of the call to match those of the
684 // return. Ignore noalias because it doesn't affect the call sequence.
685 unsigned CalleeRetAttr = CS.getAttributes().getRetAttributes();
686 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
687 continue;
688
689 // Make sure the call instruction is followed by an unconditional branch to
690 // the return block.
691 BasicBlock *CallBB = CI->getParent();
692 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
693 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
694 continue;
695
696 // Duplicate the return into CallBB.
697 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000698 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000699 ++NumRetsDup;
700 }
701
702 // If we eliminated all predecessors of the block, delete the block now.
703 if (Changed && pred_begin(BB) == pred_end(BB))
704 BB->eraseFromParent();
705
706 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000707}
708
Chris Lattner88a5c832008-11-25 07:09:13 +0000709//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000710// Memory Optimization
711//===----------------------------------------------------------------------===//
712
Chris Lattnerdd77df32007-04-13 20:30:56 +0000713/// IsNonLocalValue - Return true if the specified values are defined in a
714/// different basic block than BB.
715static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
716 if (Instruction *I = dyn_cast<Instruction>(V))
717 return I->getParent() != BB;
718 return false;
719}
720
Bob Wilson4a8ee232009-12-03 21:47:07 +0000721/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000722/// addressing modes that can do significant amounts of computation. As such,
723/// instruction selection will try to get the load or store to do as much
724/// computation as possible for the program. The problem is that isel can only
725/// see within a single block. As such, we sink as much legal addressing mode
726/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000727///
728/// This method is used to optimize both load/store and inline asms with memory
729/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000730bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000731 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000732 Value *Repl = Addr;
733
Owen Andersond2f41742010-11-19 22:15:03 +0000734 // Try to collapse single-value PHI nodes. This is necessary to undo
735 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000736 SmallVector<Value*, 8> worklist;
737 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000738 worklist.push_back(Addr);
739
740 // Use a worklist to iteratively look through PHI nodes, and ensure that
741 // the addressing mode obtained from the non-PHI roots of the graph
742 // are equivalent.
743 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000744 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000745 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000746 SmallVector<Instruction*, 16> AddrModeInsts;
747 ExtAddrMode AddrMode;
748 while (!worklist.empty()) {
749 Value *V = worklist.back();
750 worklist.pop_back();
751
752 // Break use-def graph loops.
753 if (Visited.count(V)) {
754 Consensus = 0;
755 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000756 }
757
Owen Anderson35bf4d62010-11-27 08:15:55 +0000758 Visited.insert(V);
759
760 // For a PHI node, push all of its incoming values.
761 if (PHINode *P = dyn_cast<PHINode>(V)) {
762 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
763 worklist.push_back(P->getIncomingValue(i));
764 continue;
765 }
766
767 // For non-PHIs, determine the addressing mode being computed.
768 SmallVector<Instruction*, 16> NewAddrModeInsts;
769 ExtAddrMode NewAddrMode =
770 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
771 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000772
773 // This check is broken into two cases with very similar code to avoid using
774 // getNumUses() as much as possible. Some values have a lot of uses, so
775 // calling getNumUses() unconditionally caused a significant compile-time
776 // regression.
777 if (!Consensus) {
778 Consensus = V;
779 AddrMode = NewAddrMode;
780 AddrModeInsts = NewAddrModeInsts;
781 continue;
782 } else if (NewAddrMode == AddrMode) {
783 if (!IsNumUsesConsensusValid) {
784 NumUsesConsensus = Consensus->getNumUses();
785 IsNumUsesConsensusValid = true;
786 }
787
788 // Ensure that the obtained addressing mode is equivalent to that obtained
789 // for all other roots of the PHI traversal. Also, when choosing one
790 // such root as representative, select the one with the most uses in order
791 // to keep the cost modeling heuristics in AddressingModeMatcher
792 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000793 unsigned NumUses = V->getNumUses();
794 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000795 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000796 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000797 AddrModeInsts = NewAddrModeInsts;
798 }
799 continue;
800 }
801
802 Consensus = 0;
803 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000804 }
805
Owen Anderson35bf4d62010-11-27 08:15:55 +0000806 // If the addressing mode couldn't be determined, or if multiple different
807 // ones were determined, bail out now.
808 if (!Consensus) return false;
809
Chris Lattnerdd77df32007-04-13 20:30:56 +0000810 // Check to see if any of the instructions supersumed by this addr mode are
811 // non-local to I's BB.
812 bool AnyNonLocal = false;
813 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000814 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000815 AnyNonLocal = true;
816 break;
817 }
818 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000819
Chris Lattnerdd77df32007-04-13 20:30:56 +0000820 // If all the instructions matched are already in this BB, don't do anything.
821 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000822 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000823 return false;
824 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000825
Chris Lattnerdd77df32007-04-13 20:30:56 +0000826 // Insert this computation right after this user. Since our caller is
827 // scanning from the top of the BB to the bottom, reuse of the expr are
828 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000829 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000830
Chris Lattnerdd77df32007-04-13 20:30:56 +0000831 // Now that we determined the addressing expression we want to use and know
832 // that we have to sink it into this block. Check to see if we have already
833 // done this for some other load/store instr in this block. If so, reuse the
834 // computation.
835 Value *&SunkAddr = SunkAddrs[Addr];
836 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000837 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000838 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000839 if (SunkAddr->getType() != Addr->getType())
840 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
841 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000842 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000843 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000844 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000845 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000846
Chris Lattnerdd77df32007-04-13 20:30:56 +0000847 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000848
849 // Start with the base register. Do this first so that subsequent address
850 // matching finds it last, which will prevent it from trying to match it
851 // as the scaled value in case it happens to be a mul. That would be
852 // problematic if we've sunk a different mul for the scale, because then
853 // we'd end up sinking both muls.
854 if (AddrMode.BaseReg) {
855 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000856 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000857 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
858 if (V->getType() != IntPtrTy)
859 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
860 "sunkaddr", InsertPt);
861 Result = V;
862 }
863
864 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 if (AddrMode.Scale) {
866 Value *V = AddrMode.ScaledReg;
867 if (V->getType() == IntPtrTy) {
868 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000869 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000870 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
871 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
872 cast<IntegerType>(V->getType())->getBitWidth()) {
873 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
874 } else {
875 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
876 }
877 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000878 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000879 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000880 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000881 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000882 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000883 else
884 Result = V;
885 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000886
Chris Lattnerdd77df32007-04-13 20:30:56 +0000887 // Add in the BaseGV if present.
888 if (AddrMode.BaseGV) {
889 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
890 InsertPt);
891 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000892 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000893 else
894 Result = V;
895 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000896
Chris Lattnerdd77df32007-04-13 20:30:56 +0000897 // Add in the Base Offset if present.
898 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000899 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000900 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000901 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000902 else
903 Result = V;
904 }
905
906 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000907 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000908 else
909 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
910 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000911
Owen Andersond2f41742010-11-19 22:15:03 +0000912 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000913
Chris Lattner0403b472011-04-09 07:05:44 +0000914 // If we have no uses, recursively delete the value and all dead instructions
915 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000916 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000917 // This can cause recursive deletion, which can invalidate our iterator.
918 // Use a WeakVH to hold onto it in case this happens.
919 WeakVH IterHandle(CurInstIterator);
920 BasicBlock *BB = CurInstIterator->getParent();
921
Owen Andersond2f41742010-11-19 22:15:03 +0000922 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000923
924 if (IterHandle != CurInstIterator) {
925 // If the iterator instruction was recursively deleted, start over at the
926 // start of the block.
927 CurInstIterator = BB->begin();
928 SunkAddrs.clear();
929 } else {
930 // This address is now available for reassignment, so erase the table
931 // entry; we don't want to match some completely different instruction.
932 SunkAddrs[Addr] = 0;
933 }
Dale Johannesen536d31b2010-03-31 20:37:15 +0000934 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000935 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000936 return true;
937}
938
Evan Cheng9bf12b52008-02-26 02:42:37 +0000939/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000940/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000941/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000942bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000943 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000944
Chris Lattner75796092011-01-15 07:14:54 +0000945 TargetLowering::AsmOperandInfoVector
946 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000947 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000948 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
949 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
950
Evan Cheng9bf12b52008-02-26 02:42:37 +0000951 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000952 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000953
Eli Friedman9ec80952008-02-26 18:37:49 +0000954 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
955 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000956 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000957 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000958 } else if (OpInfo.Type == InlineAsm::isInput)
959 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000960 }
961
962 return MadeChange;
963}
964
Dan Gohmanb00f2362009-10-16 20:59:35 +0000965/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
966/// basic block as the load, unless conditions are unfavorable. This allows
967/// SelectionDAG to fold the extend into the load.
968///
969bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
970 // Look for a load being extended.
971 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
972 if (!LI) return false;
973
974 // If they're already in the same block, there's nothing to do.
975 if (LI->getParent() == I->getParent())
976 return false;
977
978 // If the load has other users and the truncate is not free, this probably
979 // isn't worthwhile.
980 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000981 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
982 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000983 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000984 return false;
985
986 // Check whether the target supports casts folded into loads.
987 unsigned LType;
988 if (isa<ZExtInst>(I))
989 LType = ISD::ZEXTLOAD;
990 else {
991 assert(isa<SExtInst>(I) && "Unexpected ext type!");
992 LType = ISD::SEXTLOAD;
993 }
994 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
995 return false;
996
997 // Move the extend into the same block as the load, so that SelectionDAG
998 // can fold it.
999 I->removeFromParent();
1000 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001001 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001002 return true;
1003}
1004
Evan Chengbdcb7262007-12-05 23:58:20 +00001005bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1006 BasicBlock *DefBB = I->getParent();
1007
Bob Wilson9120f5c2010-09-21 21:44:14 +00001008 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001009 // other uses of the source with result of extension.
1010 Value *Src = I->getOperand(0);
1011 if (Src->hasOneUse())
1012 return false;
1013
Evan Cheng696e5c02007-12-13 07:50:36 +00001014 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001015 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001016 return false;
1017
Evan Cheng772de512007-12-12 00:51:06 +00001018 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001019 // this block.
1020 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001021 return false;
1022
Evan Chengbdcb7262007-12-05 23:58:20 +00001023 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001024 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001025 UI != E; ++UI) {
1026 Instruction *User = cast<Instruction>(*UI);
1027
1028 // Figure out which BB this ext is used in.
1029 BasicBlock *UserBB = User->getParent();
1030 if (UserBB == DefBB) continue;
1031 DefIsLiveOut = true;
1032 break;
1033 }
1034 if (!DefIsLiveOut)
1035 return false;
1036
Evan Cheng765dff22007-12-12 02:53:41 +00001037 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001038 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001039 UI != E; ++UI) {
1040 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001041 BasicBlock *UserBB = User->getParent();
1042 if (UserBB == DefBB) continue;
1043 // Be conservative. We don't want this xform to end up introducing
1044 // reloads just before load / store instructions.
1045 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001046 return false;
1047 }
1048
Evan Chengbdcb7262007-12-05 23:58:20 +00001049 // InsertedTruncs - Only insert one trunc in each block once.
1050 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1051
1052 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001053 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001054 UI != E; ++UI) {
1055 Use &TheUse = UI.getUse();
1056 Instruction *User = cast<Instruction>(*UI);
1057
1058 // Figure out which BB this ext is used in.
1059 BasicBlock *UserBB = User->getParent();
1060 if (UserBB == DefBB) continue;
1061
1062 // Both src and def are live in this block. Rewrite the use.
1063 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1064
1065 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001066 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Bill Wendling5e38c472011-08-15 23:19:54 +00001067 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
Evan Chengbdcb7262007-12-05 23:58:20 +00001068 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1069 }
1070
1071 // Replace a use of the {s|z}ext source with a use of the result.
1072 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001073 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001074 MadeChange = true;
1075 }
1076
1077 return MadeChange;
1078}
1079
Cameron Zwarichc0611012011-01-06 02:37:26 +00001080bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001081 if (PHINode *P = dyn_cast<PHINode>(I)) {
1082 // It is possible for very late stage optimizations (such as SimplifyCFG)
1083 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1084 // trivial PHI, go ahead and zap it here.
1085 if (Value *V = SimplifyInstruction(P)) {
1086 P->replaceAllUsesWith(V);
1087 P->eraseFromParent();
1088 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001089 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001090 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001091 return false;
1092 }
1093
1094 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001095 // If the source of the cast is a constant, then this should have
1096 // already been constant folded. The only reason NOT to constant fold
1097 // it is if something (e.g. LSR) was careful to place the constant
1098 // evaluation in a block other than then one that uses it (e.g. to hoist
1099 // the address of globals out of a loop). If this is the case, we don't
1100 // want to forward-subst the cast.
1101 if (isa<Constant>(CI->getOperand(0)))
1102 return false;
1103
Chris Lattner1a8943a2011-01-15 07:29:01 +00001104 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1105 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001106
Chris Lattner1a8943a2011-01-15 07:29:01 +00001107 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1108 bool MadeChange = MoveExtToFormExtLoad(I);
1109 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001110 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001111 return false;
1112 }
1113
1114 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1115 return OptimizeCmpExpression(CI);
1116
1117 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001118 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001119 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1120 return false;
1121 }
1122
1123 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001124 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001125 return OptimizeMemoryInst(I, SI->getOperand(1),
1126 SI->getOperand(0)->getType());
1127 return false;
1128 }
1129
1130 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001131 if (GEPI->hasAllZeroIndices()) {
1132 /// The GEP operand must be a pointer, so must its result -> BitCast
1133 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1134 GEPI->getName(), GEPI);
1135 GEPI->replaceAllUsesWith(NC);
1136 GEPI->eraseFromParent();
1137 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001138 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001139 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001140 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001141 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001142 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001143
1144 if (CallInst *CI = dyn_cast<CallInst>(I))
1145 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001146
Evan Cheng485fafc2011-03-21 01:19:09 +00001147 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1148 return DupRetToEnableTailCallOpts(RI);
1149
Chris Lattner1a8943a2011-01-15 07:29:01 +00001150 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001151}
1152
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001153// In this pass we look for GEP and cast instructions that are used
1154// across basic blocks and rewrite them to improve basic-block-at-a-time
1155// selection.
1156bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001157 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001158 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001159
Chris Lattner75796092011-01-15 07:14:54 +00001160 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001161 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1162 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001163
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001164 return MadeChange;
1165}