blob: f4edcc76ec532620e043852b56802ebb01495da7 [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
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000122 // Now find loop back edges.
123 findLoopBackEdges(F);
124
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000125 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000126 while (MadeChange) {
127 MadeChange = false;
128 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
129 MadeChange |= OptimizeBlock(*BB);
130 EverMadeChange |= MadeChange;
131 }
132 return EverMadeChange;
133}
134
Dale Johannesen2d697242009-03-27 01:13:37 +0000135/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
136/// debug info directives, and an unconditional branch. Passes before isel
137/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
138/// isel. Start by eliminating these blocks so we can split them the way we
139/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000140bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
141 bool MadeChange = false;
142 // Note that this intentionally skips the entry block.
143 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
144 BasicBlock *BB = I++;
145
146 // If this block doesn't end with an uncond branch, ignore it.
147 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
148 if (!BI || !BI->isUnconditional())
149 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000150
Dale Johannesen2d697242009-03-27 01:13:37 +0000151 // If the instruction before the branch (skipping debug info) isn't a phi
152 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000153 BasicBlock::iterator BBI = BI;
154 if (BBI != BB->begin()) {
155 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000156 while (isa<DbgInfoIntrinsic>(BBI)) {
157 if (BBI == BB->begin())
158 break;
159 --BBI;
160 }
161 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
162 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000164
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 // Do not break infinite loops.
166 BasicBlock *DestBB = BI->getSuccessor(0);
167 if (DestBB == BB)
168 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000169
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000170 if (!CanMergeBlocks(BB, DestBB))
171 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000172
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000173 EliminateMostlyEmptyBlock(BB);
174 MadeChange = true;
175 }
176 return MadeChange;
177}
178
179/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
180/// single uncond branch between them, and BB contains no other non-phi
181/// instructions.
182bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
183 const BasicBlock *DestBB) const {
184 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
185 // the successor. If there are more complex condition (e.g. preheaders),
186 // don't mess around with them.
187 BasicBlock::const_iterator BBI = BB->begin();
188 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000189 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000190 UI != E; ++UI) {
191 const Instruction *User = cast<Instruction>(*UI);
192 if (User->getParent() != DestBB || !isa<PHINode>(User))
193 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000194 // If User is inside DestBB block and it is a PHINode then check
195 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000196 // a complex condition (e.g. preheaders) we want to avoid here.
197 if (User->getParent() == DestBB) {
198 if (const PHINode *UPN = dyn_cast<PHINode>(User))
199 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
200 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
201 if (Insn && Insn->getParent() == BB &&
202 Insn->getParent() != UPN->getIncomingBlock(I))
203 return false;
204 }
205 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000206 }
207 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000208
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000209 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
210 // and DestBB may have conflicting incoming values for the block. If so, we
211 // can't merge the block.
212 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
213 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000214
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000215 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000216 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000217 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
218 // It is faster to get preds from a PHI than with pred_iterator.
219 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
220 BBPreds.insert(BBPN->getIncomingBlock(i));
221 } else {
222 BBPreds.insert(pred_begin(BB), pred_end(BB));
223 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000224
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000225 // Walk the preds of DestBB.
226 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
227 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
228 if (BBPreds.count(Pred)) { // Common predecessor?
229 BBI = DestBB->begin();
230 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
231 const Value *V1 = PN->getIncomingValueForBlock(Pred);
232 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000233
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 // If V2 is a phi node in BB, look up what the mapped value will be.
235 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
236 if (V2PN->getParent() == BB)
237 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000238
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000239 // If there is a conflict, bail out.
240 if (V1 != V2) return false;
241 }
242 }
243 }
244
245 return true;
246}
247
248
249/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
250/// an unconditional branch in it.
251void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
252 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
253 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000254
David Greene68d67fd2010-01-05 01:27:11 +0000255 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000256
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000257 // If the destination block has a single pred, then this is a trivial edge,
258 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000259 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000260 if (SinglePred != DestBB) {
261 // Remember if SinglePred was the entry block of the function. If so, we
262 // will need to move BB back to the entry position.
263 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000264 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000265
Chris Lattnerf5102a02008-11-28 19:54:49 +0000266 if (isEntry && BB != &BB->getParent()->getEntryBlock())
267 BB->moveBefore(&BB->getParent()->getEntryBlock());
268
David Greene68d67fd2010-01-05 01:27:11 +0000269 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000270 return;
271 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000272 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000273
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000274 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
275 // to handle the new incoming edges it is about to have.
276 PHINode *PN;
277 for (BasicBlock::iterator BBI = DestBB->begin();
278 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
279 // Remove the incoming value for BB, and remember it.
280 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000281
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000282 // Two options: either the InVal is a phi node defined in BB or it is some
283 // value that dominates BB.
284 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
285 if (InValPhi && InValPhi->getParent() == BB) {
286 // Add all of the input values of the input PHI as inputs of this phi.
287 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
288 PN->addIncoming(InValPhi->getIncomingValue(i),
289 InValPhi->getIncomingBlock(i));
290 } else {
291 // Otherwise, add one instance of the dominating value for each edge that
292 // we will be adding.
293 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
294 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
295 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
296 } else {
297 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
298 PN->addIncoming(InVal, *PI);
299 }
300 }
301 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000302
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000303 // The PHIs are now updated, change everything that refers to BB to use
304 // DestBB and remove BB.
305 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000306 if (PFI) {
307 PFI->replaceAllUses(BB, DestBB);
308 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000309 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000310 BB->eraseFromParent();
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +0000311 ++NumElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000312
David Greene68d67fd2010-01-05 01:27:11 +0000313 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000314}
315
Chris Lattner98d5c312010-02-13 05:35:08 +0000316/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
317/// lives in to see if there is a block that we can reuse as a critical edge
318/// from TIBB.
319static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
320 BasicBlock *Dest = DestPHI->getParent();
321
322 /// TIPHIValues - This array is lazily computed to determine the values of
323 /// PHIs in Dest that TI would provide.
324 SmallVector<Value*, 32> TIPHIValues;
325
326 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
327 unsigned TIBBEntryNo = 0;
328
329 // Check to see if Dest has any blocks that can be used as a split edge for
330 // this terminator.
331 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
332 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
333 // To be usable, the pred has to end with an uncond branch to the dest.
334 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
335 if (!PredBr || !PredBr->isUnconditional())
336 continue;
337 // Must be empty other than the branch and debug info.
338 BasicBlock::iterator I = Pred->begin();
339 while (isa<DbgInfoIntrinsic>(I))
340 I++;
341 if (&*I != PredBr)
342 continue;
343 // Cannot be the entry block; its label does not get emitted.
344 if (Pred == &Dest->getParent()->getEntryBlock())
345 continue;
346
347 // Finally, since we know that Dest has phi nodes in it, we have to make
348 // sure that jumping to Pred will have the same effect as going to Dest in
349 // terms of PHI values.
350 PHINode *PN;
351 unsigned PHINo = 0;
352 unsigned PredEntryNo = pi;
353
354 bool FoundMatch = true;
355 for (BasicBlock::iterator I = Dest->begin();
356 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
357 if (PHINo == TIPHIValues.size()) {
358 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
359 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
360 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
361 }
362
363 // If the PHI entry doesn't work, we can't use this pred.
364 if (PN->getIncomingBlock(PredEntryNo) != Pred)
365 PredEntryNo = PN->getBasicBlockIndex(Pred);
366
367 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
368 FoundMatch = false;
369 break;
370 }
371 }
372
373 // If we found a workable predecessor, change TI to branch to Succ.
374 if (FoundMatch)
375 return Pred;
376 }
377 return 0;
378}
379
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000380
Chris Lattnerebe80752007-12-24 19:32:55 +0000381/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000382/// successor if it will improve codegen. We only do this if the successor has
383/// phi nodes (otherwise critical edges are ok). If there is already another
384/// predecessor of the succ that is empty (and thus has no phi nodes), use it
385/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000386static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000387 SmallSet<std::pair<const BasicBlock*,
388 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000389 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000390 BasicBlock *TIBB = TI->getParent();
391 BasicBlock *Dest = TI->getSuccessor(SuccNum);
392 assert(isa<PHINode>(Dest->begin()) &&
393 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000394 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000395
Evan Chengfc0b80d2009-03-13 22:59:14 +0000396 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000397 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000398 if (Invoke->getSuccessor(1) == Dest)
399 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000400
Chris Lattnerebe80752007-12-24 19:32:55 +0000401 // As a hack, never split backedges of loops. Even though the copy for any
402 // PHIs inserted on the backedge would be dead for exits from the loop, we
403 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000404 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000405 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000406
Chris Lattnerc09687b2010-02-13 19:07:06 +0000407 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
408 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
409 if (PFI)
410 PFI->splitEdge(TIBB, Dest, ReuseBB);
411 Dest->removePredecessor(TIBB);
412 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000413 return;
414 }
415
Chris Lattnerc09687b2010-02-13 19:07:06 +0000416 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000417}
418
Evan Chengab631522008-12-19 18:03:11 +0000419
Chris Lattnerdd77df32007-04-13 20:30:56 +0000420/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000421/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
422/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000423/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000424///
425/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000426///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000427static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000428 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000429 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
430 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000431
Chris Lattnerdd77df32007-04-13 20:30:56 +0000432 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000433 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000434 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000435
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436 // If this is an extension, it will be a zero or sign extension, which
437 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000438 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000439
Chris Lattnerdd77df32007-04-13 20:30:56 +0000440 // If these values will be promoted, find out what they will be promoted
441 // to. This helps us consider truncates on PPC as noop copies when they
442 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000443 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000444 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000445 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000446 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Chris Lattnerdd77df32007-04-13 20:30:56 +0000448 // If, after promotion, these are the same types, this is a noop copy.
449 if (SrcVT != DstVT)
450 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000453
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000455 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 UI != E; ) {
460 Use &TheUse = UI.getUse();
461 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 // Figure out which BB this cast is used in. For PHI's this is the
464 // appropriate predecessor block.
465 BasicBlock *UserBB = User->getParent();
466 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000467 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000468 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 // Preincrement use iterator so we don't invalidate it.
471 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000473 // If this user is in the same block as the cast, don't change the cast.
474 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000475
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 // If we have already inserted a cast into this block, use it.
477 CastInst *&InsertedCast = InsertedCasts[UserBB];
478
479 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000480 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000481
482 InsertedCast =
483 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000484 InsertPt);
485 MadeChange = true;
486 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Dale Johannesence0b2372007-06-12 16:50:17 +0000488 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 TheUse = InsertedCast;
490 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000493 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000495 MadeChange = true;
496 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 return MadeChange;
499}
500
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000502/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000503/// a clear win except on targets with multiple condition code registers
504/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000505///
506/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000507static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Dale Johannesence0b2372007-06-12 16:50:17 +0000510 /// InsertedCmp - Only insert a cmp in each block once.
511 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512
Dale Johannesence0b2372007-06-12 16:50:17 +0000513 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 UI != E; ) {
516 Use &TheUse = UI.getUse();
517 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 // Preincrement use iterator so we don't invalidate it.
520 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 // Don't bother for PHI nodes.
523 if (isa<PHINode>(User))
524 continue;
525
526 // Figure out which BB this cmp is used in.
527 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000528
Dale Johannesence0b2372007-06-12 16:50:17 +0000529 // If this user is in the same block as the cmp, don't change the cmp.
530 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Dale Johannesence0b2372007-06-12 16:50:17 +0000532 // If we have already inserted a cmp into this block, use it.
533 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
534
535 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000536 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537
538 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000539 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000540 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000541 CI->getOperand(1), "", InsertPt);
542 MadeChange = true;
543 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 // Replace a use of the cmp with a use of the new cmp.
546 TheUse = InsertedCmp;
547 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000548
Dale Johannesence0b2372007-06-12 16:50:17 +0000549 // If we removed all uses, nuke the cmp.
550 if (CI->use_empty())
551 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552
Dale Johannesence0b2372007-06-12 16:50:17 +0000553 return MadeChange;
554}
555
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000556namespace {
557class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
558protected:
559 void replaceCall(Value *With) {
560 CI->replaceAllUsesWith(With);
561 CI->eraseFromParent();
562 }
563 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000564 if (ConstantInt *SizeCI =
565 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
566 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000567 return false;
568 }
569};
570} // end anonymous namespace
571
Eric Christopher040056f2010-03-11 02:41:03 +0000572bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000573 // Lower all uses of llvm.objectsize.*
574 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
575 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000576 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000577 const Type *ReturnTy = CI->getType();
578 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
579 CI->replaceAllUsesWith(RetVal);
580 CI->eraseFromParent();
581 return true;
582 }
583
584 // From here on out we're working with named functions.
585 if (CI->getCalledFunction() == 0) return false;
586
587 // We'll need TargetData from here on out.
588 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
589 if (!TD) return false;
590
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000591 // Lower all default uses of _chk calls. This is very similar
592 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000593 // that have the default "don't know" as the objectsize. Anything else
594 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000595 CodeGenPrepareFortifiedLibCalls Simplifier;
596 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000597}
Chris Lattner88a5c832008-11-25 07:09:13 +0000598//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000599// Memory Optimization
600//===----------------------------------------------------------------------===//
601
Chris Lattnerdd77df32007-04-13 20:30:56 +0000602/// IsNonLocalValue - Return true if the specified values are defined in a
603/// different basic block than BB.
604static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
605 if (Instruction *I = dyn_cast<Instruction>(V))
606 return I->getParent() != BB;
607 return false;
608}
609
Bob Wilson4a8ee232009-12-03 21:47:07 +0000610/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000611/// addressing modes that can do significant amounts of computation. As such,
612/// instruction selection will try to get the load or store to do as much
613/// computation as possible for the program. The problem is that isel can only
614/// see within a single block. As such, we sink as much legal addressing mode
615/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000616///
617/// This method is used to optimize both load/store and inline asms with memory
618/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000619bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000620 const Type *AccessTy,
621 DenseMap<Value*,Value*> &SunkAddrs) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000622 Value *Repl = Addr;
623
Owen Andersond2f41742010-11-19 22:15:03 +0000624 // Try to collapse single-value PHI nodes. This is necessary to undo
625 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000626 SmallVector<Value*, 8> worklist;
627 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000628 worklist.push_back(Addr);
629
630 // Use a worklist to iteratively look through PHI nodes, and ensure that
631 // the addressing mode obtained from the non-PHI roots of the graph
632 // are equivalent.
633 Value *Consensus = 0;
634 unsigned NumUses = 0;
635 SmallVector<Instruction*, 16> AddrModeInsts;
636 ExtAddrMode AddrMode;
637 while (!worklist.empty()) {
638 Value *V = worklist.back();
639 worklist.pop_back();
640
641 // Break use-def graph loops.
642 if (Visited.count(V)) {
643 Consensus = 0;
644 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000645 }
646
Owen Anderson35bf4d62010-11-27 08:15:55 +0000647 Visited.insert(V);
648
649 // For a PHI node, push all of its incoming values.
650 if (PHINode *P = dyn_cast<PHINode>(V)) {
651 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
652 worklist.push_back(P->getIncomingValue(i));
653 continue;
654 }
655
656 // For non-PHIs, determine the addressing mode being computed.
657 SmallVector<Instruction*, 16> NewAddrModeInsts;
658 ExtAddrMode NewAddrMode =
659 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
660 NewAddrModeInsts, *TLI);
661
662 // Ensure that the obtained addressing mode is equivalent to that obtained
663 // for all other roots of the PHI traversal. Also, when choosing one
664 // such root as representative, select the one with the most uses in order
665 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
666 if (!Consensus || NewAddrMode == AddrMode) {
667 if (V->getNumUses() > NumUses) {
668 Consensus = V;
669 NumUses = V->getNumUses();
670 AddrMode = NewAddrMode;
671 AddrModeInsts = NewAddrModeInsts;
672 }
673 continue;
674 }
675
676 Consensus = 0;
677 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000678 }
679
Owen Anderson35bf4d62010-11-27 08:15:55 +0000680 // If the addressing mode couldn't be determined, or if multiple different
681 // ones were determined, bail out now.
682 if (!Consensus) return false;
683
Chris Lattnerdd77df32007-04-13 20:30:56 +0000684 // Check to see if any of the instructions supersumed by this addr mode are
685 // non-local to I's BB.
686 bool AnyNonLocal = false;
687 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000688 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000689 AnyNonLocal = true;
690 break;
691 }
692 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000693
Chris Lattnerdd77df32007-04-13 20:30:56 +0000694 // If all the instructions matched are already in this BB, don't do anything.
695 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000696 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000697 return false;
698 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000699
Chris Lattnerdd77df32007-04-13 20:30:56 +0000700 // Insert this computation right after this user. Since our caller is
701 // scanning from the top of the BB to the bottom, reuse of the expr are
702 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000703 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000704
Chris Lattnerdd77df32007-04-13 20:30:56 +0000705 // Now that we determined the addressing expression we want to use and know
706 // that we have to sink it into this block. Check to see if we have already
707 // done this for some other load/store instr in this block. If so, reuse the
708 // computation.
709 Value *&SunkAddr = SunkAddrs[Addr];
710 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000711 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000712 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000713 if (SunkAddr->getType() != Addr->getType())
714 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
715 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000716 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000717 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000718 const Type *IntPtrTy =
719 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000720
Chris Lattnerdd77df32007-04-13 20:30:56 +0000721 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000722
723 // Start with the base register. Do this first so that subsequent address
724 // matching finds it last, which will prevent it from trying to match it
725 // as the scaled value in case it happens to be a mul. That would be
726 // problematic if we've sunk a different mul for the scale, because then
727 // we'd end up sinking both muls.
728 if (AddrMode.BaseReg) {
729 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000730 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000731 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
732 if (V->getType() != IntPtrTy)
733 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
734 "sunkaddr", InsertPt);
735 Result = V;
736 }
737
738 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000739 if (AddrMode.Scale) {
740 Value *V = AddrMode.ScaledReg;
741 if (V->getType() == IntPtrTy) {
742 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000743 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000744 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
745 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
746 cast<IntegerType>(V->getType())->getBitWidth()) {
747 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
748 } else {
749 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
750 }
751 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000752 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000753 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000754 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000755 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000756 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000757 else
758 Result = V;
759 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000760
Chris Lattnerdd77df32007-04-13 20:30:56 +0000761 // Add in the BaseGV if present.
762 if (AddrMode.BaseGV) {
763 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
764 InsertPt);
765 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000766 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000767 else
768 Result = V;
769 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000770
Chris Lattnerdd77df32007-04-13 20:30:56 +0000771 // Add in the Base Offset if present.
772 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000773 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000774 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000775 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000776 else
777 Result = V;
778 }
779
780 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000781 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000782 else
783 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
784 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000785
Owen Andersond2f41742010-11-19 22:15:03 +0000786 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000787
Owen Andersond2f41742010-11-19 22:15:03 +0000788 if (Repl->use_empty()) {
789 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000790 // This address is now available for reassignment, so erase the table entry;
791 // we don't want to match some completely different instruction.
792 SunkAddrs[Addr] = 0;
793 }
Chris Lattnerdd77df32007-04-13 20:30:56 +0000794 return true;
795}
796
Evan Cheng9bf12b52008-02-26 02:42:37 +0000797/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000798/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000799/// possible / profitable.
800bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
801 DenseMap<Value*,Value*> &SunkAddrs) {
802 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000803
John Thompson44ab89e2010-10-29 17:29:13 +0000804 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000805 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000806 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
807 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
808
Evan Cheng9bf12b52008-02-26 02:42:37 +0000809 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000810 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000811
Eli Friedman9ec80952008-02-26 18:37:49 +0000812 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
813 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000814 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000815 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000816 } else if (OpInfo.Type == InlineAsm::isInput)
817 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000818 }
819
820 return MadeChange;
821}
822
Dan Gohmanb00f2362009-10-16 20:59:35 +0000823/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
824/// basic block as the load, unless conditions are unfavorable. This allows
825/// SelectionDAG to fold the extend into the load.
826///
827bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
828 // Look for a load being extended.
829 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
830 if (!LI) return false;
831
832 // If they're already in the same block, there's nothing to do.
833 if (LI->getParent() == I->getParent())
834 return false;
835
836 // If the load has other users and the truncate is not free, this probably
837 // isn't worthwhile.
838 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000839 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
840 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000841 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000842 return false;
843
844 // Check whether the target supports casts folded into loads.
845 unsigned LType;
846 if (isa<ZExtInst>(I))
847 LType = ISD::ZEXTLOAD;
848 else {
849 assert(isa<SExtInst>(I) && "Unexpected ext type!");
850 LType = ISD::SEXTLOAD;
851 }
852 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
853 return false;
854
855 // Move the extend into the same block as the load, so that SelectionDAG
856 // can fold it.
857 I->removeFromParent();
858 I->insertAfter(LI);
859 return true;
860}
861
Evan Chengbdcb7262007-12-05 23:58:20 +0000862bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
863 BasicBlock *DefBB = I->getParent();
864
Bob Wilson9120f5c2010-09-21 21:44:14 +0000865 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000866 // other uses of the source with result of extension.
867 Value *Src = I->getOperand(0);
868 if (Src->hasOneUse())
869 return false;
870
Evan Cheng696e5c02007-12-13 07:50:36 +0000871 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000872 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000873 return false;
874
Evan Cheng772de512007-12-12 00:51:06 +0000875 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000876 // this block.
877 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000878 return false;
879
Evan Chengbdcb7262007-12-05 23:58:20 +0000880 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000881 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000882 UI != E; ++UI) {
883 Instruction *User = cast<Instruction>(*UI);
884
885 // Figure out which BB this ext is used in.
886 BasicBlock *UserBB = User->getParent();
887 if (UserBB == DefBB) continue;
888 DefIsLiveOut = true;
889 break;
890 }
891 if (!DefIsLiveOut)
892 return false;
893
Evan Cheng765dff22007-12-12 02:53:41 +0000894 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000895 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000896 UI != E; ++UI) {
897 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000898 BasicBlock *UserBB = User->getParent();
899 if (UserBB == DefBB) continue;
900 // Be conservative. We don't want this xform to end up introducing
901 // reloads just before load / store instructions.
902 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000903 return false;
904 }
905
Evan Chengbdcb7262007-12-05 23:58:20 +0000906 // InsertedTruncs - Only insert one trunc in each block once.
907 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
908
909 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000910 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000911 UI != E; ++UI) {
912 Use &TheUse = UI.getUse();
913 Instruction *User = cast<Instruction>(*UI);
914
915 // Figure out which BB this ext is used in.
916 BasicBlock *UserBB = User->getParent();
917 if (UserBB == DefBB) continue;
918
919 // Both src and def are live in this block. Rewrite the use.
920 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
921
922 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000923 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000924
Evan Chengbdcb7262007-12-05 23:58:20 +0000925 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
926 }
927
928 // Replace a use of the {s|z}ext source with a use of the result.
929 TheUse = InsertedTrunc;
930
931 MadeChange = true;
932 }
933
934 return MadeChange;
935}
936
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000937// In this pass we look for GEP and cast instructions that are used
938// across basic blocks and rewrite them to improve basic-block-at-a-time
939// selection.
940bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
941 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000942
Evan Chengab631522008-12-19 18:03:11 +0000943 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +0000944 if (CriticalEdgeSplit) {
945 TerminatorInst *BBTI = BB.getTerminator();
946 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
947 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
948 BasicBlock *SuccBB = BBTI->getSuccessor(i);
949 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
950 SplitEdgeNicely(BBTI, i, BackEdges, this);
951 }
Evan Chengab631522008-12-19 18:03:11 +0000952 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000953 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000954
Chris Lattnerdd77df32007-04-13 20:30:56 +0000955 // Keep track of non-local addresses that have been sunk into this block.
956 // This allows us to avoid inserting duplicate code for blocks with multiple
957 // load/stores of the same address.
958 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000959
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000960 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
961 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000962
Owen Andersond5f86842010-12-23 20:57:35 +0000963 if (PHINode *P = dyn_cast<PHINode>(I)) {
964 // It is possible for very late stage optimizations (such as SimplifyCFG)
965 // to introduce PHI nodes too late to be cleaned up. If we detect such a
966 // trivial PHI, go ahead and zap it here.
967 if (Value *V = SimplifyInstruction(P)) {
968 P->replaceAllUsesWith(V);
969 P->eraseFromParent();
970 }
971 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000972 // If the source of the cast is a constant, then this should have
973 // already been constant folded. The only reason NOT to constant fold
974 // it is if something (e.g. LSR) was careful to place the constant
975 // evaluation in a block other than then one that uses it (e.g. to hoist
976 // the address of globals out of a loop). If this is the case, we don't
977 // want to forward-subst the cast.
978 if (isa<Constant>(CI->getOperand(0)))
979 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000980
Evan Chengbdcb7262007-12-05 23:58:20 +0000981 bool Change = false;
982 if (TLI) {
983 Change = OptimizeNoopCopyExpression(CI, *TLI);
984 MadeChange |= Change;
985 }
986
Dan Gohmanb00f2362009-10-16 20:59:35 +0000987 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
988 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000989 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000990 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000991 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
992 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000993 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
994 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000995 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
996 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000997 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
998 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000999 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1000 SI->getOperand(0)->getType(),
1001 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001002 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +00001003 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +00001004 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +00001005 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +00001006 GEPI->getName(), GEPI);
1007 GEPI->replaceAllUsesWith(NC);
1008 GEPI->eraseFromParent();
1009 MadeChange = true;
1010 BBI = NC;
1011 }
1012 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1013 // If we found an inline asm expession, and if the target knows how to
1014 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +00001015 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1016 if (TLI->ExpandInlineAsm(CI)) {
1017 BBI = BB.begin();
1018 // Avoid processing instructions out of order, which could cause
1019 // reuse before a value is defined.
1020 SunkAddrs.clear();
1021 } else
1022 // Sink address computing for memory operands into the block.
1023 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +00001024 } else {
1025 // Other CallInst optimizations that don't need to muck with the
1026 // enclosing iterator here.
1027 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +00001028 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001029 }
1030 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001031
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001032 return MadeChange;
1033}