blob: 921cec8351285c4360c433f7ebba7d290454833a [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");
Cameron Zwarich073057f2011-01-05 17:47:38 +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");
58STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000060
Evan Chenge1bcb442010-08-17 01:34:49 +000061static cl::opt<bool>
62CriticalEdgeSplit("cgp-critical-edge-splitting",
63 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000064 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000065
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
79 /// BackEdges - Keep a set of all the loop back edges.
80 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000081 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000082
83 // Keeps track of non-local addresses that have been sunk into a block. This
84 // allows us to avoid inserting duplicate code for blocks with multiple
85 // load/stores of the same address.
86 DenseMap<Value*, Value*> SunkAddrs;
87
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
Dan Gohmanaa0e5232010-02-05 19:24:11 +0000101 virtual void releaseMemory() {
102 BackEdges.clear();
103 }
104
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000105 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000106 bool EliminateMostlyEmptyBlocks(Function &F);
107 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
108 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000110 bool OptimizeInst(Instruction *I);
Chris Lattner88a5c832008-11-25 07:09:13 +0000111 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
112 DenseMap<Value*,Value*> &SunkAddrs);
Chris Lattner75796092011-01-15 07:14:54 +0000113 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000114 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000115 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000116 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +0000117 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 };
119}
Devang Patel794fd752007-05-01 21:15:47 +0000120
Devang Patel19974732007-05-03 01:11:54 +0000121char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000122INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000123 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000124
125FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
126 return new CodeGenPrepare(TLI);
127}
128
Evan Chengab631522008-12-19 18:03:11 +0000129/// findLoopBackEdges - Do a DFS walk to find loop back edges.
130///
Mike Stumpfe095f32009-05-04 18:40:41 +0000131void CodeGenPrepare::findLoopBackEdges(const Function &F) {
132 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
133 FindFunctionBackedges(F, Edges);
134
135 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000136}
137
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000138
139bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000140 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000141
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000142 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000143 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000144 // First pass, eliminate blocks that contain only PHI nodes and an
145 // unconditional branch.
146 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147
Cameron Zwarich95bb0042011-01-04 04:43:31 +0000148 // Now find loop back edges, but only if they are being used to decide which
149 // critical edges to split.
150 if (CriticalEdgeSplit)
151 findLoopBackEdges(F);
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000152
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000153 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000154 while (MadeChange) {
155 MadeChange = false;
156 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
157 MadeChange |= OptimizeBlock(*BB);
158 EverMadeChange |= MadeChange;
159 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000160
161 SunkAddrs.clear();
162
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000163 return EverMadeChange;
164}
165
Dale Johannesen2d697242009-03-27 01:13:37 +0000166/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
167/// debug info directives, and an unconditional branch. Passes before isel
168/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
169/// isel. Start by eliminating these blocks so we can split them the way we
170/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000171bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
172 bool MadeChange = false;
173 // Note that this intentionally skips the entry block.
174 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
175 BasicBlock *BB = I++;
176
177 // If this block doesn't end with an uncond branch, ignore it.
178 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
179 if (!BI || !BI->isUnconditional())
180 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000181
Dale Johannesen2d697242009-03-27 01:13:37 +0000182 // If the instruction before the branch (skipping debug info) isn't a phi
183 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000184 BasicBlock::iterator BBI = BI;
185 if (BBI != BB->begin()) {
186 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000187 while (isa<DbgInfoIntrinsic>(BBI)) {
188 if (BBI == BB->begin())
189 break;
190 --BBI;
191 }
192 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
193 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000194 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000195
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000196 // Do not break infinite loops.
197 BasicBlock *DestBB = BI->getSuccessor(0);
198 if (DestBB == BB)
199 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000200
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000201 if (!CanMergeBlocks(BB, DestBB))
202 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000203
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000204 EliminateMostlyEmptyBlock(BB);
205 MadeChange = true;
206 }
207 return MadeChange;
208}
209
210/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
211/// single uncond branch between them, and BB contains no other non-phi
212/// instructions.
213bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
214 const BasicBlock *DestBB) const {
215 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
216 // the successor. If there are more complex condition (e.g. preheaders),
217 // don't mess around with them.
218 BasicBlock::const_iterator BBI = BB->begin();
219 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000220 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000221 UI != E; ++UI) {
222 const Instruction *User = cast<Instruction>(*UI);
223 if (User->getParent() != DestBB || !isa<PHINode>(User))
224 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000225 // If User is inside DestBB block and it is a PHINode then check
226 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000227 // a complex condition (e.g. preheaders) we want to avoid here.
228 if (User->getParent() == DestBB) {
229 if (const PHINode *UPN = dyn_cast<PHINode>(User))
230 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
231 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
232 if (Insn && Insn->getParent() == BB &&
233 Insn->getParent() != UPN->getIncomingBlock(I))
234 return false;
235 }
236 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000237 }
238 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000239
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000240 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
241 // and DestBB may have conflicting incoming values for the block. If so, we
242 // can't merge the block.
243 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
244 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000245
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000246 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000247 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000248 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
249 // It is faster to get preds from a PHI than with pred_iterator.
250 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
251 BBPreds.insert(BBPN->getIncomingBlock(i));
252 } else {
253 BBPreds.insert(pred_begin(BB), pred_end(BB));
254 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000255
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000256 // Walk the preds of DestBB.
257 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
258 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
259 if (BBPreds.count(Pred)) { // Common predecessor?
260 BBI = DestBB->begin();
261 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
262 const Value *V1 = PN->getIncomingValueForBlock(Pred);
263 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000264
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000265 // If V2 is a phi node in BB, look up what the mapped value will be.
266 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
267 if (V2PN->getParent() == BB)
268 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000269
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270 // If there is a conflict, bail out.
271 if (V1 != V2) return false;
272 }
273 }
274 }
275
276 return true;
277}
278
279
280/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
281/// an unconditional branch in it.
282void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
283 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
284 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
David Greene68d67fd2010-01-05 01:27:11 +0000286 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000287
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000288 // If the destination block has a single pred, then this is a trivial edge,
289 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000290 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000291 if (SinglePred != DestBB) {
292 // Remember if SinglePred was the entry block of the function. If so, we
293 // will need to move BB back to the entry position.
294 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000295 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000296
Chris Lattnerf5102a02008-11-28 19:54:49 +0000297 if (isEntry && BB != &BB->getParent()->getEntryBlock())
298 BB->moveBefore(&BB->getParent()->getEntryBlock());
299
David Greene68d67fd2010-01-05 01:27:11 +0000300 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000301 return;
302 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000303 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000305 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
306 // to handle the new incoming edges it is about to have.
307 PHINode *PN;
308 for (BasicBlock::iterator BBI = DestBB->begin();
309 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
310 // Remove the incoming value for BB, and remember it.
311 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000312
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000313 // Two options: either the InVal is a phi node defined in BB or it is some
314 // value that dominates BB.
315 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
316 if (InValPhi && InValPhi->getParent() == BB) {
317 // Add all of the input values of the input PHI as inputs of this phi.
318 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
319 PN->addIncoming(InValPhi->getIncomingValue(i),
320 InValPhi->getIncomingBlock(i));
321 } else {
322 // Otherwise, add one instance of the dominating value for each edge that
323 // we will be adding.
324 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
325 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
326 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
327 } else {
328 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
329 PN->addIncoming(InVal, *PI);
330 }
331 }
332 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000333
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000334 // The PHIs are now updated, change everything that refers to BB to use
335 // DestBB and remove BB.
336 BB->replaceAllUsesWith(DestBB);
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000337 if (DT) {
338 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
339 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
340 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
341 DT->changeImmediateDominator(DestBB, NewIDom);
342 DT->eraseNode(BB);
343 }
Evan Cheng04149f72009-12-17 09:39:49 +0000344 if (PFI) {
345 PFI->replaceAllUses(BB, DestBB);
346 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000347 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000348 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000349 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000350
David Greene68d67fd2010-01-05 01:27:11 +0000351 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352}
353
Chris Lattner98d5c312010-02-13 05:35:08 +0000354/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
355/// lives in to see if there is a block that we can reuse as a critical edge
356/// from TIBB.
357static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
358 BasicBlock *Dest = DestPHI->getParent();
359
360 /// TIPHIValues - This array is lazily computed to determine the values of
361 /// PHIs in Dest that TI would provide.
362 SmallVector<Value*, 32> TIPHIValues;
363
364 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
365 unsigned TIBBEntryNo = 0;
366
367 // Check to see if Dest has any blocks that can be used as a split edge for
368 // this terminator.
369 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
370 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
371 // To be usable, the pred has to end with an uncond branch to the dest.
372 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
373 if (!PredBr || !PredBr->isUnconditional())
374 continue;
375 // Must be empty other than the branch and debug info.
376 BasicBlock::iterator I = Pred->begin();
377 while (isa<DbgInfoIntrinsic>(I))
378 I++;
379 if (&*I != PredBr)
380 continue;
381 // Cannot be the entry block; its label does not get emitted.
382 if (Pred == &Dest->getParent()->getEntryBlock())
383 continue;
384
385 // Finally, since we know that Dest has phi nodes in it, we have to make
386 // sure that jumping to Pred will have the same effect as going to Dest in
387 // terms of PHI values.
388 PHINode *PN;
389 unsigned PHINo = 0;
390 unsigned PredEntryNo = pi;
391
392 bool FoundMatch = true;
393 for (BasicBlock::iterator I = Dest->begin();
394 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
395 if (PHINo == TIPHIValues.size()) {
396 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
397 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
398 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
399 }
400
401 // If the PHI entry doesn't work, we can't use this pred.
402 if (PN->getIncomingBlock(PredEntryNo) != Pred)
403 PredEntryNo = PN->getBasicBlockIndex(Pred);
404
405 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
406 FoundMatch = false;
407 break;
408 }
409 }
410
411 // If we found a workable predecessor, change TI to branch to Succ.
412 if (FoundMatch)
413 return Pred;
414 }
415 return 0;
416}
417
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000418
Chris Lattnerebe80752007-12-24 19:32:55 +0000419/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000420/// successor if it will improve codegen. We only do this if the successor has
421/// phi nodes (otherwise critical edges are ok). If there is already another
422/// predecessor of the succ that is empty (and thus has no phi nodes), use it
423/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000424static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000425 SmallSet<std::pair<const BasicBlock*,
426 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000427 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000428 BasicBlock *TIBB = TI->getParent();
429 BasicBlock *Dest = TI->getSuccessor(SuccNum);
430 assert(isa<PHINode>(Dest->begin()) &&
431 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000432 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Evan Chengfc0b80d2009-03-13 22:59:14 +0000434 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000435 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000436 if (Invoke->getSuccessor(1) == Dest)
437 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000438
Chris Lattnerebe80752007-12-24 19:32:55 +0000439 // As a hack, never split backedges of loops. Even though the copy for any
440 // PHIs inserted on the backedge would be dead for exits from the loop, we
441 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000442 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000443 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerc09687b2010-02-13 19:07:06 +0000445 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
446 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
447 if (PFI)
448 PFI->splitEdge(TIBB, Dest, ReuseBB);
449 Dest->removePredecessor(TIBB);
450 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000451 return;
452 }
453
Chris Lattnerc09687b2010-02-13 19:07:06 +0000454 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000455}
456
Evan Chengab631522008-12-19 18:03:11 +0000457
Chris Lattnerdd77df32007-04-13 20:30:56 +0000458/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000459/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
460/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000461/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000462///
463/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000464///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000465static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000466 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000467 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
468 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdd77df32007-04-13 20:30:56 +0000470 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000471 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000472 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000473
Chris Lattnerdd77df32007-04-13 20:30:56 +0000474 // If this is an extension, it will be a zero or sign extension, which
475 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000476 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
Chris Lattnerdd77df32007-04-13 20:30:56 +0000478 // If these values will be promoted, find out what they will be promoted
479 // to. This helps us consider truncates on PPC as noop copies when they
480 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000481 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000482 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000483 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000484 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdd77df32007-04-13 20:30:56 +0000486 // If, after promotion, these are the same types, this is a noop copy.
487 if (SrcVT != DstVT)
488 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000493 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000497 UI != E; ) {
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000500
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 // Figure out which BB this cast is used in. For PHI's this is the
502 // appropriate predecessor block.
503 BasicBlock *UserBB = User->getParent();
504 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000505 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 // Preincrement use iterator so we don't invalidate it.
509 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 // If this user is in the same block as the cast, don't change the cast.
512 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000514 // If we have already inserted a cast into this block, use it.
515 CastInst *&InsertedCast = InsertedCasts[UserBB];
516
517 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000518 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519
520 InsertedCast =
521 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000522 InsertPt);
523 MadeChange = true;
524 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Dale Johannesence0b2372007-06-12 16:50:17 +0000526 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000527 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000528 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000529 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000531 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000532 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000533 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000534 MadeChange = true;
535 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000537 return MadeChange;
538}
539
Eric Christopher692bf6b2008-09-24 05:32:41 +0000540/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000541/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000542/// a clear win except on targets with multiple condition code registers
543/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000544///
545/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000546static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 /// InsertedCmp - Only insert a cmp in each block once.
550 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000551
Dale Johannesence0b2372007-06-12 16:50:17 +0000552 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000553 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000554 UI != E; ) {
555 Use &TheUse = UI.getUse();
556 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000557
Dale Johannesence0b2372007-06-12 16:50:17 +0000558 // Preincrement use iterator so we don't invalidate it.
559 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
Dale Johannesence0b2372007-06-12 16:50:17 +0000561 // Don't bother for PHI nodes.
562 if (isa<PHINode>(User))
563 continue;
564
565 // Figure out which BB this cmp is used in.
566 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000567
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 // If this user is in the same block as the cmp, don't change the cmp.
569 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000570
Dale Johannesence0b2372007-06-12 16:50:17 +0000571 // If we have already inserted a cmp into this block, use it.
572 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
573
574 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000575 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000576
577 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000578 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000579 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000580 CI->getOperand(1), "", InsertPt);
581 MadeChange = true;
582 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000583
Dale Johannesence0b2372007-06-12 16:50:17 +0000584 // Replace a use of the cmp with a use of the new cmp.
585 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000586 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000587 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000588
Dale Johannesence0b2372007-06-12 16:50:17 +0000589 // If we removed all uses, nuke the cmp.
590 if (CI->use_empty())
591 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000592
Dale Johannesence0b2372007-06-12 16:50:17 +0000593 return MadeChange;
594}
595
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000596namespace {
597class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
598protected:
599 void replaceCall(Value *With) {
600 CI->replaceAllUsesWith(With);
601 CI->eraseFromParent();
602 }
603 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000604 if (ConstantInt *SizeCI =
605 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
606 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000607 return false;
608 }
609};
610} // end anonymous namespace
611
Eric Christopher040056f2010-03-11 02:41:03 +0000612bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000613 BasicBlock *BB = CI->getParent();
614
615 // Lower inline assembly if we can.
616 // If we found an inline asm expession, and if the target knows how to
617 // lower it to normal LLVM code, do so now.
618 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
619 if (TLI->ExpandInlineAsm(CI)) {
620 // Avoid invalidating the iterator.
621 CurInstIterator = BB->begin();
622 // Avoid processing instructions out of order, which could cause
623 // reuse before a value is defined.
624 SunkAddrs.clear();
625 return true;
626 }
627 // Sink address computing for memory operands into the block.
628 if (OptimizeInlineAsmInst(CI))
629 return true;
630 }
631
Eric Christopher040056f2010-03-11 02:41:03 +0000632 // Lower all uses of llvm.objectsize.*
633 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
634 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000635 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000636 const Type *ReturnTy = CI->getType();
637 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000638
639 // Substituting this can cause recursive simplifications, which can
640 // invalidate our iterator. Use a WeakVH to hold onto it in case this
641 // happens.
642 WeakVH IterHandle(CurInstIterator);
643
644 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
645
646 // If the iterator instruction was recursively deleted, start over at the
647 // start of the block.
648 if (IterHandle != CurInstIterator)
649 CurInstIterator = BB->begin();
Eric Christopher040056f2010-03-11 02:41:03 +0000650 return true;
651 }
652
653 // From here on out we're working with named functions.
654 if (CI->getCalledFunction() == 0) return false;
655
656 // We'll need TargetData from here on out.
657 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
658 if (!TD) return false;
659
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000660 // Lower all default uses of _chk calls. This is very similar
661 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000662 // that have the default "don't know" as the objectsize. Anything else
663 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000664 CodeGenPrepareFortifiedLibCalls Simplifier;
665 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000666}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000667
Chris Lattner88a5c832008-11-25 07:09:13 +0000668//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000669// Memory Optimization
670//===----------------------------------------------------------------------===//
671
Chris Lattnerdd77df32007-04-13 20:30:56 +0000672/// IsNonLocalValue - Return true if the specified values are defined in a
673/// different basic block than BB.
674static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
675 if (Instruction *I = dyn_cast<Instruction>(V))
676 return I->getParent() != BB;
677 return false;
678}
679
Bob Wilson4a8ee232009-12-03 21:47:07 +0000680/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000681/// addressing modes that can do significant amounts of computation. As such,
682/// instruction selection will try to get the load or store to do as much
683/// computation as possible for the program. The problem is that isel can only
684/// see within a single block. As such, we sink as much legal addressing mode
685/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000686///
687/// This method is used to optimize both load/store and inline asms with memory
688/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000689bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000690 const Type *AccessTy,
691 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000692 Value *Repl = Addr;
693
Owen Andersond2f41742010-11-19 22:15:03 +0000694 // Try to collapse single-value PHI nodes. This is necessary to undo
695 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000696 SmallVector<Value*, 8> worklist;
697 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000698 worklist.push_back(Addr);
699
700 // Use a worklist to iteratively look through PHI nodes, and ensure that
701 // the addressing mode obtained from the non-PHI roots of the graph
702 // are equivalent.
703 Value *Consensus = 0;
704 unsigned NumUses = 0;
705 SmallVector<Instruction*, 16> AddrModeInsts;
706 ExtAddrMode AddrMode;
707 while (!worklist.empty()) {
708 Value *V = worklist.back();
709 worklist.pop_back();
710
711 // Break use-def graph loops.
712 if (Visited.count(V)) {
713 Consensus = 0;
714 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000715 }
716
Owen Anderson35bf4d62010-11-27 08:15:55 +0000717 Visited.insert(V);
718
719 // For a PHI node, push all of its incoming values.
720 if (PHINode *P = dyn_cast<PHINode>(V)) {
721 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
722 worklist.push_back(P->getIncomingValue(i));
723 continue;
724 }
725
726 // For non-PHIs, determine the addressing mode being computed.
727 SmallVector<Instruction*, 16> NewAddrModeInsts;
728 ExtAddrMode NewAddrMode =
729 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
730 NewAddrModeInsts, *TLI);
731
732 // Ensure that the obtained addressing mode is equivalent to that obtained
733 // for all other roots of the PHI traversal. Also, when choosing one
734 // such root as representative, select the one with the most uses in order
735 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
736 if (!Consensus || NewAddrMode == AddrMode) {
737 if (V->getNumUses() > NumUses) {
738 Consensus = V;
739 NumUses = V->getNumUses();
740 AddrMode = NewAddrMode;
741 AddrModeInsts = NewAddrModeInsts;
742 }
743 continue;
744 }
745
746 Consensus = 0;
747 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000748 }
749
Owen Anderson35bf4d62010-11-27 08:15:55 +0000750 // If the addressing mode couldn't be determined, or if multiple different
751 // ones were determined, bail out now.
752 if (!Consensus) return false;
753
Chris Lattnerdd77df32007-04-13 20:30:56 +0000754 // Check to see if any of the instructions supersumed by this addr mode are
755 // non-local to I's BB.
756 bool AnyNonLocal = false;
757 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000758 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000759 AnyNonLocal = true;
760 break;
761 }
762 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000763
Chris Lattnerdd77df32007-04-13 20:30:56 +0000764 // If all the instructions matched are already in this BB, don't do anything.
765 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000766 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000767 return false;
768 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000769
Chris Lattnerdd77df32007-04-13 20:30:56 +0000770 // Insert this computation right after this user. Since our caller is
771 // scanning from the top of the BB to the bottom, reuse of the expr are
772 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000773 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000774
Chris Lattnerdd77df32007-04-13 20:30:56 +0000775 // Now that we determined the addressing expression we want to use and know
776 // that we have to sink it into this block. Check to see if we have already
777 // done this for some other load/store instr in this block. If so, reuse the
778 // computation.
779 Value *&SunkAddr = SunkAddrs[Addr];
780 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000781 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000782 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000783 if (SunkAddr->getType() != Addr->getType())
784 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
785 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000786 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000787 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000788 const Type *IntPtrTy =
789 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000790
Chris Lattnerdd77df32007-04-13 20:30:56 +0000791 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000792
793 // Start with the base register. Do this first so that subsequent address
794 // matching finds it last, which will prevent it from trying to match it
795 // as the scaled value in case it happens to be a mul. That would be
796 // problematic if we've sunk a different mul for the scale, because then
797 // we'd end up sinking both muls.
798 if (AddrMode.BaseReg) {
799 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000800 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000801 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
802 if (V->getType() != IntPtrTy)
803 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
804 "sunkaddr", InsertPt);
805 Result = V;
806 }
807
808 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000809 if (AddrMode.Scale) {
810 Value *V = AddrMode.ScaledReg;
811 if (V->getType() == IntPtrTy) {
812 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000813 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000814 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
815 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
816 cast<IntegerType>(V->getType())->getBitWidth()) {
817 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
818 } else {
819 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
820 }
821 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000822 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000823 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000824 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000825 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000826 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000827 else
828 Result = V;
829 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000830
Chris Lattnerdd77df32007-04-13 20:30:56 +0000831 // Add in the BaseGV if present.
832 if (AddrMode.BaseGV) {
833 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
834 InsertPt);
835 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000836 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000837 else
838 Result = V;
839 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000840
Chris Lattnerdd77df32007-04-13 20:30:56 +0000841 // Add in the Base Offset if present.
842 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000843 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000844 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000845 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000846 else
847 Result = V;
848 }
849
850 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000851 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000852 else
853 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
854 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000855
Owen Andersond2f41742010-11-19 22:15:03 +0000856 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000857
Owen Andersond2f41742010-11-19 22:15:03 +0000858 if (Repl->use_empty()) {
859 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000860 // This address is now available for reassignment, so erase the table entry;
861 // we don't want to match some completely different instruction.
862 SunkAddrs[Addr] = 0;
863 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000864 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000865 return true;
866}
867
Evan Cheng9bf12b52008-02-26 02:42:37 +0000868/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000869/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000870/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +0000871bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000872 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000873
Chris Lattner75796092011-01-15 07:14:54 +0000874 TargetLowering::AsmOperandInfoVector
875 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000876 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000877 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
878 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
879
Evan Cheng9bf12b52008-02-26 02:42:37 +0000880 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000881 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000882
Eli Friedman9ec80952008-02-26 18:37:49 +0000883 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
884 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +0000885 Value *OpVal = CS->getArgOperand(ArgNo++);
886 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000887 } else if (OpInfo.Type == InlineAsm::isInput)
888 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000889 }
890
891 return MadeChange;
892}
893
Dan Gohmanb00f2362009-10-16 20:59:35 +0000894/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
895/// basic block as the load, unless conditions are unfavorable. This allows
896/// SelectionDAG to fold the extend into the load.
897///
898bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
899 // Look for a load being extended.
900 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
901 if (!LI) return false;
902
903 // If they're already in the same block, there's nothing to do.
904 if (LI->getParent() == I->getParent())
905 return false;
906
907 // If the load has other users and the truncate is not free, this probably
908 // isn't worthwhile.
909 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000910 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
911 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000912 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000913 return false;
914
915 // Check whether the target supports casts folded into loads.
916 unsigned LType;
917 if (isa<ZExtInst>(I))
918 LType = ISD::ZEXTLOAD;
919 else {
920 assert(isa<SExtInst>(I) && "Unexpected ext type!");
921 LType = ISD::SEXTLOAD;
922 }
923 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
924 return false;
925
926 // Move the extend into the same block as the load, so that SelectionDAG
927 // can fold it.
928 I->removeFromParent();
929 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000930 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000931 return true;
932}
933
Evan Chengbdcb7262007-12-05 23:58:20 +0000934bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
935 BasicBlock *DefBB = I->getParent();
936
Bob Wilson9120f5c2010-09-21 21:44:14 +0000937 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000938 // other uses of the source with result of extension.
939 Value *Src = I->getOperand(0);
940 if (Src->hasOneUse())
941 return false;
942
Evan Cheng696e5c02007-12-13 07:50:36 +0000943 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000944 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000945 return false;
946
Evan Cheng772de512007-12-12 00:51:06 +0000947 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000948 // this block.
949 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000950 return false;
951
Evan Chengbdcb7262007-12-05 23:58:20 +0000952 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000953 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000954 UI != E; ++UI) {
955 Instruction *User = cast<Instruction>(*UI);
956
957 // Figure out which BB this ext is used in.
958 BasicBlock *UserBB = User->getParent();
959 if (UserBB == DefBB) continue;
960 DefIsLiveOut = true;
961 break;
962 }
963 if (!DefIsLiveOut)
964 return false;
965
Evan Cheng765dff22007-12-12 02:53:41 +0000966 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000967 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000968 UI != E; ++UI) {
969 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000970 BasicBlock *UserBB = User->getParent();
971 if (UserBB == DefBB) continue;
972 // Be conservative. We don't want this xform to end up introducing
973 // reloads just before load / store instructions.
974 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000975 return false;
976 }
977
Evan Chengbdcb7262007-12-05 23:58:20 +0000978 // InsertedTruncs - Only insert one trunc in each block once.
979 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
980
981 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000982 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000983 UI != E; ++UI) {
984 Use &TheUse = UI.getUse();
985 Instruction *User = cast<Instruction>(*UI);
986
987 // Figure out which BB this ext is used in.
988 BasicBlock *UserBB = User->getParent();
989 if (UserBB == DefBB) continue;
990
991 // Both src and def are live in this block. Rewrite the use.
992 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
993
994 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000995 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000996
Evan Chengbdcb7262007-12-05 23:58:20 +0000997 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
998 }
999
1000 // Replace a use of the {s|z}ext source with a use of the result.
1001 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001002 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001003 MadeChange = true;
1004 }
1005
1006 return MadeChange;
1007}
1008
Cameron Zwarichc0611012011-01-06 02:37:26 +00001009bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1010 bool MadeChange = false;
1011
1012 if (PHINode *P = dyn_cast<PHINode>(I)) {
1013 // It is possible for very late stage optimizations (such as SimplifyCFG)
1014 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1015 // trivial PHI, go ahead and zap it here.
1016 if (Value *V = SimplifyInstruction(P)) {
1017 P->replaceAllUsesWith(V);
1018 P->eraseFromParent();
1019 ++NumPHIsElim;
1020 }
1021 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1022 // If the source of the cast is a constant, then this should have
1023 // already been constant folded. The only reason NOT to constant fold
1024 // it is if something (e.g. LSR) was careful to place the constant
1025 // evaluation in a block other than then one that uses it (e.g. to hoist
1026 // the address of globals out of a loop). If this is the case, we don't
1027 // want to forward-subst the cast.
1028 if (isa<Constant>(CI->getOperand(0)))
1029 return false;
1030
1031 bool Change = false;
1032 if (TLI) {
1033 Change = OptimizeNoopCopyExpression(CI, *TLI);
1034 MadeChange |= Change;
1035 }
1036
1037 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
1038 MadeChange |= MoveExtToFormExtLoad(I);
1039 MadeChange |= OptimizeExtUses(I);
1040 }
1041 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1042 MadeChange |= OptimizeCmpExpression(CI);
1043 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1044 if (TLI)
1045 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1046 SunkAddrs);
1047 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1048 if (TLI)
1049 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1050 SI->getOperand(0)->getType(),
1051 SunkAddrs);
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001052 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1053 if (GEPI->hasAllZeroIndices()) {
1054 /// The GEP operand must be a pointer, so must its result -> BitCast
1055 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1056 GEPI->getName(), GEPI);
1057 GEPI->replaceAllUsesWith(NC);
1058 GEPI->eraseFromParent();
1059 ++NumGEPsElim;
1060 MadeChange = true;
1061 OptimizeInst(NC);
1062 }
Cameron Zwarich6cf34ab2011-01-06 02:56:42 +00001063 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattner75796092011-01-15 07:14:54 +00001064 MadeChange |= OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001065 }
1066
1067 return MadeChange;
1068}
1069
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001070// In this pass we look for GEP and cast instructions that are used
1071// across basic blocks and rewrite them to improve basic-block-at-a-time
1072// selection.
1073bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1074 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001075
Evan Chengab631522008-12-19 18:03:11 +00001076 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +00001077 if (CriticalEdgeSplit) {
1078 TerminatorInst *BBTI = BB.getTerminator();
1079 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1080 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1081 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1082 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1083 SplitEdgeNicely(BBTI, i, BackEdges, this);
1084 }
Evan Chengab631522008-12-19 18:03:11 +00001085 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001086 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001087
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001088 SunkAddrs.clear();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001089
Chris Lattner75796092011-01-15 07:14:54 +00001090 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001091 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1092 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001093
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001094 return MadeChange;
1095}