blob: 8df0b3ce47a265534380f8f34114289200fc3c96 [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"
Owen Andersond5f86842010-12-23 20:57:35 +000025#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000026#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000029#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000031#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000032#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000034#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000035#include "llvm/ADT/Statistic.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000036#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000037#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000038#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000039#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000040#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000041#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000042#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000044using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000045using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000047STATISTIC(NumElim, "Number of blocks eliminated");
48
Evan Chenge1bcb442010-08-17 01:34:49 +000049static cl::opt<bool>
50CriticalEdgeSplit("cgp-critical-edge-splitting",
51 cl::desc("Split critical edges during codegen prepare"),
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000052 cl::init(false), cl::Hidden);
Evan Chenge1bcb442010-08-17 01:34:49 +000053
Eric Christopher692bf6b2008-09-24 05:32:41 +000054namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000055 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000056 /// TLI - Keep a pointer of a TargetLowering to consult for determining
57 /// transformation profitability.
58 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000059 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000060
61 /// BackEdges - Keep a set of all the loop back edges.
62 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000063 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000064 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000065 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000066 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +000067 : FunctionPass(ID), TLI(tli) {
68 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
69 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000070 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000071
Andreas Neustifterad809812009-09-16 09:26:52 +000072 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addPreserved<ProfileInfo>();
74 }
75
Dan Gohmanaa0e5232010-02-05 19:24:11 +000076 virtual void releaseMemory() {
77 BackEdges.clear();
78 }
79
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000081 bool EliminateMostlyEmptyBlocks(Function &F);
82 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
83 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000084 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000085 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
86 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000087 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
88 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +000089 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +000090 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000091 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000092 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000093 };
94}
Devang Patel794fd752007-05-01 21:15:47 +000095
Devang Patel19974732007-05-03 01:11:54 +000096char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000097INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +000098 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000099
100FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
101 return new CodeGenPrepare(TLI);
102}
103
Evan Chengab631522008-12-19 18:03:11 +0000104/// findLoopBackEdges - Do a DFS walk to find loop back edges.
105///
Mike Stumpfe095f32009-05-04 18:40:41 +0000106void CodeGenPrepare::findLoopBackEdges(const Function &F) {
107 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
108 FindFunctionBackedges(F, Edges);
109
110 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000111}
112
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000113
114bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000116
Evan Cheng04149f72009-12-17 09:39:49 +0000117 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000118 // First pass, eliminate blocks that contain only PHI nodes and an
119 // unconditional branch.
120 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000121
Cameron Zwarich95bb0042011-01-04 04:43:31 +0000122 // Now find loop back edges, but only if they are being used to decide which
123 // critical edges to split.
124 if (CriticalEdgeSplit)
125 findLoopBackEdges(F);
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000126
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000127 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000128 while (MadeChange) {
129 MadeChange = false;
130 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
131 MadeChange |= OptimizeBlock(*BB);
132 EverMadeChange |= MadeChange;
133 }
134 return EverMadeChange;
135}
136
Dale Johannesen2d697242009-03-27 01:13:37 +0000137/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
138/// debug info directives, and an unconditional branch. Passes before isel
139/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
140/// isel. Start by eliminating these blocks so we can split them the way we
141/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
143 bool MadeChange = false;
144 // Note that this intentionally skips the entry block.
145 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
146 BasicBlock *BB = I++;
147
148 // If this block doesn't end with an uncond branch, ignore it.
149 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
150 if (!BI || !BI->isUnconditional())
151 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000152
Dale Johannesen2d697242009-03-27 01:13:37 +0000153 // If the instruction before the branch (skipping debug info) isn't a phi
154 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000155 BasicBlock::iterator BBI = BI;
156 if (BBI != BB->begin()) {
157 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000158 while (isa<DbgInfoIntrinsic>(BBI)) {
159 if (BBI == BB->begin())
160 break;
161 --BBI;
162 }
163 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
164 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000166
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000167 // Do not break infinite loops.
168 BasicBlock *DestBB = BI->getSuccessor(0);
169 if (DestBB == BB)
170 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000171
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000172 if (!CanMergeBlocks(BB, DestBB))
173 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000174
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000175 EliminateMostlyEmptyBlock(BB);
176 MadeChange = true;
177 }
178 return MadeChange;
179}
180
181/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
182/// single uncond branch between them, and BB contains no other non-phi
183/// instructions.
184bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
185 const BasicBlock *DestBB) const {
186 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
187 // the successor. If there are more complex condition (e.g. preheaders),
188 // don't mess around with them.
189 BasicBlock::const_iterator BBI = BB->begin();
190 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000191 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000192 UI != E; ++UI) {
193 const Instruction *User = cast<Instruction>(*UI);
194 if (User->getParent() != DestBB || !isa<PHINode>(User))
195 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000196 // If User is inside DestBB block and it is a PHINode then check
197 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000198 // a complex condition (e.g. preheaders) we want to avoid here.
199 if (User->getParent() == DestBB) {
200 if (const PHINode *UPN = dyn_cast<PHINode>(User))
201 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
202 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
203 if (Insn && Insn->getParent() == BB &&
204 Insn->getParent() != UPN->getIncomingBlock(I))
205 return false;
206 }
207 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000208 }
209 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000210
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000211 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
212 // and DestBB may have conflicting incoming values for the block. If so, we
213 // can't merge the block.
214 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
215 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000216
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000217 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000218 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000219 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
220 // It is faster to get preds from a PHI than with pred_iterator.
221 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
222 BBPreds.insert(BBPN->getIncomingBlock(i));
223 } else {
224 BBPreds.insert(pred_begin(BB), pred_end(BB));
225 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000226
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000227 // Walk the preds of DestBB.
228 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
229 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
230 if (BBPreds.count(Pred)) { // Common predecessor?
231 BBI = DestBB->begin();
232 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
233 const Value *V1 = PN->getIncomingValueForBlock(Pred);
234 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000235
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000236 // If V2 is a phi node in BB, look up what the mapped value will be.
237 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
238 if (V2PN->getParent() == BB)
239 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000240
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000241 // If there is a conflict, bail out.
242 if (V1 != V2) return false;
243 }
244 }
245 }
246
247 return true;
248}
249
250
251/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
252/// an unconditional branch in it.
253void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
254 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
255 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000256
David Greene68d67fd2010-01-05 01:27:11 +0000257 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000258
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000259 // If the destination block has a single pred, then this is a trivial edge,
260 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000261 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000262 if (SinglePred != DestBB) {
263 // Remember if SinglePred was the entry block of the function. If so, we
264 // will need to move BB back to the entry position.
265 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000266 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000267
Chris Lattnerf5102a02008-11-28 19:54:49 +0000268 if (isEntry && BB != &BB->getParent()->getEntryBlock())
269 BB->moveBefore(&BB->getParent()->getEntryBlock());
270
David Greene68d67fd2010-01-05 01:27:11 +0000271 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000272 return;
273 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000275
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
277 // to handle the new incoming edges it is about to have.
278 PHINode *PN;
279 for (BasicBlock::iterator BBI = DestBB->begin();
280 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
281 // Remove the incoming value for BB, and remember it.
282 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000283
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000284 // Two options: either the InVal is a phi node defined in BB or it is some
285 // value that dominates BB.
286 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
287 if (InValPhi && InValPhi->getParent() == BB) {
288 // Add all of the input values of the input PHI as inputs of this phi.
289 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
290 PN->addIncoming(InValPhi->getIncomingValue(i),
291 InValPhi->getIncomingBlock(i));
292 } else {
293 // Otherwise, add one instance of the dominating value for each edge that
294 // we will be adding.
295 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
296 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
297 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
298 } else {
299 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
300 PN->addIncoming(InVal, *PI);
301 }
302 }
303 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000305 // The PHIs are now updated, change everything that refers to BB to use
306 // DestBB and remove BB.
307 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000308 if (PFI) {
309 PFI->replaceAllUses(BB, DestBB);
310 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000311 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000312 BB->eraseFromParent();
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +0000313 ++NumElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000314
David Greene68d67fd2010-01-05 01:27:11 +0000315 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000316}
317
Chris Lattner98d5c312010-02-13 05:35:08 +0000318/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
319/// lives in to see if there is a block that we can reuse as a critical edge
320/// from TIBB.
321static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
322 BasicBlock *Dest = DestPHI->getParent();
323
324 /// TIPHIValues - This array is lazily computed to determine the values of
325 /// PHIs in Dest that TI would provide.
326 SmallVector<Value*, 32> TIPHIValues;
327
328 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
329 unsigned TIBBEntryNo = 0;
330
331 // Check to see if Dest has any blocks that can be used as a split edge for
332 // this terminator.
333 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
334 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
335 // To be usable, the pred has to end with an uncond branch to the dest.
336 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
337 if (!PredBr || !PredBr->isUnconditional())
338 continue;
339 // Must be empty other than the branch and debug info.
340 BasicBlock::iterator I = Pred->begin();
341 while (isa<DbgInfoIntrinsic>(I))
342 I++;
343 if (&*I != PredBr)
344 continue;
345 // Cannot be the entry block; its label does not get emitted.
346 if (Pred == &Dest->getParent()->getEntryBlock())
347 continue;
348
349 // Finally, since we know that Dest has phi nodes in it, we have to make
350 // sure that jumping to Pred will have the same effect as going to Dest in
351 // terms of PHI values.
352 PHINode *PN;
353 unsigned PHINo = 0;
354 unsigned PredEntryNo = pi;
355
356 bool FoundMatch = true;
357 for (BasicBlock::iterator I = Dest->begin();
358 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
359 if (PHINo == TIPHIValues.size()) {
360 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
361 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
362 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
363 }
364
365 // If the PHI entry doesn't work, we can't use this pred.
366 if (PN->getIncomingBlock(PredEntryNo) != Pred)
367 PredEntryNo = PN->getBasicBlockIndex(Pred);
368
369 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
370 FoundMatch = false;
371 break;
372 }
373 }
374
375 // If we found a workable predecessor, change TI to branch to Succ.
376 if (FoundMatch)
377 return Pred;
378 }
379 return 0;
380}
381
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000382
Chris Lattnerebe80752007-12-24 19:32:55 +0000383/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000384/// successor if it will improve codegen. We only do this if the successor has
385/// phi nodes (otherwise critical edges are ok). If there is already another
386/// predecessor of the succ that is empty (and thus has no phi nodes), use it
387/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000388static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000389 SmallSet<std::pair<const BasicBlock*,
390 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000391 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000392 BasicBlock *TIBB = TI->getParent();
393 BasicBlock *Dest = TI->getSuccessor(SuccNum);
394 assert(isa<PHINode>(Dest->begin()) &&
395 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000396 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000397
Evan Chengfc0b80d2009-03-13 22:59:14 +0000398 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000399 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000400 if (Invoke->getSuccessor(1) == Dest)
401 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000402
Chris Lattnerebe80752007-12-24 19:32:55 +0000403 // As a hack, never split backedges of loops. Even though the copy for any
404 // PHIs inserted on the backedge would be dead for exits from the loop, we
405 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000406 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000407 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000408
Chris Lattnerc09687b2010-02-13 19:07:06 +0000409 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
410 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
411 if (PFI)
412 PFI->splitEdge(TIBB, Dest, ReuseBB);
413 Dest->removePredecessor(TIBB);
414 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000415 return;
416 }
417
Chris Lattnerc09687b2010-02-13 19:07:06 +0000418 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000419}
420
Evan Chengab631522008-12-19 18:03:11 +0000421
Chris Lattnerdd77df32007-04-13 20:30:56 +0000422/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000423/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
424/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000425/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000426///
427/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000428///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000429static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000430 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000431 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
432 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000433
Chris Lattnerdd77df32007-04-13 20:30:56 +0000434 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000435 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000437
Chris Lattnerdd77df32007-04-13 20:30:56 +0000438 // If this is an extension, it will be a zero or sign extension, which
439 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000440 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441
Chris Lattnerdd77df32007-04-13 20:30:56 +0000442 // If these values will be promoted, find out what they will be promoted
443 // to. This helps us consider truncates on PPC as noop copies when they
444 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000445 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000446 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000447 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000448 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450 // If, after promotion, these are the same types, this is a noop copy.
451 if (SrcVT != DstVT)
452 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000457 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000460 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000461 UI != E; ) {
462 Use &TheUse = UI.getUse();
463 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000465 // Figure out which BB this cast is used in. For PHI's this is the
466 // appropriate predecessor block.
467 BasicBlock *UserBB = User->getParent();
468 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000469 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 // Preincrement use iterator so we don't invalidate it.
473 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 // If this user is in the same block as the cast, don't change the cast.
476 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000478 // If we have already inserted a cast into this block, use it.
479 CastInst *&InsertedCast = InsertedCasts[UserBB];
480
481 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000482 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
484 InsertedCast =
485 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 InsertPt);
487 MadeChange = true;
488 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000489
Dale Johannesence0b2372007-06-12 16:50:17 +0000490 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 TheUse = InsertedCast;
492 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000495 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000496 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000497 MadeChange = true;
498 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000500 return MadeChange;
501}
502
Eric Christopher692bf6b2008-09-24 05:32:41 +0000503/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000504/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000505/// a clear win except on targets with multiple condition code registers
506/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000507///
508/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000509static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000511
Dale Johannesence0b2372007-06-12 16:50:17 +0000512 /// InsertedCmp - Only insert a cmp in each block once.
513 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000516 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000517 UI != E; ) {
518 Use &TheUse = UI.getUse();
519 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
Dale Johannesence0b2372007-06-12 16:50:17 +0000521 // Preincrement use iterator so we don't invalidate it.
522 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523
Dale Johannesence0b2372007-06-12 16:50:17 +0000524 // Don't bother for PHI nodes.
525 if (isa<PHINode>(User))
526 continue;
527
528 // Figure out which BB this cmp is used in.
529 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 // If this user is in the same block as the cmp, don't change the cmp.
532 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533
Dale Johannesence0b2372007-06-12 16:50:17 +0000534 // If we have already inserted a cmp into this block, use it.
535 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
536
537 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000538 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
540 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000541 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000542 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000543 CI->getOperand(1), "", InsertPt);
544 MadeChange = true;
545 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 // Replace a use of the cmp with a use of the new cmp.
548 TheUse = InsertedCmp;
549 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000550
Dale Johannesence0b2372007-06-12 16:50:17 +0000551 // If we removed all uses, nuke the cmp.
552 if (CI->use_empty())
553 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000554
Dale Johannesence0b2372007-06-12 16:50:17 +0000555 return MadeChange;
556}
557
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000558namespace {
559class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
560protected:
561 void replaceCall(Value *With) {
562 CI->replaceAllUsesWith(With);
563 CI->eraseFromParent();
564 }
565 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000566 if (ConstantInt *SizeCI =
567 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
568 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000569 return false;
570 }
571};
572} // end anonymous namespace
573
Eric Christopher040056f2010-03-11 02:41:03 +0000574bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000575 // Lower all uses of llvm.objectsize.*
576 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
577 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000578 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000579 const Type *ReturnTy = CI->getType();
580 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
581 CI->replaceAllUsesWith(RetVal);
582 CI->eraseFromParent();
583 return true;
584 }
585
586 // From here on out we're working with named functions.
587 if (CI->getCalledFunction() == 0) return false;
588
589 // We'll need TargetData from here on out.
590 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
591 if (!TD) return false;
592
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000593 // Lower all default uses of _chk calls. This is very similar
594 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000595 // that have the default "don't know" as the objectsize. Anything else
596 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000597 CodeGenPrepareFortifiedLibCalls Simplifier;
598 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000599}
Chris Lattner88a5c832008-11-25 07:09:13 +0000600//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000601// Memory Optimization
602//===----------------------------------------------------------------------===//
603
Chris Lattnerdd77df32007-04-13 20:30:56 +0000604/// IsNonLocalValue - Return true if the specified values are defined in a
605/// different basic block than BB.
606static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
607 if (Instruction *I = dyn_cast<Instruction>(V))
608 return I->getParent() != BB;
609 return false;
610}
611
Bob Wilson4a8ee232009-12-03 21:47:07 +0000612/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000613/// addressing modes that can do significant amounts of computation. As such,
614/// instruction selection will try to get the load or store to do as much
615/// computation as possible for the program. The problem is that isel can only
616/// see within a single block. As such, we sink as much legal addressing mode
617/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000618///
619/// This method is used to optimize both load/store and inline asms with memory
620/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000621bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000622 const Type *AccessTy,
623 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000624 Value *Repl = Addr;
625
Owen Andersond2f41742010-11-19 22:15:03 +0000626 // Try to collapse single-value PHI nodes. This is necessary to undo
627 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000628 SmallVector<Value*, 8> worklist;
629 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000630 worklist.push_back(Addr);
631
632 // Use a worklist to iteratively look through PHI nodes, and ensure that
633 // the addressing mode obtained from the non-PHI roots of the graph
634 // are equivalent.
635 Value *Consensus = 0;
636 unsigned NumUses = 0;
637 SmallVector<Instruction*, 16> AddrModeInsts;
638 ExtAddrMode AddrMode;
639 while (!worklist.empty()) {
640 Value *V = worklist.back();
641 worklist.pop_back();
642
643 // Break use-def graph loops.
644 if (Visited.count(V)) {
645 Consensus = 0;
646 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000647 }
648
Owen Anderson35bf4d62010-11-27 08:15:55 +0000649 Visited.insert(V);
650
651 // For a PHI node, push all of its incoming values.
652 if (PHINode *P = dyn_cast<PHINode>(V)) {
653 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
654 worklist.push_back(P->getIncomingValue(i));
655 continue;
656 }
657
658 // For non-PHIs, determine the addressing mode being computed.
659 SmallVector<Instruction*, 16> NewAddrModeInsts;
660 ExtAddrMode NewAddrMode =
661 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
662 NewAddrModeInsts, *TLI);
663
664 // Ensure that the obtained addressing mode is equivalent to that obtained
665 // for all other roots of the PHI traversal. Also, when choosing one
666 // such root as representative, select the one with the most uses in order
667 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
668 if (!Consensus || NewAddrMode == AddrMode) {
669 if (V->getNumUses() > NumUses) {
670 Consensus = V;
671 NumUses = V->getNumUses();
672 AddrMode = NewAddrMode;
673 AddrModeInsts = NewAddrModeInsts;
674 }
675 continue;
676 }
677
678 Consensus = 0;
679 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000680 }
681
Owen Anderson35bf4d62010-11-27 08:15:55 +0000682 // If the addressing mode couldn't be determined, or if multiple different
683 // ones were determined, bail out now.
684 if (!Consensus) return false;
685
Chris Lattnerdd77df32007-04-13 20:30:56 +0000686 // Check to see if any of the instructions supersumed by this addr mode are
687 // non-local to I's BB.
688 bool AnyNonLocal = false;
689 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000690 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000691 AnyNonLocal = true;
692 break;
693 }
694 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000695
Chris Lattnerdd77df32007-04-13 20:30:56 +0000696 // If all the instructions matched are already in this BB, don't do anything.
697 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000698 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000699 return false;
700 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000701
Chris Lattnerdd77df32007-04-13 20:30:56 +0000702 // Insert this computation right after this user. Since our caller is
703 // scanning from the top of the BB to the bottom, reuse of the expr are
704 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000705 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000706
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707 // Now that we determined the addressing expression we want to use and know
708 // that we have to sink it into this block. Check to see if we have already
709 // done this for some other load/store instr in this block. If so, reuse the
710 // computation.
711 Value *&SunkAddr = SunkAddrs[Addr];
712 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000713 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000714 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000715 if (SunkAddr->getType() != Addr->getType())
716 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
717 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000718 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000719 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000720 const Type *IntPtrTy =
721 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000722
Chris Lattnerdd77df32007-04-13 20:30:56 +0000723 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000724
725 // Start with the base register. Do this first so that subsequent address
726 // matching finds it last, which will prevent it from trying to match it
727 // as the scaled value in case it happens to be a mul. That would be
728 // problematic if we've sunk a different mul for the scale, because then
729 // we'd end up sinking both muls.
730 if (AddrMode.BaseReg) {
731 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000732 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000733 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
734 if (V->getType() != IntPtrTy)
735 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
736 "sunkaddr", InsertPt);
737 Result = V;
738 }
739
740 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000741 if (AddrMode.Scale) {
742 Value *V = AddrMode.ScaledReg;
743 if (V->getType() == IntPtrTy) {
744 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000745 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000746 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
747 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
748 cast<IntegerType>(V->getType())->getBitWidth()) {
749 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
750 } else {
751 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
752 }
753 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000754 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000755 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000756 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000757 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000758 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000759 else
760 Result = V;
761 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000762
Chris Lattnerdd77df32007-04-13 20:30:56 +0000763 // Add in the BaseGV if present.
764 if (AddrMode.BaseGV) {
765 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
766 InsertPt);
767 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000768 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000769 else
770 Result = V;
771 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000772
Chris Lattnerdd77df32007-04-13 20:30:56 +0000773 // Add in the Base Offset if present.
774 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000775 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000776 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000777 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000778 else
779 Result = V;
780 }
781
782 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000783 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000784 else
785 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
786 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000787
Owen Andersond2f41742010-11-19 22:15:03 +0000788 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000789
Owen Andersond2f41742010-11-19 22:15:03 +0000790 if (Repl->use_empty()) {
791 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000792 // This address is now available for reassignment, so erase the table entry;
793 // we don't want to match some completely different instruction.
794 SunkAddrs[Addr] = 0;
795 }
Chris Lattnerdd77df32007-04-13 20:30:56 +0000796 return true;
797}
798
Evan Cheng9bf12b52008-02-26 02:42:37 +0000799/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000800/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000801/// possible / profitable.
802bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
803 DenseMap<Value*,Value*> &SunkAddrs) {
804 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000805
John Thompson44ab89e2010-10-29 17:29:13 +0000806 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000807 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000808 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
809 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
810
Evan Cheng9bf12b52008-02-26 02:42:37 +0000811 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000812 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000813
Eli Friedman9ec80952008-02-26 18:37:49 +0000814 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
815 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000816 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000817 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000818 } else if (OpInfo.Type == InlineAsm::isInput)
819 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000820 }
821
822 return MadeChange;
823}
824
Dan Gohmanb00f2362009-10-16 20:59:35 +0000825/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
826/// basic block as the load, unless conditions are unfavorable. This allows
827/// SelectionDAG to fold the extend into the load.
828///
829bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
830 // Look for a load being extended.
831 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
832 if (!LI) return false;
833
834 // If they're already in the same block, there's nothing to do.
835 if (LI->getParent() == I->getParent())
836 return false;
837
838 // If the load has other users and the truncate is not free, this probably
839 // isn't worthwhile.
840 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000841 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
842 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000843 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000844 return false;
845
846 // Check whether the target supports casts folded into loads.
847 unsigned LType;
848 if (isa<ZExtInst>(I))
849 LType = ISD::ZEXTLOAD;
850 else {
851 assert(isa<SExtInst>(I) && "Unexpected ext type!");
852 LType = ISD::SEXTLOAD;
853 }
854 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
855 return false;
856
857 // Move the extend into the same block as the load, so that SelectionDAG
858 // can fold it.
859 I->removeFromParent();
860 I->insertAfter(LI);
861 return true;
862}
863
Evan Chengbdcb7262007-12-05 23:58:20 +0000864bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
865 BasicBlock *DefBB = I->getParent();
866
Bob Wilson9120f5c2010-09-21 21:44:14 +0000867 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000868 // other uses of the source with result of extension.
869 Value *Src = I->getOperand(0);
870 if (Src->hasOneUse())
871 return false;
872
Evan Cheng696e5c02007-12-13 07:50:36 +0000873 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000874 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000875 return false;
876
Evan Cheng772de512007-12-12 00:51:06 +0000877 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000878 // this block.
879 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000880 return false;
881
Evan Chengbdcb7262007-12-05 23:58:20 +0000882 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000883 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000884 UI != E; ++UI) {
885 Instruction *User = cast<Instruction>(*UI);
886
887 // Figure out which BB this ext is used in.
888 BasicBlock *UserBB = User->getParent();
889 if (UserBB == DefBB) continue;
890 DefIsLiveOut = true;
891 break;
892 }
893 if (!DefIsLiveOut)
894 return false;
895
Evan Cheng765dff22007-12-12 02:53:41 +0000896 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000897 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000898 UI != E; ++UI) {
899 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000900 BasicBlock *UserBB = User->getParent();
901 if (UserBB == DefBB) continue;
902 // Be conservative. We don't want this xform to end up introducing
903 // reloads just before load / store instructions.
904 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000905 return false;
906 }
907
Evan Chengbdcb7262007-12-05 23:58:20 +0000908 // InsertedTruncs - Only insert one trunc in each block once.
909 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
910
911 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000912 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000913 UI != E; ++UI) {
914 Use &TheUse = UI.getUse();
915 Instruction *User = cast<Instruction>(*UI);
916
917 // Figure out which BB this ext is used in.
918 BasicBlock *UserBB = User->getParent();
919 if (UserBB == DefBB) continue;
920
921 // Both src and def are live in this block. Rewrite the use.
922 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
923
924 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000925 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000926
Evan Chengbdcb7262007-12-05 23:58:20 +0000927 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
928 }
929
930 // Replace a use of the {s|z}ext source with a use of the result.
931 TheUse = InsertedTrunc;
932
933 MadeChange = true;
934 }
935
936 return MadeChange;
937}
938
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000939// In this pass we look for GEP and cast instructions that are used
940// across basic blocks and rewrite them to improve basic-block-at-a-time
941// selection.
942bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
943 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000944
Evan Chengab631522008-12-19 18:03:11 +0000945 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +0000946 if (CriticalEdgeSplit) {
947 TerminatorInst *BBTI = BB.getTerminator();
948 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
949 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
950 BasicBlock *SuccBB = BBTI->getSuccessor(i);
951 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
952 SplitEdgeNicely(BBTI, i, BackEdges, this);
953 }
Evan Chengab631522008-12-19 18:03:11 +0000954 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000955 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000956
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 // Keep track of non-local addresses that have been sunk into this block.
958 // This allows us to avoid inserting duplicate code for blocks with multiple
959 // load/stores of the same address.
960 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000961
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000962 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
963 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000964
Owen Andersond5f86842010-12-23 20:57:35 +0000965 if (PHINode *P = dyn_cast<PHINode>(I)) {
966 // It is possible for very late stage optimizations (such as SimplifyCFG)
967 // to introduce PHI nodes too late to be cleaned up. If we detect such a
968 // trivial PHI, go ahead and zap it here.
969 if (Value *V = SimplifyInstruction(P)) {
970 P->replaceAllUsesWith(V);
971 P->eraseFromParent();
972 }
973 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000974 // If the source of the cast is a constant, then this should have
975 // already been constant folded. The only reason NOT to constant fold
976 // it is if something (e.g. LSR) was careful to place the constant
977 // evaluation in a block other than then one that uses it (e.g. to hoist
978 // the address of globals out of a loop). If this is the case, we don't
979 // want to forward-subst the cast.
980 if (isa<Constant>(CI->getOperand(0)))
981 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000982
Evan Chengbdcb7262007-12-05 23:58:20 +0000983 bool Change = false;
984 if (TLI) {
985 Change = OptimizeNoopCopyExpression(CI, *TLI);
986 MadeChange |= Change;
987 }
988
Dan Gohmanb00f2362009-10-16 20:59:35 +0000989 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
990 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000991 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000992 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000993 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
994 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000995 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
996 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000997 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
998 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000999 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1000 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +00001001 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1002 SI->getOperand(0)->getType(),
1003 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001004 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001005 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001006 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001007 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001008 GEPI->getName(), GEPI);
1009 GEPI->replaceAllUsesWith(NC);
1010 GEPI->eraseFromParent();
1011 MadeChange = true;
1012 BBI = NC;
1013 }
1014 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1015 // If we found an inline asm expession, and if the target knows how to
1016 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +00001017 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1018 if (TLI->ExpandInlineAsm(CI)) {
1019 BBI = BB.begin();
1020 // Avoid processing instructions out of order, which could cause
1021 // reuse before a value is defined.
1022 SunkAddrs.clear();
1023 } else
1024 // Sink address computing for memory operands into the block.
1025 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +00001026 } else {
1027 // Other CallInst optimizations that don't need to muck with the
1028 // enclosing iterator here.
1029 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +00001030 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001031 }
1032 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001033
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001034 return MadeChange;
1035}