blob: 1068108f07245cc5d325692208cc82bbba9b83ea [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 Lattnerdbe0dec2007-03-31 04:06:36 +000045using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000046using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047
Cameron Zwarich31ff1332011-01-05 17:27:27 +000048STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Cameron Zwarich073057f2011-01-05 17:47:38 +000049STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
50STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000051STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
52 "sunken Cmps");
53STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
54 "of sunken Casts");
55STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
56 "computations were sunk");
57STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
58STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000059
Evan Chenge1bcb442010-08-17 01:34:49 +000060static cl::opt<bool>
61CriticalEdgeSplit("cgp-critical-edge-splitting",
62 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000063 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000064
Eric Christopher692bf6b2008-09-24 05:32:41 +000065namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000066 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000067 /// TLI - Keep a pointer of a TargetLowering to consult for determining
68 /// transformation profitability.
69 const TargetLowering *TLI;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000070 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000071 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000072
73 /// BackEdges - Keep a set of all the loop back edges.
74 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000075 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000076
77 // Keeps track of non-local addresses that have been sunk into a block. This
78 // allows us to avoid inserting duplicate code for blocks with multiple
79 // load/stores of the same address.
80 DenseMap<Value*, Value*> SunkAddrs;
81
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000082 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000083 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000084 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000085 : FunctionPass(ID), TLI(tli) {
86 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
87 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000088 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000089
Andreas Neustifterad809812009-09-16 09:26:52 +000090 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +000091 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +000092 AU.addPreserved<ProfileInfo>();
93 }
94
Dan Gohmanaa0e5232010-02-05 19:24:11 +000095 virtual void releaseMemory() {
96 BackEdges.clear();
97 }
98
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000099 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000100 bool EliminateMostlyEmptyBlocks(Function &F);
101 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
102 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000103 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000104 bool OptimizeInst(Instruction *I);
Chris Lattner88a5c832008-11-25 07:09:13 +0000105 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
106 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000107 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
108 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +0000109 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000110 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000111 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +0000112 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000113 };
114}
Devang Patel794fd752007-05-01 21:15:47 +0000115
Devang Patel19974732007-05-03 01:11:54 +0000116char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000117INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000118 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000119
120FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
121 return new CodeGenPrepare(TLI);
122}
123
Evan Chengab631522008-12-19 18:03:11 +0000124/// findLoopBackEdges - Do a DFS walk to find loop back edges.
125///
Mike Stumpfe095f32009-05-04 18:40:41 +0000126void CodeGenPrepare::findLoopBackEdges(const Function &F) {
127 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
128 FindFunctionBackedges(F, Edges);
129
130 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000131}
132
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000133
134bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000135 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000136
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000137 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000138 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000139 // First pass, eliminate blocks that contain only PHI nodes and an
140 // unconditional branch.
141 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000142
Cameron Zwarich95bb0042011-01-04 04:43:31 +0000143 // Now find loop back edges, but only if they are being used to decide which
144 // critical edges to split.
145 if (CriticalEdgeSplit)
146 findLoopBackEdges(F);
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000147
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000148 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000149 while (MadeChange) {
150 MadeChange = false;
151 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
152 MadeChange |= OptimizeBlock(*BB);
153 EverMadeChange |= MadeChange;
154 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000155
156 SunkAddrs.clear();
157
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000158 return EverMadeChange;
159}
160
Dale Johannesen2d697242009-03-27 01:13:37 +0000161/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
162/// debug info directives, and an unconditional branch. Passes before isel
163/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
164/// isel. Start by eliminating these blocks so we can split them the way we
165/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000166bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
167 bool MadeChange = false;
168 // Note that this intentionally skips the entry block.
169 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
170 BasicBlock *BB = I++;
171
172 // If this block doesn't end with an uncond branch, ignore it.
173 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
174 if (!BI || !BI->isUnconditional())
175 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000176
Dale Johannesen2d697242009-03-27 01:13:37 +0000177 // If the instruction before the branch (skipping debug info) isn't a phi
178 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000179 BasicBlock::iterator BBI = BI;
180 if (BBI != BB->begin()) {
181 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000182 while (isa<DbgInfoIntrinsic>(BBI)) {
183 if (BBI == BB->begin())
184 break;
185 --BBI;
186 }
187 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
188 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000189 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000190
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000191 // Do not break infinite loops.
192 BasicBlock *DestBB = BI->getSuccessor(0);
193 if (DestBB == BB)
194 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000195
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000196 if (!CanMergeBlocks(BB, DestBB))
197 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000198
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000199 EliminateMostlyEmptyBlock(BB);
200 MadeChange = true;
201 }
202 return MadeChange;
203}
204
205/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
206/// single uncond branch between them, and BB contains no other non-phi
207/// instructions.
208bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
209 const BasicBlock *DestBB) const {
210 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
211 // the successor. If there are more complex condition (e.g. preheaders),
212 // don't mess around with them.
213 BasicBlock::const_iterator BBI = BB->begin();
214 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000215 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000216 UI != E; ++UI) {
217 const Instruction *User = cast<Instruction>(*UI);
218 if (User->getParent() != DestBB || !isa<PHINode>(User))
219 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000220 // If User is inside DestBB block and it is a PHINode then check
221 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000222 // a complex condition (e.g. preheaders) we want to avoid here.
223 if (User->getParent() == DestBB) {
224 if (const PHINode *UPN = dyn_cast<PHINode>(User))
225 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
226 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
227 if (Insn && Insn->getParent() == BB &&
228 Insn->getParent() != UPN->getIncomingBlock(I))
229 return false;
230 }
231 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000232 }
233 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000234
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000235 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
236 // and DestBB may have conflicting incoming values for the block. If so, we
237 // can't merge the block.
238 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
239 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000240
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000242 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000243 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
244 // It is faster to get preds from a PHI than with pred_iterator.
245 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
246 BBPreds.insert(BBPN->getIncomingBlock(i));
247 } else {
248 BBPreds.insert(pred_begin(BB), pred_end(BB));
249 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000250
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 // Walk the preds of DestBB.
252 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
253 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
254 if (BBPreds.count(Pred)) { // Common predecessor?
255 BBI = DestBB->begin();
256 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
257 const Value *V1 = PN->getIncomingValueForBlock(Pred);
258 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000259
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 // If V2 is a phi node in BB, look up what the mapped value will be.
261 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
262 if (V2PN->getParent() == BB)
263 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000264
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000265 // If there is a conflict, bail out.
266 if (V1 != V2) return false;
267 }
268 }
269 }
270
271 return true;
272}
273
274
275/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
276/// an unconditional branch in it.
277void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
278 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
279 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
David Greene68d67fd2010-01-05 01:27:11 +0000281 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000282
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000283 // If the destination block has a single pred, then this is a trivial edge,
284 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000285 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000286 if (SinglePred != DestBB) {
287 // Remember if SinglePred was the entry block of the function. If so, we
288 // will need to move BB back to the entry position.
289 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000290 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000291
Chris Lattnerf5102a02008-11-28 19:54:49 +0000292 if (isEntry && BB != &BB->getParent()->getEntryBlock())
293 BB->moveBefore(&BB->getParent()->getEntryBlock());
294
David Greene68d67fd2010-01-05 01:27:11 +0000295 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000296 return;
297 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000298 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
301 // to handle the new incoming edges it is about to have.
302 PHINode *PN;
303 for (BasicBlock::iterator BBI = DestBB->begin();
304 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
305 // Remove the incoming value for BB, and remember it.
306 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000307
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000308 // Two options: either the InVal is a phi node defined in BB or it is some
309 // value that dominates BB.
310 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
311 if (InValPhi && InValPhi->getParent() == BB) {
312 // Add all of the input values of the input PHI as inputs of this phi.
313 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
314 PN->addIncoming(InValPhi->getIncomingValue(i),
315 InValPhi->getIncomingBlock(i));
316 } else {
317 // Otherwise, add one instance of the dominating value for each edge that
318 // we will be adding.
319 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
320 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
321 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
322 } else {
323 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
324 PN->addIncoming(InVal, *PI);
325 }
326 }
327 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000328
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000329 // The PHIs are now updated, change everything that refers to BB to use
330 // DestBB and remove BB.
331 BB->replaceAllUsesWith(DestBB);
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000332 if (DT) {
333 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
334 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
335 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
336 DT->changeImmediateDominator(DestBB, NewIDom);
337 DT->eraseNode(BB);
338 }
Evan Cheng04149f72009-12-17 09:39:49 +0000339 if (PFI) {
340 PFI->replaceAllUses(BB, DestBB);
341 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000342 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000343 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000344 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000345
David Greene68d67fd2010-01-05 01:27:11 +0000346 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000347}
348
Chris Lattner98d5c312010-02-13 05:35:08 +0000349/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
350/// lives in to see if there is a block that we can reuse as a critical edge
351/// from TIBB.
352static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
353 BasicBlock *Dest = DestPHI->getParent();
354
355 /// TIPHIValues - This array is lazily computed to determine the values of
356 /// PHIs in Dest that TI would provide.
357 SmallVector<Value*, 32> TIPHIValues;
358
359 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
360 unsigned TIBBEntryNo = 0;
361
362 // Check to see if Dest has any blocks that can be used as a split edge for
363 // this terminator.
364 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
365 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
366 // To be usable, the pred has to end with an uncond branch to the dest.
367 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
368 if (!PredBr || !PredBr->isUnconditional())
369 continue;
370 // Must be empty other than the branch and debug info.
371 BasicBlock::iterator I = Pred->begin();
372 while (isa<DbgInfoIntrinsic>(I))
373 I++;
374 if (&*I != PredBr)
375 continue;
376 // Cannot be the entry block; its label does not get emitted.
377 if (Pred == &Dest->getParent()->getEntryBlock())
378 continue;
379
380 // Finally, since we know that Dest has phi nodes in it, we have to make
381 // sure that jumping to Pred will have the same effect as going to Dest in
382 // terms of PHI values.
383 PHINode *PN;
384 unsigned PHINo = 0;
385 unsigned PredEntryNo = pi;
386
387 bool FoundMatch = true;
388 for (BasicBlock::iterator I = Dest->begin();
389 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
390 if (PHINo == TIPHIValues.size()) {
391 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
392 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
393 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
394 }
395
396 // If the PHI entry doesn't work, we can't use this pred.
397 if (PN->getIncomingBlock(PredEntryNo) != Pred)
398 PredEntryNo = PN->getBasicBlockIndex(Pred);
399
400 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
401 FoundMatch = false;
402 break;
403 }
404 }
405
406 // If we found a workable predecessor, change TI to branch to Succ.
407 if (FoundMatch)
408 return Pred;
409 }
410 return 0;
411}
412
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000413
Chris Lattnerebe80752007-12-24 19:32:55 +0000414/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000415/// successor if it will improve codegen. We only do this if the successor has
416/// phi nodes (otherwise critical edges are ok). If there is already another
417/// predecessor of the succ that is empty (and thus has no phi nodes), use it
418/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000419static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000420 SmallSet<std::pair<const BasicBlock*,
421 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000422 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000423 BasicBlock *TIBB = TI->getParent();
424 BasicBlock *Dest = TI->getSuccessor(SuccNum);
425 assert(isa<PHINode>(Dest->begin()) &&
426 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000427 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428
Evan Chengfc0b80d2009-03-13 22:59:14 +0000429 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000430 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000431 if (Invoke->getSuccessor(1) == Dest)
432 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000433
Chris Lattnerebe80752007-12-24 19:32:55 +0000434 // As a hack, never split backedges of loops. Even though the copy for any
435 // PHIs inserted on the backedge would be dead for exits from the loop, we
436 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000437 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000438 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000439
Chris Lattnerc09687b2010-02-13 19:07:06 +0000440 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
441 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
442 if (PFI)
443 PFI->splitEdge(TIBB, Dest, ReuseBB);
444 Dest->removePredecessor(TIBB);
445 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000446 return;
447 }
448
Chris Lattnerc09687b2010-02-13 19:07:06 +0000449 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450}
451
Evan Chengab631522008-12-19 18:03:11 +0000452
Chris Lattnerdd77df32007-04-13 20:30:56 +0000453/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000454/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
455/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000456/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457///
458/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000459///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000460static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000462 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
463 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
Chris Lattnerdd77df32007-04-13 20:30:56 +0000465 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000466 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000467 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000468
Chris Lattnerdd77df32007-04-13 20:30:56 +0000469 // If this is an extension, it will be a zero or sign extension, which
470 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000471 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdd77df32007-04-13 20:30:56 +0000473 // If these values will be promoted, find out what they will be promoted
474 // to. This helps us consider truncates on PPC as noop copies when they
475 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000476 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000477 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000478 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000479 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480
Chris Lattnerdd77df32007-04-13 20:30:56 +0000481 // If, after promotion, these are the same types, this is a noop copy.
482 if (SrcVT != DstVT)
483 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000486
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000487 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000488 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000490 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 UI != E; ) {
493 Use &TheUse = UI.getUse();
494 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 // Figure out which BB this cast is used in. For PHI's this is the
497 // appropriate predecessor block.
498 BasicBlock *UserBB = User->getParent();
499 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000500 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000502
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 // Preincrement use iterator so we don't invalidate it.
504 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506 // If this user is in the same block as the cast, don't change the cast.
507 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000508
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000509 // If we have already inserted a cast into this block, use it.
510 CastInst *&InsertedCast = InsertedCasts[UserBB];
511
512 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000513 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
515 InsertedCast =
516 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000517 InsertPt);
518 MadeChange = true;
519 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Dale Johannesence0b2372007-06-12 16:50:17 +0000521 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000522 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000523 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000524 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000526 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000527 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000528 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000529 MadeChange = true;
530 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000532 return MadeChange;
533}
534
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000536/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000537/// a clear win except on targets with multiple condition code registers
538/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000539///
540/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000541static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 /// InsertedCmp - Only insert a cmp in each block once.
545 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 UI != E; ) {
550 Use &TheUse = UI.getUse();
551 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 // Preincrement use iterator so we don't invalidate it.
554 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000555
Dale Johannesence0b2372007-06-12 16:50:17 +0000556 // Don't bother for PHI nodes.
557 if (isa<PHINode>(User))
558 continue;
559
560 // Figure out which BB this cmp is used in.
561 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000562
Dale Johannesence0b2372007-06-12 16:50:17 +0000563 // If this user is in the same block as the cmp, don't change the cmp.
564 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000565
Dale Johannesence0b2372007-06-12 16:50:17 +0000566 // If we have already inserted a cmp into this block, use it.
567 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
568
569 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000570 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000571
572 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000573 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000574 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000575 CI->getOperand(1), "", InsertPt);
576 MadeChange = true;
577 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000578
Dale Johannesence0b2372007-06-12 16:50:17 +0000579 // Replace a use of the cmp with a use of the new cmp.
580 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000581 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000582 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000583
Dale Johannesence0b2372007-06-12 16:50:17 +0000584 // If we removed all uses, nuke the cmp.
585 if (CI->use_empty())
586 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000587
Dale Johannesence0b2372007-06-12 16:50:17 +0000588 return MadeChange;
589}
590
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000591namespace {
592class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
593protected:
594 void replaceCall(Value *With) {
595 CI->replaceAllUsesWith(With);
596 CI->eraseFromParent();
597 }
598 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000599 if (ConstantInt *SizeCI =
600 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
601 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000602 return false;
603 }
604};
605} // end anonymous namespace
606
Eric Christopher040056f2010-03-11 02:41:03 +0000607bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000608 // Lower all uses of llvm.objectsize.*
609 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
610 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000611 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000612 const Type *ReturnTy = CI->getType();
613 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
614 CI->replaceAllUsesWith(RetVal);
615 CI->eraseFromParent();
616 return true;
617 }
618
619 // From here on out we're working with named functions.
620 if (CI->getCalledFunction() == 0) return false;
621
622 // We'll need TargetData from here on out.
623 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
624 if (!TD) return false;
625
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000626 // Lower all default uses of _chk calls. This is very similar
627 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000628 // that have the default "don't know" as the objectsize. Anything else
629 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000630 CodeGenPrepareFortifiedLibCalls Simplifier;
631 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000632}
Chris Lattner88a5c832008-11-25 07:09:13 +0000633//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000634// Memory Optimization
635//===----------------------------------------------------------------------===//
636
Chris Lattnerdd77df32007-04-13 20:30:56 +0000637/// IsNonLocalValue - Return true if the specified values are defined in a
638/// different basic block than BB.
639static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
640 if (Instruction *I = dyn_cast<Instruction>(V))
641 return I->getParent() != BB;
642 return false;
643}
644
Bob Wilson4a8ee232009-12-03 21:47:07 +0000645/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000646/// addressing modes that can do significant amounts of computation. As such,
647/// instruction selection will try to get the load or store to do as much
648/// computation as possible for the program. The problem is that isel can only
649/// see within a single block. As such, we sink as much legal addressing mode
650/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000651///
652/// This method is used to optimize both load/store and inline asms with memory
653/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000654bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000655 const Type *AccessTy,
656 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000657 Value *Repl = Addr;
658
Owen Andersond2f41742010-11-19 22:15:03 +0000659 // Try to collapse single-value PHI nodes. This is necessary to undo
660 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000661 SmallVector<Value*, 8> worklist;
662 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000663 worklist.push_back(Addr);
664
665 // Use a worklist to iteratively look through PHI nodes, and ensure that
666 // the addressing mode obtained from the non-PHI roots of the graph
667 // are equivalent.
668 Value *Consensus = 0;
669 unsigned NumUses = 0;
670 SmallVector<Instruction*, 16> AddrModeInsts;
671 ExtAddrMode AddrMode;
672 while (!worklist.empty()) {
673 Value *V = worklist.back();
674 worklist.pop_back();
675
676 // Break use-def graph loops.
677 if (Visited.count(V)) {
678 Consensus = 0;
679 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000680 }
681
Owen Anderson35bf4d62010-11-27 08:15:55 +0000682 Visited.insert(V);
683
684 // For a PHI node, push all of its incoming values.
685 if (PHINode *P = dyn_cast<PHINode>(V)) {
686 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
687 worklist.push_back(P->getIncomingValue(i));
688 continue;
689 }
690
691 // For non-PHIs, determine the addressing mode being computed.
692 SmallVector<Instruction*, 16> NewAddrModeInsts;
693 ExtAddrMode NewAddrMode =
694 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
695 NewAddrModeInsts, *TLI);
696
697 // Ensure that the obtained addressing mode is equivalent to that obtained
698 // for all other roots of the PHI traversal. Also, when choosing one
699 // such root as representative, select the one with the most uses in order
700 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
701 if (!Consensus || NewAddrMode == AddrMode) {
702 if (V->getNumUses() > NumUses) {
703 Consensus = V;
704 NumUses = V->getNumUses();
705 AddrMode = NewAddrMode;
706 AddrModeInsts = NewAddrModeInsts;
707 }
708 continue;
709 }
710
711 Consensus = 0;
712 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000713 }
714
Owen Anderson35bf4d62010-11-27 08:15:55 +0000715 // If the addressing mode couldn't be determined, or if multiple different
716 // ones were determined, bail out now.
717 if (!Consensus) return false;
718
Chris Lattnerdd77df32007-04-13 20:30:56 +0000719 // Check to see if any of the instructions supersumed by this addr mode are
720 // non-local to I's BB.
721 bool AnyNonLocal = false;
722 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000723 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724 AnyNonLocal = true;
725 break;
726 }
727 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000728
Chris Lattnerdd77df32007-04-13 20:30:56 +0000729 // If all the instructions matched are already in this BB, don't do anything.
730 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000731 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000732 return false;
733 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000734
Chris Lattnerdd77df32007-04-13 20:30:56 +0000735 // Insert this computation right after this user. Since our caller is
736 // scanning from the top of the BB to the bottom, reuse of the expr are
737 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000738 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000739
Chris Lattnerdd77df32007-04-13 20:30:56 +0000740 // Now that we determined the addressing expression we want to use and know
741 // that we have to sink it into this block. Check to see if we have already
742 // done this for some other load/store instr in this block. If so, reuse the
743 // computation.
744 Value *&SunkAddr = SunkAddrs[Addr];
745 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000746 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000747 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000748 if (SunkAddr->getType() != Addr->getType())
749 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
750 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000751 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000752 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000753 const Type *IntPtrTy =
754 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000755
Chris Lattnerdd77df32007-04-13 20:30:56 +0000756 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000757
758 // Start with the base register. Do this first so that subsequent address
759 // matching finds it last, which will prevent it from trying to match it
760 // as the scaled value in case it happens to be a mul. That would be
761 // problematic if we've sunk a different mul for the scale, because then
762 // we'd end up sinking both muls.
763 if (AddrMode.BaseReg) {
764 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000765 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000766 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
767 if (V->getType() != IntPtrTy)
768 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
769 "sunkaddr", InsertPt);
770 Result = V;
771 }
772
773 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000774 if (AddrMode.Scale) {
775 Value *V = AddrMode.ScaledReg;
776 if (V->getType() == IntPtrTy) {
777 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000778 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000779 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
780 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
781 cast<IntegerType>(V->getType())->getBitWidth()) {
782 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
783 } else {
784 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
785 }
786 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000787 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000788 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000789 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000790 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000791 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000792 else
793 Result = V;
794 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000795
Chris Lattnerdd77df32007-04-13 20:30:56 +0000796 // Add in the BaseGV if present.
797 if (AddrMode.BaseGV) {
798 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
799 InsertPt);
800 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000801 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000802 else
803 Result = V;
804 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000805
Chris Lattnerdd77df32007-04-13 20:30:56 +0000806 // Add in the Base Offset if present.
807 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000808 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000809 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000810 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000811 else
812 Result = V;
813 }
814
815 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000816 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000817 else
818 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
819 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000820
Owen Andersond2f41742010-11-19 22:15:03 +0000821 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000822
Owen Andersond2f41742010-11-19 22:15:03 +0000823 if (Repl->use_empty()) {
824 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000825 // This address is now available for reassignment, so erase the table entry;
826 // we don't want to match some completely different instruction.
827 SunkAddrs[Addr] = 0;
828 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000829 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +0000830 return true;
831}
832
Evan Cheng9bf12b52008-02-26 02:42:37 +0000833/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000834/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000835/// possible / profitable.
836bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
837 DenseMap<Value*,Value*> &SunkAddrs) {
838 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000839
John Thompson44ab89e2010-10-29 17:29:13 +0000840 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000841 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000842 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
843 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
844
Evan Cheng9bf12b52008-02-26 02:42:37 +0000845 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000846 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000847
Eli Friedman9ec80952008-02-26 18:37:49 +0000848 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
849 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000850 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000851 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000852 } else if (OpInfo.Type == InlineAsm::isInput)
853 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000854 }
855
856 return MadeChange;
857}
858
Dan Gohmanb00f2362009-10-16 20:59:35 +0000859/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
860/// basic block as the load, unless conditions are unfavorable. This allows
861/// SelectionDAG to fold the extend into the load.
862///
863bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
864 // Look for a load being extended.
865 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
866 if (!LI) return false;
867
868 // If they're already in the same block, there's nothing to do.
869 if (LI->getParent() == I->getParent())
870 return false;
871
872 // If the load has other users and the truncate is not free, this probably
873 // isn't worthwhile.
874 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000875 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
876 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000877 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000878 return false;
879
880 // Check whether the target supports casts folded into loads.
881 unsigned LType;
882 if (isa<ZExtInst>(I))
883 LType = ISD::ZEXTLOAD;
884 else {
885 assert(isa<SExtInst>(I) && "Unexpected ext type!");
886 LType = ISD::SEXTLOAD;
887 }
888 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
889 return false;
890
891 // Move the extend into the same block as the load, so that SelectionDAG
892 // can fold it.
893 I->removeFromParent();
894 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000895 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +0000896 return true;
897}
898
Evan Chengbdcb7262007-12-05 23:58:20 +0000899bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
900 BasicBlock *DefBB = I->getParent();
901
Bob Wilson9120f5c2010-09-21 21:44:14 +0000902 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000903 // other uses of the source with result of extension.
904 Value *Src = I->getOperand(0);
905 if (Src->hasOneUse())
906 return false;
907
Evan Cheng696e5c02007-12-13 07:50:36 +0000908 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000909 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000910 return false;
911
Evan Cheng772de512007-12-12 00:51:06 +0000912 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000913 // this block.
914 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000915 return false;
916
Evan Chengbdcb7262007-12-05 23:58:20 +0000917 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000918 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000919 UI != E; ++UI) {
920 Instruction *User = cast<Instruction>(*UI);
921
922 // Figure out which BB this ext is used in.
923 BasicBlock *UserBB = User->getParent();
924 if (UserBB == DefBB) continue;
925 DefIsLiveOut = true;
926 break;
927 }
928 if (!DefIsLiveOut)
929 return false;
930
Evan Cheng765dff22007-12-12 02:53:41 +0000931 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000932 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000933 UI != E; ++UI) {
934 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000935 BasicBlock *UserBB = User->getParent();
936 if (UserBB == DefBB) continue;
937 // Be conservative. We don't want this xform to end up introducing
938 // reloads just before load / store instructions.
939 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000940 return false;
941 }
942
Evan Chengbdcb7262007-12-05 23:58:20 +0000943 // InsertedTruncs - Only insert one trunc in each block once.
944 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
945
946 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000947 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000948 UI != E; ++UI) {
949 Use &TheUse = UI.getUse();
950 Instruction *User = cast<Instruction>(*UI);
951
952 // Figure out which BB this ext is used in.
953 BasicBlock *UserBB = User->getParent();
954 if (UserBB == DefBB) continue;
955
956 // Both src and def are live in this block. Rewrite the use.
957 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
958
959 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000960 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000961
Evan Chengbdcb7262007-12-05 23:58:20 +0000962 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
963 }
964
965 // Replace a use of the {s|z}ext source with a use of the result.
966 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000967 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +0000968 MadeChange = true;
969 }
970
971 return MadeChange;
972}
973
Cameron Zwarichc0611012011-01-06 02:37:26 +0000974bool CodeGenPrepare::OptimizeInst(Instruction *I) {
975 bool MadeChange = false;
976
977 if (PHINode *P = dyn_cast<PHINode>(I)) {
978 // It is possible for very late stage optimizations (such as SimplifyCFG)
979 // to introduce PHI nodes too late to be cleaned up. If we detect such a
980 // trivial PHI, go ahead and zap it here.
981 if (Value *V = SimplifyInstruction(P)) {
982 P->replaceAllUsesWith(V);
983 P->eraseFromParent();
984 ++NumPHIsElim;
985 }
986 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
987 // If the source of the cast is a constant, then this should have
988 // already been constant folded. The only reason NOT to constant fold
989 // it is if something (e.g. LSR) was careful to place the constant
990 // evaluation in a block other than then one that uses it (e.g. to hoist
991 // the address of globals out of a loop). If this is the case, we don't
992 // want to forward-subst the cast.
993 if (isa<Constant>(CI->getOperand(0)))
994 return false;
995
996 bool Change = false;
997 if (TLI) {
998 Change = OptimizeNoopCopyExpression(CI, *TLI);
999 MadeChange |= Change;
1000 }
1001
1002 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
1003 MadeChange |= MoveExtToFormExtLoad(I);
1004 MadeChange |= OptimizeExtUses(I);
1005 }
1006 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1007 MadeChange |= OptimizeCmpExpression(CI);
1008 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1009 if (TLI)
1010 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1011 SunkAddrs);
1012 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1013 if (TLI)
1014 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1015 SI->getOperand(0)->getType(),
1016 SunkAddrs);
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001017 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1018 if (GEPI->hasAllZeroIndices()) {
1019 /// The GEP operand must be a pointer, so must its result -> BitCast
1020 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1021 GEPI->getName(), GEPI);
1022 GEPI->replaceAllUsesWith(NC);
1023 GEPI->eraseFromParent();
1024 ++NumGEPsElim;
1025 MadeChange = true;
1026 OptimizeInst(NC);
1027 }
Cameron Zwarich6cf34ab2011-01-06 02:56:42 +00001028 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1029 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1030 // Sink address computing for memory operands into the block.
1031 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1032 } else {
1033 MadeChange |= OptimizeCallInst(CI);
1034 }
Cameron Zwarichc0611012011-01-06 02:37:26 +00001035 }
1036
1037 return MadeChange;
1038}
1039
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001040// In this pass we look for GEP and cast instructions that are used
1041// across basic blocks and rewrite them to improve basic-block-at-a-time
1042// selection.
1043bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1044 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001045
Evan Chengab631522008-12-19 18:03:11 +00001046 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +00001047 if (CriticalEdgeSplit) {
1048 TerminatorInst *BBTI = BB.getTerminator();
1049 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1050 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1051 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1052 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1053 SplitEdgeNicely(BBTI, i, BackEdges, this);
1054 }
Evan Chengab631522008-12-19 18:03:11 +00001055 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001056 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001057
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001058 SunkAddrs.clear();
Eric Christopher692bf6b2008-09-24 05:32:41 +00001059
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001060 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1061 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001062
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001063 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001064 // If we found an inline asm expession, and if the target knows how to
1065 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +00001066 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1067 if (TLI->ExpandInlineAsm(CI)) {
1068 BBI = BB.begin();
1069 // Avoid processing instructions out of order, which could cause
1070 // reuse before a value is defined.
1071 SunkAddrs.clear();
1072 } else
1073 // Sink address computing for memory operands into the block.
1074 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +00001075 } else {
1076 // Other CallInst optimizations that don't need to muck with the
1077 // enclosing iterator here.
1078 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +00001079 }
Cameron Zwarichc0611012011-01-06 02:37:26 +00001080 } else {
1081 MadeChange |= OptimizeInst(I);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001082 }
1083 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001084
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001085 return MadeChange;
1086}