blob: eb80f5c64acde5c2208b4273ae3ea0e29f65b73f [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 Chengae16d6b2011-03-19 17:17:39 +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 Chengae16d6b2011-03-19 17:17:39 +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
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000079 // Keeps track of non-local addresses that have been sunk into a block. This
80 // allows us to avoid inserting duplicate code for blocks with multiple
81 // load/stores of the same address.
82 DenseMap<Value*, Value*> SunkAddrs;
83
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000084 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000085 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000086 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000087 : FunctionPass(ID), TLI(tli) {
88 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
89 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000090 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000091
Andreas Neustifterad809812009-09-16 09:26:52 +000092 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000093 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000094 AU.addPreserved<ProfileInfo>();
95 }
96
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000097 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000098 bool EliminateMostlyEmptyBlocks(Function &F);
99 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
100 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000102 bool OptimizeInst(Instruction *I);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000103 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000104 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000105 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000106 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000107 bool OptimizeExtUses(Instruction *I);
Evan Chengae16d6b2011-03-19 17:17:39 +0000108 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109 };
110}
Devang Patel794fd752007-05-01 21:15:47 +0000111
Devang Patel19974732007-05-03 01:11:54 +0000112char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000113INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000114 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115
116FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
117 return new CodeGenPrepare(TLI);
118}
119
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000120bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000121 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000122
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000123 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000124 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000125 // First pass, eliminate blocks that contain only PHI nodes and an
126 // unconditional branch.
127 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000128
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000129 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000130 while (MadeChange) {
131 MadeChange = false;
132 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
133 MadeChange |= OptimizeBlock(*BB);
134 EverMadeChange |= MadeChange;
135 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000136
137 SunkAddrs.clear();
138
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000139 if (!DisableBranchOpts) {
140 MadeChange = false;
141 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
142 MadeChange |= ConstantFoldTerminator(BB);
143
144 if (MadeChange && DT)
145 DT->DT->recalculate(F);
146 EverMadeChange |= MadeChange;
147 }
148
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000149 return EverMadeChange;
150}
151
Dale Johannesen2d697242009-03-27 01:13:37 +0000152/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
153/// debug info directives, and an unconditional branch. Passes before isel
154/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
155/// isel. Start by eliminating these blocks so we can split them the way we
156/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000157bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
158 bool MadeChange = false;
159 // Note that this intentionally skips the entry block.
160 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
161 BasicBlock *BB = I++;
162
163 // If this block doesn't end with an uncond branch, ignore it.
164 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
165 if (!BI || !BI->isUnconditional())
166 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000167
Dale Johannesen2d697242009-03-27 01:13:37 +0000168 // If the instruction before the branch (skipping debug info) isn't a phi
169 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000170 BasicBlock::iterator BBI = BI;
171 if (BBI != BB->begin()) {
172 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000173 while (isa<DbgInfoIntrinsic>(BBI)) {
174 if (BBI == BB->begin())
175 break;
176 --BBI;
177 }
178 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
179 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000180 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000181
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000182 // Do not break infinite loops.
183 BasicBlock *DestBB = BI->getSuccessor(0);
184 if (DestBB == BB)
185 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000186
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 if (!CanMergeBlocks(BB, DestBB))
188 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000189
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000190 EliminateMostlyEmptyBlock(BB);
191 MadeChange = true;
192 }
193 return MadeChange;
194}
195
196/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
197/// single uncond branch between them, and BB contains no other non-phi
198/// instructions.
199bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
200 const BasicBlock *DestBB) const {
201 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
202 // the successor. If there are more complex condition (e.g. preheaders),
203 // don't mess around with them.
204 BasicBlock::const_iterator BBI = BB->begin();
205 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000206 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000207 UI != E; ++UI) {
208 const Instruction *User = cast<Instruction>(*UI);
209 if (User->getParent() != DestBB || !isa<PHINode>(User))
210 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211 // If User is inside DestBB block and it is a PHINode then check
212 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000213 // a complex condition (e.g. preheaders) we want to avoid here.
214 if (User->getParent() == DestBB) {
215 if (const PHINode *UPN = dyn_cast<PHINode>(User))
216 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
217 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
218 if (Insn && Insn->getParent() == BB &&
219 Insn->getParent() != UPN->getIncomingBlock(I))
220 return false;
221 }
222 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000223 }
224 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000225
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000226 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
227 // and DestBB may have conflicting incoming values for the block. If so, we
228 // can't merge the block.
229 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
230 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000231
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000232 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000233 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
235 // It is faster to get preds from a PHI than with pred_iterator.
236 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
237 BBPreds.insert(BBPN->getIncomingBlock(i));
238 } else {
239 BBPreds.insert(pred_begin(BB), pred_end(BB));
240 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000241
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000242 // Walk the preds of DestBB.
243 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
244 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
245 if (BBPreds.count(Pred)) { // Common predecessor?
246 BBI = DestBB->begin();
247 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
248 const Value *V1 = PN->getIncomingValueForBlock(Pred);
249 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000250
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 // If V2 is a phi node in BB, look up what the mapped value will be.
252 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
253 if (V2PN->getParent() == BB)
254 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000255
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000256 // If there is a conflict, bail out.
257 if (V1 != V2) return false;
258 }
259 }
260 }
261
262 return true;
263}
264
265
266/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
267/// an unconditional branch in it.
268void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
269 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
270 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000271
David Greene68d67fd2010-01-05 01:27:11 +0000272 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000273
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 // If the destination block has a single pred, then this is a trivial edge,
275 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000276 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000277 if (SinglePred != DestBB) {
278 // Remember if SinglePred was the entry block of the function. If so, we
279 // will need to move BB back to the entry position.
280 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000281 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000282
Chris Lattnerf5102a02008-11-28 19:54:49 +0000283 if (isEntry && BB != &BB->getParent()->getEntryBlock())
284 BB->moveBefore(&BB->getParent()->getEntryBlock());
285
David Greene68d67fd2010-01-05 01:27:11 +0000286 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000287 return;
288 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000289 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000290
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000291 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
292 // to handle the new incoming edges it is about to have.
293 PHINode *PN;
294 for (BasicBlock::iterator BBI = DestBB->begin();
295 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
296 // Remove the incoming value for BB, and remember it.
297 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000298
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000299 // Two options: either the InVal is a phi node defined in BB or it is some
300 // value that dominates BB.
301 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
302 if (InValPhi && InValPhi->getParent() == BB) {
303 // Add all of the input values of the input PHI as inputs of this phi.
304 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
305 PN->addIncoming(InValPhi->getIncomingValue(i),
306 InValPhi->getIncomingBlock(i));
307 } else {
308 // Otherwise, add one instance of the dominating value for each edge that
309 // we will be adding.
310 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
311 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
312 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
313 } else {
314 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
315 PN->addIncoming(InVal, *PI);
316 }
317 }
318 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000319
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000320 // The PHIs are now updated, change everything that refers to BB to use
321 // DestBB and remove BB.
322 BB->replaceAllUsesWith(DestBB);
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000323 if (DT) {
324 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
325 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
326 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
327 DT->changeImmediateDominator(DestBB, NewIDom);
328 DT->eraseNode(BB);
329 }
Evan Cheng04149f72009-12-17 09:39:49 +0000330 if (PFI) {
331 PFI->replaceAllUses(BB, DestBB);
332 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000333 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000334 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000335 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000336
David Greene68d67fd2010-01-05 01:27:11 +0000337 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338}
339
Chris Lattnerdd77df32007-04-13 20:30:56 +0000340/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000341/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
342/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000343/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000344///
345/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000346///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000347static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000348 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000349 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
350 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerdd77df32007-04-13 20:30:56 +0000352 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000353 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000354 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000355
Chris Lattnerdd77df32007-04-13 20:30:56 +0000356 // If this is an extension, it will be a zero or sign extension, which
357 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000358 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000359
Chris Lattnerdd77df32007-04-13 20:30:56 +0000360 // If these values will be promoted, find out what they will be promoted
361 // to. This helps us consider truncates on PPC as noop copies when they
362 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000363 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000364 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000365 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000366 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000367
Chris Lattnerdd77df32007-04-13 20:30:56 +0000368 // If, after promotion, these are the same types, this is a noop copy.
369 if (SrcVT != DstVT)
370 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000371
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000372 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000373
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000374 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000375 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000376
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000377 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000378 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000379 UI != E; ) {
380 Use &TheUse = UI.getUse();
381 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000382
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000383 // Figure out which BB this cast is used in. For PHI's this is the
384 // appropriate predecessor block.
385 BasicBlock *UserBB = User->getParent();
386 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000387 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000388 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000389
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000390 // Preincrement use iterator so we don't invalidate it.
391 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000393 // If this user is in the same block as the cast, don't change the cast.
394 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000396 // If we have already inserted a cast into this block, use it.
397 CastInst *&InsertedCast = InsertedCasts[UserBB];
398
399 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000400 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000401
402 InsertedCast =
403 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000404 InsertPt);
405 MadeChange = true;
406 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000407
Dale Johannesence0b2372007-06-12 16:50:17 +0000408 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000409 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000410 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000411 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000413 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000414 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000415 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000416 MadeChange = true;
417 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000418
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000419 return MadeChange;
420}
421
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000423/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000424/// a clear win except on targets with multiple condition code registers
425/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000426///
427/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000428static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000429 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000430
Dale Johannesence0b2372007-06-12 16:50:17 +0000431 /// InsertedCmp - Only insert a cmp in each block once.
432 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Dale Johannesence0b2372007-06-12 16:50:17 +0000434 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000435 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000436 UI != E; ) {
437 Use &TheUse = UI.getUse();
438 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000439
Dale Johannesence0b2372007-06-12 16:50:17 +0000440 // Preincrement use iterator so we don't invalidate it.
441 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000442
Dale Johannesence0b2372007-06-12 16:50:17 +0000443 // Don't bother for PHI nodes.
444 if (isa<PHINode>(User))
445 continue;
446
447 // Figure out which BB this cmp is used in.
448 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Dale Johannesence0b2372007-06-12 16:50:17 +0000450 // If this user is in the same block as the cmp, don't change the cmp.
451 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Dale Johannesence0b2372007-06-12 16:50:17 +0000453 // If we have already inserted a cmp into this block, use it.
454 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
455
456 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000457 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
459 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000460 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000461 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000462 CI->getOperand(1), "", InsertPt);
463 MadeChange = true;
464 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Dale Johannesence0b2372007-06-12 16:50:17 +0000466 // Replace a use of the cmp with a use of the new cmp.
467 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000468 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000469 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470
Dale Johannesence0b2372007-06-12 16:50:17 +0000471 // If we removed all uses, nuke the cmp.
472 if (CI->use_empty())
473 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Dale Johannesence0b2372007-06-12 16:50:17 +0000475 return MadeChange;
476}
477
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000478namespace {
479class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
480protected:
481 void replaceCall(Value *With) {
482 CI->replaceAllUsesWith(With);
483 CI->eraseFromParent();
484 }
485 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000486 if (ConstantInt *SizeCI =
487 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
488 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000489 return false;
490 }
491};
492} // end anonymous namespace
493
Eric Christopher040056f2010-03-11 02:41:03 +0000494bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000495 BasicBlock *BB = CI->getParent();
496
497 // Lower inline assembly if we can.
498 // If we found an inline asm expession, and if the target knows how to
499 // lower it to normal LLVM code, do so now.
500 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
501 if (TLI->ExpandInlineAsm(CI)) {
502 // Avoid invalidating the iterator.
503 CurInstIterator = BB->begin();
504 // Avoid processing instructions out of order, which could cause
505 // reuse before a value is defined.
506 SunkAddrs.clear();
507 return true;
508 }
509 // Sink address computing for memory operands into the block.
510 if (OptimizeInlineAsmInst(CI))
511 return true;
512 }
513
Eric Christopher040056f2010-03-11 02:41:03 +0000514 // Lower all uses of llvm.objectsize.*
515 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
516 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000517 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000518 const Type *ReturnTy = CI->getType();
519 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000520
521 // Substituting this can cause recursive simplifications, which can
522 // invalidate our iterator. Use a WeakVH to hold onto it in case this
523 // happens.
524 WeakVH IterHandle(CurInstIterator);
525
526 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
527
528 // If the iterator instruction was recursively deleted, start over at the
529 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000530 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000531 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000532 SunkAddrs.clear();
533 }
Eric Christopher040056f2010-03-11 02:41:03 +0000534 return true;
535 }
536
537 // From here on out we're working with named functions.
538 if (CI->getCalledFunction() == 0) return false;
539
540 // We'll need TargetData from here on out.
541 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
542 if (!TD) return false;
543
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000544 // Lower all default uses of _chk calls. This is very similar
545 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000546 // that have the default "don't know" as the objectsize. Anything else
547 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000548 CodeGenPrepareFortifiedLibCalls Simplifier;
549 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000550}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000551
Evan Chengae16d6b2011-03-19 17:17:39 +0000552/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
553/// instructions to the predecessor to enable tail call optimizations. The
554/// case it is currently looking for is:
555/// bb0:
556/// %tmp0 = tail call i32 @f0()
557/// br label %return
558/// bb1:
559/// %tmp1 = tail call i32 @f1()
560/// br label %return
561/// bb2:
562/// %tmp2 = tail call i32 @f2()
563/// br label %return
564/// return:
565/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
566/// ret i32 %retval
567///
568/// =>
569///
570/// bb0:
571/// %tmp0 = tail call i32 @f0()
572/// ret i32 %tmp0
573/// bb1:
574/// %tmp1 = tail call i32 @f1()
575/// ret i32 %tmp1
576/// bb2:
577/// %tmp2 = tail call i32 @f2()
578/// ret i32 %tmp2
579///
580bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
581 Value *V = RI->getReturnValue();
582 if (!V)
583 return false;
584
585 if (PHINode *PN = dyn_cast<PHINode>(V)) {
586 BasicBlock *BB = RI->getParent();
587 if (PN->getParent() != BB)
588 return false;
589
590 // It's not safe to eliminate the sign / zero extension of the return value.
591 // See llvm::isInTailCallPosition().
592 const Function *F = BB->getParent();
593 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
594 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
595 return false;
596
597 // Make sure there are no instructions between PHI and return.
598 BasicBlock::iterator BI = PN;
599 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
600 if (&*BI != RI)
601 return false;
602
603 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a
604 /// tail call.
605 SmallVector<CallInst*, 4> TailCalls;
606 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
607 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
608 if (CI && TLI->mayBeEmittedAsTailCall(CI))
609 TailCalls.push_back(CI);
610 }
611
612 bool Changed = false;
613 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
614 CallInst *CI = TailCalls[i];
615 CallSite CS(CI);
616
617 // Conservatively require the attributes of the call to match those of
618 // the return. Ignore noalias because it doesn't affect the call sequence.
619 unsigned CalleeRetAttr = CS.getAttributes().getRetAttributes();
620 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
621 continue;
622
623 // Make sure the call instruction is followed by an unconditional branch
624 // to the return block.
625 BasicBlock *CallBB = CI->getParent();
626 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
627 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
628 continue;
629
630 // Duplicate the return into CallBB.
631 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
632 Changed = true;
633 ++NumRetsDup;
634 }
635
636 return Changed;
637 }
638
639 return false;
640}
641
Chris Lattner88a5c832008-11-25 07:09:13 +0000642//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000643// Memory Optimization
644//===----------------------------------------------------------------------===//
645
Chris Lattnerdd77df32007-04-13 20:30:56 +0000646/// IsNonLocalValue - Return true if the specified values are defined in a
647/// different basic block than BB.
648static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
649 if (Instruction *I = dyn_cast<Instruction>(V))
650 return I->getParent() != BB;
651 return false;
652}
653
Bob Wilson4a8ee232009-12-03 21:47:07 +0000654/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000655/// addressing modes that can do significant amounts of computation. As such,
656/// instruction selection will try to get the load or store to do as much
657/// computation as possible for the program. The problem is that isel can only
658/// see within a single block. As such, we sink as much legal addressing mode
659/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000660///
661/// This method is used to optimize both load/store and inline asms with memory
662/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000663bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner1a8943a2011-01-15 07:29:01 +0000664 const Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000665 Value *Repl = Addr;
666
Owen Andersond2f41742010-11-19 22:15:03 +0000667 // Try to collapse single-value PHI nodes. This is necessary to undo
668 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000669 SmallVector<Value*, 8> worklist;
670 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000671 worklist.push_back(Addr);
672
673 // Use a worklist to iteratively look through PHI nodes, and ensure that
674 // the addressing mode obtained from the non-PHI roots of the graph
675 // are equivalent.
676 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000677 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000678 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000679 SmallVector<Instruction*, 16> AddrModeInsts;
680 ExtAddrMode AddrMode;
681 while (!worklist.empty()) {
682 Value *V = worklist.back();
683 worklist.pop_back();
684
685 // Break use-def graph loops.
686 if (Visited.count(V)) {
687 Consensus = 0;
688 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000689 }
690
Owen Anderson35bf4d62010-11-27 08:15:55 +0000691 Visited.insert(V);
692
693 // For a PHI node, push all of its incoming values.
694 if (PHINode *P = dyn_cast<PHINode>(V)) {
695 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
696 worklist.push_back(P->getIncomingValue(i));
697 continue;
698 }
699
700 // For non-PHIs, determine the addressing mode being computed.
701 SmallVector<Instruction*, 16> NewAddrModeInsts;
702 ExtAddrMode NewAddrMode =
703 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
704 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000705
706 // This check is broken into two cases with very similar code to avoid using
707 // getNumUses() as much as possible. Some values have a lot of uses, so
708 // calling getNumUses() unconditionally caused a significant compile-time
709 // regression.
710 if (!Consensus) {
711 Consensus = V;
712 AddrMode = NewAddrMode;
713 AddrModeInsts = NewAddrModeInsts;
714 continue;
715 } else if (NewAddrMode == AddrMode) {
716 if (!IsNumUsesConsensusValid) {
717 NumUsesConsensus = Consensus->getNumUses();
718 IsNumUsesConsensusValid = true;
719 }
720
721 // Ensure that the obtained addressing mode is equivalent to that obtained
722 // for all other roots of the PHI traversal. Also, when choosing one
723 // such root as representative, select the one with the most uses in order
724 // to keep the cost modeling heuristics in AddressingModeMatcher
725 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000726 unsigned NumUses = V->getNumUses();
727 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000728 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000729 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000730 AddrModeInsts = NewAddrModeInsts;
731 }
732 continue;
733 }
734
735 Consensus = 0;
736 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000737 }
738
Owen Anderson35bf4d62010-11-27 08:15:55 +0000739 // If the addressing mode couldn't be determined, or if multiple different
740 // ones were determined, bail out now.
741 if (!Consensus) return false;
742
Chris Lattnerdd77df32007-04-13 20:30:56 +0000743 // Check to see if any of the instructions supersumed by this addr mode are
744 // non-local to I's BB.
745 bool AnyNonLocal = false;
746 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000747 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000748 AnyNonLocal = true;
749 break;
750 }
751 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000752
Chris Lattnerdd77df32007-04-13 20:30:56 +0000753 // If all the instructions matched are already in this BB, don't do anything.
754 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000755 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000756 return false;
757 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000758
Chris Lattnerdd77df32007-04-13 20:30:56 +0000759 // Insert this computation right after this user. Since our caller is
760 // scanning from the top of the BB to the bottom, reuse of the expr are
761 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000762 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000763
Chris Lattnerdd77df32007-04-13 20:30:56 +0000764 // Now that we determined the addressing expression we want to use and know
765 // that we have to sink it into this block. Check to see if we have already
766 // done this for some other load/store instr in this block. If so, reuse the
767 // computation.
768 Value *&SunkAddr = SunkAddrs[Addr];
769 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000770 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000771 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000772 if (SunkAddr->getType() != Addr->getType())
773 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
774 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000775 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000776 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000777 const Type *IntPtrTy =
778 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000779
Chris Lattnerdd77df32007-04-13 20:30:56 +0000780 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000781
782 // Start with the base register. Do this first so that subsequent address
783 // matching finds it last, which will prevent it from trying to match it
784 // as the scaled value in case it happens to be a mul. That would be
785 // problematic if we've sunk a different mul for the scale, because then
786 // we'd end up sinking both muls.
787 if (AddrMode.BaseReg) {
788 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000789 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000790 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
791 if (V->getType() != IntPtrTy)
792 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
793 "sunkaddr", InsertPt);
794 Result = V;
795 }
796
797 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000798 if (AddrMode.Scale) {
799 Value *V = AddrMode.ScaledReg;
800 if (V->getType() == IntPtrTy) {
801 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000802 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000803 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
804 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
805 cast<IntegerType>(V->getType())->getBitWidth()) {
806 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
807 } else {
808 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
809 }
810 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000811 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000812 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000813 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000814 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000815 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000816 else
817 Result = V;
818 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000819
Chris Lattnerdd77df32007-04-13 20:30:56 +0000820 // Add in the BaseGV if present.
821 if (AddrMode.BaseGV) {
822 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
823 InsertPt);
824 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000825 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000826 else
827 Result = V;
828 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000829
Chris Lattnerdd77df32007-04-13 20:30:56 +0000830 // Add in the Base Offset if present.
831 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000832 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000833 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000834 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000835 else
836 Result = V;
837 }
838
839 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000840 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000841 else
842 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
843 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000844
Owen Andersond2f41742010-11-19 22:15:03 +0000845 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000846
Owen Andersond2f41742010-11-19 22:15:03 +0000847 if (Repl->use_empty()) {
848 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000849 // This address is now available for reassignment, so erase the table entry;
850 // we don't want to match some completely different instruction.
851 SunkAddrs[Addr] = 0;
852 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000853 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000854 return true;
855}
856
Evan Cheng9bf12b52008-02-26 02:42:37 +0000857/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000858/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000859/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000860bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000861 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000862
Chris Lattner75796092011-01-15 07:14:54 +0000863 TargetLowering::AsmOperandInfoVector
864 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000865 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000866 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
867 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
868
Evan Cheng9bf12b52008-02-26 02:42:37 +0000869 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000870 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000871
Eli Friedman9ec80952008-02-26 18:37:49 +0000872 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
873 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000874 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +0000875 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000876 } else if (OpInfo.Type == InlineAsm::isInput)
877 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000878 }
879
880 return MadeChange;
881}
882
Dan Gohmanb00f2362009-10-16 20:59:35 +0000883/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
884/// basic block as the load, unless conditions are unfavorable. This allows
885/// SelectionDAG to fold the extend into the load.
886///
887bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
888 // Look for a load being extended.
889 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
890 if (!LI) return false;
891
892 // If they're already in the same block, there's nothing to do.
893 if (LI->getParent() == I->getParent())
894 return false;
895
896 // If the load has other users and the truncate is not free, this probably
897 // isn't worthwhile.
898 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000899 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
900 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000901 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000902 return false;
903
904 // Check whether the target supports casts folded into loads.
905 unsigned LType;
906 if (isa<ZExtInst>(I))
907 LType = ISD::ZEXTLOAD;
908 else {
909 assert(isa<SExtInst>(I) && "Unexpected ext type!");
910 LType = ISD::SEXTLOAD;
911 }
912 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
913 return false;
914
915 // Move the extend into the same block as the load, so that SelectionDAG
916 // can fold it.
917 I->removeFromParent();
918 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000919 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000920 return true;
921}
922
Evan Chengbdcb7262007-12-05 23:58:20 +0000923bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
924 BasicBlock *DefBB = I->getParent();
925
Bob Wilson9120f5c2010-09-21 21:44:14 +0000926 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000927 // other uses of the source with result of extension.
928 Value *Src = I->getOperand(0);
929 if (Src->hasOneUse())
930 return false;
931
Evan Cheng696e5c02007-12-13 07:50:36 +0000932 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000933 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000934 return false;
935
Evan Cheng772de512007-12-12 00:51:06 +0000936 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000937 // this block.
938 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000939 return false;
940
Evan Chengbdcb7262007-12-05 23:58:20 +0000941 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000942 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000943 UI != E; ++UI) {
944 Instruction *User = cast<Instruction>(*UI);
945
946 // Figure out which BB this ext is used in.
947 BasicBlock *UserBB = User->getParent();
948 if (UserBB == DefBB) continue;
949 DefIsLiveOut = true;
950 break;
951 }
952 if (!DefIsLiveOut)
953 return false;
954
Evan Cheng765dff22007-12-12 02:53:41 +0000955 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000956 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000957 UI != E; ++UI) {
958 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000959 BasicBlock *UserBB = User->getParent();
960 if (UserBB == DefBB) continue;
961 // Be conservative. We don't want this xform to end up introducing
962 // reloads just before load / store instructions.
963 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000964 return false;
965 }
966
Evan Chengbdcb7262007-12-05 23:58:20 +0000967 // InsertedTruncs - Only insert one trunc in each block once.
968 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
969
970 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000971 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000972 UI != E; ++UI) {
973 Use &TheUse = UI.getUse();
974 Instruction *User = cast<Instruction>(*UI);
975
976 // Figure out which BB this ext is used in.
977 BasicBlock *UserBB = User->getParent();
978 if (UserBB == DefBB) continue;
979
980 // Both src and def are live in this block. Rewrite the use.
981 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
982
983 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000984 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000985
Evan Chengbdcb7262007-12-05 23:58:20 +0000986 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
987 }
988
989 // Replace a use of the {s|z}ext source with a use of the result.
990 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000991 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +0000992 MadeChange = true;
993 }
994
995 return MadeChange;
996}
997
Cameron Zwarichc0611012011-01-06 02:37:26 +0000998bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +0000999 if (PHINode *P = dyn_cast<PHINode>(I)) {
1000 // It is possible for very late stage optimizations (such as SimplifyCFG)
1001 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1002 // trivial PHI, go ahead and zap it here.
1003 if (Value *V = SimplifyInstruction(P)) {
1004 P->replaceAllUsesWith(V);
1005 P->eraseFromParent();
1006 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001007 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001008 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001009 return false;
1010 }
1011
1012 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001013 // If the source of the cast is a constant, then this should have
1014 // already been constant folded. The only reason NOT to constant fold
1015 // it is if something (e.g. LSR) was careful to place the constant
1016 // evaluation in a block other than then one that uses it (e.g. to hoist
1017 // the address of globals out of a loop). If this is the case, we don't
1018 // want to forward-subst the cast.
1019 if (isa<Constant>(CI->getOperand(0)))
1020 return false;
1021
Chris Lattner1a8943a2011-01-15 07:29:01 +00001022 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1023 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001024
Chris Lattner1a8943a2011-01-15 07:29:01 +00001025 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1026 bool MadeChange = MoveExtToFormExtLoad(I);
1027 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001028 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001029 return false;
1030 }
1031
1032 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1033 return OptimizeCmpExpression(CI);
1034
1035 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001036 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001037 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1038 return false;
1039 }
1040
1041 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001042 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001043 return OptimizeMemoryInst(I, SI->getOperand(1),
1044 SI->getOperand(0)->getType());
1045 return false;
1046 }
1047
1048 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001049 if (GEPI->hasAllZeroIndices()) {
1050 /// The GEP operand must be a pointer, so must its result -> BitCast
1051 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1052 GEPI->getName(), GEPI);
1053 GEPI->replaceAllUsesWith(NC);
1054 GEPI->eraseFromParent();
1055 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001056 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001057 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001058 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001059 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001060 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001061
1062 if (CallInst *CI = dyn_cast<CallInst>(I))
1063 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001064
Evan Chengae16d6b2011-03-19 17:17:39 +00001065 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1066 return DupRetToEnableTailCallOpts(RI);
1067
Chris Lattner1a8943a2011-01-15 07:29:01 +00001068 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001069}
1070
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001071// In this pass we look for GEP and cast instructions that are used
1072// across basic blocks and rewrite them to improve basic-block-at-a-time
1073// selection.
1074bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001075 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001076 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001077
Chris Lattner75796092011-01-15 07:14:54 +00001078 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001079 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1080 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001081
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001082 return MadeChange;
1083}