blob: 880a4e5eb890551e6144e146937f52a329c6afd5 [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"
Andreas Neustifterad809812009-09-16 09:26:52 +000025#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000028#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000030#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000031#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000034#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000035#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000036#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000037#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000039#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000040#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000041#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000042#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000044using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000045
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000046STATISTIC(NumElim, "Number of blocks eliminated");
47
Evan Chenge1bcb442010-08-17 01:34:49 +000048static cl::opt<bool>
49CriticalEdgeSplit("cgp-critical-edge-splitting",
50 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000051 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000052
Eric Christopher692bf6b2008-09-24 05:32:41 +000053namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000054 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000055 /// TLI - Keep a pointer of a TargetLowering to consult for determining
56 /// transformation profitability.
57 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000058 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000059
60 /// BackEdges - Keep a set of all the loop back edges.
61 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000062 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000063 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000064 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000065 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson90c579d2010-08-06 18:33:48 +000066 : FunctionPass(ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000067 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000068
Andreas Neustifterad809812009-09-16 09:26:52 +000069 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addPreserved<ProfileInfo>();
71 }
72
Dan Gohmanaa0e5232010-02-05 19:24:11 +000073 virtual void releaseMemory() {
74 BackEdges.clear();
75 }
76
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000078 bool EliminateMostlyEmptyBlocks(Function &F);
79 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
80 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000081 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000082 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
83 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000084 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
85 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +000086 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +000087 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000088 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000089 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000090 };
91}
Devang Patel794fd752007-05-01 21:15:47 +000092
Devang Patel19974732007-05-03 01:11:54 +000093char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000094INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
95 "Optimize for code generation", false, false);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000096
97FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
98 return new CodeGenPrepare(TLI);
99}
100
Evan Chengab631522008-12-19 18:03:11 +0000101/// findLoopBackEdges - Do a DFS walk to find loop back edges.
102///
Mike Stumpfe095f32009-05-04 18:40:41 +0000103void CodeGenPrepare::findLoopBackEdges(const Function &F) {
104 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
105 FindFunctionBackedges(F, Edges);
106
107 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000108}
109
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110
111bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000112 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000113
Evan Cheng04149f72009-12-17 09:39:49 +0000114 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000115 // First pass, eliminate blocks that contain only PHI nodes and an
116 // unconditional branch.
117 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000118
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000119 // Now find loop back edges.
120 findLoopBackEdges(F);
121
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000122 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000123 while (MadeChange) {
124 MadeChange = false;
125 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
126 MadeChange |= OptimizeBlock(*BB);
127 EverMadeChange |= MadeChange;
128 }
129 return EverMadeChange;
130}
131
Dale Johannesen2d697242009-03-27 01:13:37 +0000132/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
133/// debug info directives, and an unconditional branch. Passes before isel
134/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
135/// isel. Start by eliminating these blocks so we can split them the way we
136/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000137bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
138 bool MadeChange = false;
139 // Note that this intentionally skips the entry block.
140 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
141 BasicBlock *BB = I++;
142
143 // If this block doesn't end with an uncond branch, ignore it.
144 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
145 if (!BI || !BI->isUnconditional())
146 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000147
Dale Johannesen2d697242009-03-27 01:13:37 +0000148 // If the instruction before the branch (skipping debug info) isn't a phi
149 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000150 BasicBlock::iterator BBI = BI;
151 if (BBI != BB->begin()) {
152 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000153 while (isa<DbgInfoIntrinsic>(BBI)) {
154 if (BBI == BB->begin())
155 break;
156 --BBI;
157 }
158 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
159 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000160 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000161
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000162 // Do not break infinite loops.
163 BasicBlock *DestBB = BI->getSuccessor(0);
164 if (DestBB == BB)
165 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000166
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000167 if (!CanMergeBlocks(BB, DestBB))
168 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000169
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000170 EliminateMostlyEmptyBlock(BB);
171 MadeChange = true;
172 }
173 return MadeChange;
174}
175
176/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
177/// single uncond branch between them, and BB contains no other non-phi
178/// instructions.
179bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
180 const BasicBlock *DestBB) const {
181 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
182 // the successor. If there are more complex condition (e.g. preheaders),
183 // don't mess around with them.
184 BasicBlock::const_iterator BBI = BB->begin();
185 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000186 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000187 UI != E; ++UI) {
188 const Instruction *User = cast<Instruction>(*UI);
189 if (User->getParent() != DestBB || !isa<PHINode>(User))
190 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000191 // If User is inside DestBB block and it is a PHINode then check
192 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000193 // a complex condition (e.g. preheaders) we want to avoid here.
194 if (User->getParent() == DestBB) {
195 if (const PHINode *UPN = dyn_cast<PHINode>(User))
196 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
197 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
198 if (Insn && Insn->getParent() == BB &&
199 Insn->getParent() != UPN->getIncomingBlock(I))
200 return false;
201 }
202 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 }
204 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000205
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000206 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
207 // and DestBB may have conflicting incoming values for the block. If so, we
208 // can't merge the block.
209 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
210 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000211
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000212 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000213 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000214 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
215 // It is faster to get preds from a PHI than with pred_iterator.
216 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
217 BBPreds.insert(BBPN->getIncomingBlock(i));
218 } else {
219 BBPreds.insert(pred_begin(BB), pred_end(BB));
220 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000222 // Walk the preds of DestBB.
223 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
224 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
225 if (BBPreds.count(Pred)) { // Common predecessor?
226 BBI = DestBB->begin();
227 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
228 const Value *V1 = PN->getIncomingValueForBlock(Pred);
229 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000230
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000231 // If V2 is a phi node in BB, look up what the mapped value will be.
232 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
233 if (V2PN->getParent() == BB)
234 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000235
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000236 // If there is a conflict, bail out.
237 if (V1 != V2) return false;
238 }
239 }
240 }
241
242 return true;
243}
244
245
246/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
247/// an unconditional branch in it.
248void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
249 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
250 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000251
David Greene68d67fd2010-01-05 01:27:11 +0000252 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000253
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000254 // If the destination block has a single pred, then this is a trivial edge,
255 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000256 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000257 if (SinglePred != DestBB) {
258 // Remember if SinglePred was the entry block of the function. If so, we
259 // will need to move BB back to the entry position.
260 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000261 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000262
Chris Lattnerf5102a02008-11-28 19:54:49 +0000263 if (isEntry && BB != &BB->getParent()->getEntryBlock())
264 BB->moveBefore(&BB->getParent()->getEntryBlock());
265
David Greene68d67fd2010-01-05 01:27:11 +0000266 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000267 return;
268 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000269 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000270
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000271 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
272 // to handle the new incoming edges it is about to have.
273 PHINode *PN;
274 for (BasicBlock::iterator BBI = DestBB->begin();
275 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
276 // Remove the incoming value for BB, and remember it.
277 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000278
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000279 // Two options: either the InVal is a phi node defined in BB or it is some
280 // value that dominates BB.
281 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
282 if (InValPhi && InValPhi->getParent() == BB) {
283 // Add all of the input values of the input PHI as inputs of this phi.
284 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
285 PN->addIncoming(InValPhi->getIncomingValue(i),
286 InValPhi->getIncomingBlock(i));
287 } else {
288 // Otherwise, add one instance of the dominating value for each edge that
289 // we will be adding.
290 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
291 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
292 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
293 } else {
294 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
295 PN->addIncoming(InVal, *PI);
296 }
297 }
298 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 // The PHIs are now updated, change everything that refers to BB to use
301 // DestBB and remove BB.
302 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000303 if (PFI) {
304 PFI->replaceAllUses(BB, DestBB);
305 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000306 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307 BB->eraseFromParent();
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +0000308 ++NumElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000309
David Greene68d67fd2010-01-05 01:27:11 +0000310 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000311}
312
Chris Lattner98d5c312010-02-13 05:35:08 +0000313/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
314/// lives in to see if there is a block that we can reuse as a critical edge
315/// from TIBB.
316static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
317 BasicBlock *Dest = DestPHI->getParent();
318
319 /// TIPHIValues - This array is lazily computed to determine the values of
320 /// PHIs in Dest that TI would provide.
321 SmallVector<Value*, 32> TIPHIValues;
322
323 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
324 unsigned TIBBEntryNo = 0;
325
326 // Check to see if Dest has any blocks that can be used as a split edge for
327 // this terminator.
328 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
329 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
330 // To be usable, the pred has to end with an uncond branch to the dest.
331 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
332 if (!PredBr || !PredBr->isUnconditional())
333 continue;
334 // Must be empty other than the branch and debug info.
335 BasicBlock::iterator I = Pred->begin();
336 while (isa<DbgInfoIntrinsic>(I))
337 I++;
338 if (&*I != PredBr)
339 continue;
340 // Cannot be the entry block; its label does not get emitted.
341 if (Pred == &Dest->getParent()->getEntryBlock())
342 continue;
343
344 // Finally, since we know that Dest has phi nodes in it, we have to make
345 // sure that jumping to Pred will have the same effect as going to Dest in
346 // terms of PHI values.
347 PHINode *PN;
348 unsigned PHINo = 0;
349 unsigned PredEntryNo = pi;
350
351 bool FoundMatch = true;
352 for (BasicBlock::iterator I = Dest->begin();
353 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
354 if (PHINo == TIPHIValues.size()) {
355 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
356 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
357 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
358 }
359
360 // If the PHI entry doesn't work, we can't use this pred.
361 if (PN->getIncomingBlock(PredEntryNo) != Pred)
362 PredEntryNo = PN->getBasicBlockIndex(Pred);
363
364 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
365 FoundMatch = false;
366 break;
367 }
368 }
369
370 // If we found a workable predecessor, change TI to branch to Succ.
371 if (FoundMatch)
372 return Pred;
373 }
374 return 0;
375}
376
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000377
Chris Lattnerebe80752007-12-24 19:32:55 +0000378/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000379/// successor if it will improve codegen. We only do this if the successor has
380/// phi nodes (otherwise critical edges are ok). If there is already another
381/// predecessor of the succ that is empty (and thus has no phi nodes), use it
382/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000383static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000384 SmallSet<std::pair<const BasicBlock*,
385 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000386 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000387 BasicBlock *TIBB = TI->getParent();
388 BasicBlock *Dest = TI->getSuccessor(SuccNum);
389 assert(isa<PHINode>(Dest->begin()) &&
390 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000391 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000392
Evan Chengfc0b80d2009-03-13 22:59:14 +0000393 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000394 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000395 if (Invoke->getSuccessor(1) == Dest)
396 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000397
Chris Lattnerebe80752007-12-24 19:32:55 +0000398 // As a hack, never split backedges of loops. Even though the copy for any
399 // PHIs inserted on the backedge would be dead for exits from the loop, we
400 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000401 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000402 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403
Chris Lattnerc09687b2010-02-13 19:07:06 +0000404 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
405 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
406 if (PFI)
407 PFI->splitEdge(TIBB, Dest, ReuseBB);
408 Dest->removePredecessor(TIBB);
409 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000410 return;
411 }
412
Chris Lattnerc09687b2010-02-13 19:07:06 +0000413 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000414}
415
Evan Chengab631522008-12-19 18:03:11 +0000416
Chris Lattnerdd77df32007-04-13 20:30:56 +0000417/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000418/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
419/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000420/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000421///
422/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000423///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000424static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000425 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000426 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
427 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428
Chris Lattnerdd77df32007-04-13 20:30:56 +0000429 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000430 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000431 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000432
Chris Lattnerdd77df32007-04-13 20:30:56 +0000433 // If this is an extension, it will be a zero or sign extension, which
434 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000435 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436
Chris Lattnerdd77df32007-04-13 20:30:56 +0000437 // If these values will be promoted, find out what they will be promoted
438 // to. This helps us consider truncates on PPC as noop copies when they
439 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000440 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000441 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000442 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000443 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdd77df32007-04-13 20:30:56 +0000445 // If, after promotion, these are the same types, this is a noop copy.
446 if (SrcVT != DstVT)
447 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000448
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000449 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000450
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000451 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000452 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456 UI != E; ) {
457 Use &TheUse = UI.getUse();
458 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000460 // Figure out which BB this cast is used in. For PHI's this is the
461 // appropriate predecessor block.
462 BasicBlock *UserBB = User->getParent();
463 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000464 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000465 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000466
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000467 // Preincrement use iterator so we don't invalidate it.
468 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 // If this user is in the same block as the cast, don't change the cast.
471 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 // If we have already inserted a cast into this block, use it.
474 CastInst *&InsertedCast = InsertedCasts[UserBB];
475
476 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000477 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
479 InsertedCast =
480 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 InsertPt);
482 MadeChange = true;
483 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Dale Johannesence0b2372007-06-12 16:50:17 +0000485 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 TheUse = InsertedCast;
487 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000490 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000492 MadeChange = true;
493 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495 return MadeChange;
496}
497
Eric Christopher692bf6b2008-09-24 05:32:41 +0000498/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000499/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000500/// a clear win except on targets with multiple condition code registers
501/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000502///
503/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000504static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000505 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Dale Johannesence0b2372007-06-12 16:50:17 +0000507 /// InsertedCmp - Only insert a cmp in each block once.
508 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000511 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000512 UI != E; ) {
513 Use &TheUse = UI.getUse();
514 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000515
Dale Johannesence0b2372007-06-12 16:50:17 +0000516 // Preincrement use iterator so we don't invalidate it.
517 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 // Don't bother for PHI nodes.
520 if (isa<PHINode>(User))
521 continue;
522
523 // Figure out which BB this cmp is used in.
524 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000525
Dale Johannesence0b2372007-06-12 16:50:17 +0000526 // If this user is in the same block as the cmp, don't change the cmp.
527 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 // If we have already inserted a cmp into this block, use it.
530 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
531
532 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000533 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
535 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000536 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000537 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 CI->getOperand(1), "", InsertPt);
539 MadeChange = true;
540 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // Replace a use of the cmp with a use of the new cmp.
543 TheUse = InsertedCmp;
544 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000545
Dale Johannesence0b2372007-06-12 16:50:17 +0000546 // If we removed all uses, nuke the cmp.
547 if (CI->use_empty())
548 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000549
Dale Johannesence0b2372007-06-12 16:50:17 +0000550 return MadeChange;
551}
552
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000553namespace {
554class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
555protected:
556 void replaceCall(Value *With) {
557 CI->replaceAllUsesWith(With);
558 CI->eraseFromParent();
559 }
560 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000561 if (ConstantInt *SizeCI =
562 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
563 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000564 return false;
565 }
566};
567} // end anonymous namespace
568
Eric Christopher040056f2010-03-11 02:41:03 +0000569bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000570 // Lower all uses of llvm.objectsize.*
571 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
572 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000573 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000574 const Type *ReturnTy = CI->getType();
575 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
576 CI->replaceAllUsesWith(RetVal);
577 CI->eraseFromParent();
578 return true;
579 }
580
581 // From here on out we're working with named functions.
582 if (CI->getCalledFunction() == 0) return false;
583
584 // We'll need TargetData from here on out.
585 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
586 if (!TD) return false;
587
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000588 // Lower all default uses of _chk calls. This is very similar
589 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000590 // that have the default "don't know" as the objectsize. Anything else
591 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000592 CodeGenPrepareFortifiedLibCalls Simplifier;
593 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000594}
Chris Lattner88a5c832008-11-25 07:09:13 +0000595//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000596// Memory Optimization
597//===----------------------------------------------------------------------===//
598
Chris Lattnerdd77df32007-04-13 20:30:56 +0000599/// IsNonLocalValue - Return true if the specified values are defined in a
600/// different basic block than BB.
601static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
602 if (Instruction *I = dyn_cast<Instruction>(V))
603 return I->getParent() != BB;
604 return false;
605}
606
Bob Wilson4a8ee232009-12-03 21:47:07 +0000607/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000608/// addressing modes that can do significant amounts of computation. As such,
609/// instruction selection will try to get the load or store to do as much
610/// computation as possible for the program. The problem is that isel can only
611/// see within a single block. As such, we sink as much legal addressing mode
612/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000613///
614/// This method is used to optimize both load/store and inline asms with memory
615/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000616bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000617 const Type *AccessTy,
618 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000619 // Figure out what addressing mode will be built up for this operation.
620 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000621 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
622 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000623
Chris Lattnerdd77df32007-04-13 20:30:56 +0000624 // Check to see if any of the instructions supersumed by this addr mode are
625 // non-local to I's BB.
626 bool AnyNonLocal = false;
627 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000628 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000629 AnyNonLocal = true;
630 break;
631 }
632 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000633
Chris Lattnerdd77df32007-04-13 20:30:56 +0000634 // If all the instructions matched are already in this BB, don't do anything.
635 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000636 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000637 return false;
638 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000639
Chris Lattnerdd77df32007-04-13 20:30:56 +0000640 // Insert this computation right after this user. Since our caller is
641 // scanning from the top of the BB to the bottom, reuse of the expr are
642 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000643 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000644
Chris Lattnerdd77df32007-04-13 20:30:56 +0000645 // Now that we determined the addressing expression we want to use and know
646 // that we have to sink it into this block. Check to see if we have already
647 // done this for some other load/store instr in this block. If so, reuse the
648 // computation.
649 Value *&SunkAddr = SunkAddrs[Addr];
650 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000651 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000652 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000653 if (SunkAddr->getType() != Addr->getType())
654 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
655 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000656 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000657 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000658 const Type *IntPtrTy =
659 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000660
Chris Lattnerdd77df32007-04-13 20:30:56 +0000661 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000662
663 // Start with the base register. Do this first so that subsequent address
664 // matching finds it last, which will prevent it from trying to match it
665 // as the scaled value in case it happens to be a mul. That would be
666 // problematic if we've sunk a different mul for the scale, because then
667 // we'd end up sinking both muls.
668 if (AddrMode.BaseReg) {
669 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000670 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000671 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
672 if (V->getType() != IntPtrTy)
673 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
674 "sunkaddr", InsertPt);
675 Result = V;
676 }
677
678 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000679 if (AddrMode.Scale) {
680 Value *V = AddrMode.ScaledReg;
681 if (V->getType() == IntPtrTy) {
682 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000683 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000684 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
685 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
686 cast<IntegerType>(V->getType())->getBitWidth()) {
687 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
688 } else {
689 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
690 }
691 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000692 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000693 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000694 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000695 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000696 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000697 else
698 Result = V;
699 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000700
Chris Lattnerdd77df32007-04-13 20:30:56 +0000701 // Add in the BaseGV if present.
702 if (AddrMode.BaseGV) {
703 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
704 InsertPt);
705 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000706 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707 else
708 Result = V;
709 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000710
Chris Lattnerdd77df32007-04-13 20:30:56 +0000711 // Add in the Base Offset if present.
712 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000713 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000714 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000715 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000716 else
717 Result = V;
718 }
719
720 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000721 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000722 else
723 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
724 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000725
Chris Lattner896617b2008-11-26 03:20:37 +0000726 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000727
Dale Johannesen536d31b2010-03-31 20:37:15 +0000728 if (Addr->use_empty()) {
Chris Lattner3481f242008-11-27 22:57:53 +0000729 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000730 // This address is now available for reassignment, so erase the table entry;
731 // we don't want to match some completely different instruction.
732 SunkAddrs[Addr] = 0;
733 }
Chris Lattnerdd77df32007-04-13 20:30:56 +0000734 return true;
735}
736
Evan Cheng9bf12b52008-02-26 02:42:37 +0000737/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000738/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000739/// possible / profitable.
740bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
741 DenseMap<Value*,Value*> &SunkAddrs) {
742 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000743
John Thompsoneac6e1d2010-09-13 18:15:37 +0000744 std::vector<TargetLowering::AsmOperandInfo> TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000745 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000746 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
747 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
748
Evan Cheng9bf12b52008-02-26 02:42:37 +0000749 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000750 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000751
Eli Friedman9ec80952008-02-26 18:37:49 +0000752 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
753 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000754 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000755 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000756 } else if (OpInfo.Type == InlineAsm::isInput)
757 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000758 }
759
760 return MadeChange;
761}
762
Dan Gohmanb00f2362009-10-16 20:59:35 +0000763/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
764/// basic block as the load, unless conditions are unfavorable. This allows
765/// SelectionDAG to fold the extend into the load.
766///
767bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
768 // Look for a load being extended.
769 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
770 if (!LI) return false;
771
772 // If they're already in the same block, there's nothing to do.
773 if (LI->getParent() == I->getParent())
774 return false;
775
776 // If the load has other users and the truncate is not free, this probably
777 // isn't worthwhile.
778 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000779 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
780 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000781 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000782 return false;
783
784 // Check whether the target supports casts folded into loads.
785 unsigned LType;
786 if (isa<ZExtInst>(I))
787 LType = ISD::ZEXTLOAD;
788 else {
789 assert(isa<SExtInst>(I) && "Unexpected ext type!");
790 LType = ISD::SEXTLOAD;
791 }
792 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
793 return false;
794
795 // Move the extend into the same block as the load, so that SelectionDAG
796 // can fold it.
797 I->removeFromParent();
798 I->insertAfter(LI);
799 return true;
800}
801
Evan Chengbdcb7262007-12-05 23:58:20 +0000802bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
803 BasicBlock *DefBB = I->getParent();
804
Bob Wilson9120f5c2010-09-21 21:44:14 +0000805 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000806 // other uses of the source with result of extension.
807 Value *Src = I->getOperand(0);
808 if (Src->hasOneUse())
809 return false;
810
Evan Cheng696e5c02007-12-13 07:50:36 +0000811 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000812 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000813 return false;
814
Evan Cheng772de512007-12-12 00:51:06 +0000815 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000816 // this block.
817 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000818 return false;
819
Evan Chengbdcb7262007-12-05 23:58:20 +0000820 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000821 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000822 UI != E; ++UI) {
823 Instruction *User = cast<Instruction>(*UI);
824
825 // Figure out which BB this ext is used in.
826 BasicBlock *UserBB = User->getParent();
827 if (UserBB == DefBB) continue;
828 DefIsLiveOut = true;
829 break;
830 }
831 if (!DefIsLiveOut)
832 return false;
833
Evan Cheng765dff22007-12-12 02:53:41 +0000834 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000835 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000836 UI != E; ++UI) {
837 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000838 BasicBlock *UserBB = User->getParent();
839 if (UserBB == DefBB) continue;
840 // Be conservative. We don't want this xform to end up introducing
841 // reloads just before load / store instructions.
842 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000843 return false;
844 }
845
Evan Chengbdcb7262007-12-05 23:58:20 +0000846 // InsertedTruncs - Only insert one trunc in each block once.
847 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
848
849 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000850 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000851 UI != E; ++UI) {
852 Use &TheUse = UI.getUse();
853 Instruction *User = cast<Instruction>(*UI);
854
855 // Figure out which BB this ext is used in.
856 BasicBlock *UserBB = User->getParent();
857 if (UserBB == DefBB) continue;
858
859 // Both src and def are live in this block. Rewrite the use.
860 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
861
862 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000863 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000864
Evan Chengbdcb7262007-12-05 23:58:20 +0000865 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
866 }
867
868 // Replace a use of the {s|z}ext source with a use of the result.
869 TheUse = InsertedTrunc;
870
871 MadeChange = true;
872 }
873
874 return MadeChange;
875}
876
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000877// In this pass we look for GEP and cast instructions that are used
878// across basic blocks and rewrite them to improve basic-block-at-a-time
879// selection.
880bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
881 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000882
Evan Chengab631522008-12-19 18:03:11 +0000883 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +0000884 if (CriticalEdgeSplit) {
885 TerminatorInst *BBTI = BB.getTerminator();
886 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
887 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
888 BasicBlock *SuccBB = BBTI->getSuccessor(i);
889 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
890 SplitEdgeNicely(BBTI, i, BackEdges, this);
891 }
Evan Chengab631522008-12-19 18:03:11 +0000892 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000893 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000894
Chris Lattnerdd77df32007-04-13 20:30:56 +0000895 // Keep track of non-local addresses that have been sunk into this block.
896 // This allows us to avoid inserting duplicate code for blocks with multiple
897 // load/stores of the same address.
898 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000899
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000900 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
901 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000902
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000904 // If the source of the cast is a constant, then this should have
905 // already been constant folded. The only reason NOT to constant fold
906 // it is if something (e.g. LSR) was careful to place the constant
907 // evaluation in a block other than then one that uses it (e.g. to hoist
908 // the address of globals out of a loop). If this is the case, we don't
909 // want to forward-subst the cast.
910 if (isa<Constant>(CI->getOperand(0)))
911 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000912
Evan Chengbdcb7262007-12-05 23:58:20 +0000913 bool Change = false;
914 if (TLI) {
915 Change = OptimizeNoopCopyExpression(CI, *TLI);
916 MadeChange |= Change;
917 }
918
Dan Gohmanb00f2362009-10-16 20:59:35 +0000919 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
920 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000921 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000922 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000923 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
924 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
926 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000927 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
928 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000929 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
930 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000931 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
932 SI->getOperand(0)->getType(),
933 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000934 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000935 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000936 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000937 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000938 GEPI->getName(), GEPI);
939 GEPI->replaceAllUsesWith(NC);
940 GEPI->eraseFromParent();
941 MadeChange = true;
942 BBI = NC;
943 }
944 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
945 // If we found an inline asm expession, and if the target knows how to
946 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000947 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
948 if (TLI->ExpandInlineAsm(CI)) {
949 BBI = BB.begin();
950 // Avoid processing instructions out of order, which could cause
951 // reuse before a value is defined.
952 SunkAddrs.clear();
953 } else
954 // Sink address computing for memory operands into the block.
955 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +0000956 } else {
957 // Other CallInst optimizations that don't need to muck with the
958 // enclosing iterator here.
959 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +0000960 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000961 }
962 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000963
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000964 return MadeChange;
965}