blob: 960ef1e6b2efdb9db901fb0901b2cd494d3bfa5b [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000025#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000028#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000030#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000031#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000039#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000040#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000042using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043
Eric Christopher692bf6b2008-09-24 05:32:41 +000044namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000045 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000046 /// TLI - Keep a pointer of a TargetLowering to consult for determining
47 /// transformation profitability.
48 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000049 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000050
51 /// BackEdges - Keep a set of all the loop back edges.
52 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000053 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000054 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000056 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000057 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000058 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000059
Andreas Neustifterad809812009-09-16 09:26:52 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addPreserved<ProfileInfo>();
62 }
63
Dan Gohmanaa0e5232010-02-05 19:24:11 +000064 virtual void releaseMemory() {
65 BackEdges.clear();
66 }
67
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000068 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000069 bool EliminateMostlyEmptyBlocks(Function &F);
70 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
71 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000072 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000073 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
74 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000075 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
76 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +000077 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +000078 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000079 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000080 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000081 };
82}
Devang Patel794fd752007-05-01 21:15:47 +000083
Devang Patel19974732007-05-03 01:11:54 +000084char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000085static RegisterPass<CodeGenPrepare> X("codegenprepare",
86 "Optimize for code generation");
87
88FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
89 return new CodeGenPrepare(TLI);
90}
91
Evan Chengab631522008-12-19 18:03:11 +000092/// findLoopBackEdges - Do a DFS walk to find loop back edges.
93///
Mike Stumpfe095f32009-05-04 18:40:41 +000094void CodeGenPrepare::findLoopBackEdges(const Function &F) {
95 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
96 FindFunctionBackedges(F, Edges);
97
98 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +000099}
100
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101
102bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000103 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000104
Evan Cheng04149f72009-12-17 09:39:49 +0000105 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000106 // First pass, eliminate blocks that contain only PHI nodes and an
107 // unconditional branch.
108 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000109
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000110 // Now find loop back edges.
111 findLoopBackEdges(F);
112
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000113 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000114 while (MadeChange) {
115 MadeChange = false;
116 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
117 MadeChange |= OptimizeBlock(*BB);
118 EverMadeChange |= MadeChange;
119 }
120 return EverMadeChange;
121}
122
Dale Johannesen2d697242009-03-27 01:13:37 +0000123/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
124/// debug info directives, and an unconditional branch. Passes before isel
125/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
126/// isel. Start by eliminating these blocks so we can split them the way we
127/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000128bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
129 bool MadeChange = false;
130 // Note that this intentionally skips the entry block.
131 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
132 BasicBlock *BB = I++;
133
134 // If this block doesn't end with an uncond branch, ignore it.
135 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
136 if (!BI || !BI->isUnconditional())
137 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000138
Dale Johannesen2d697242009-03-27 01:13:37 +0000139 // If the instruction before the branch (skipping debug info) isn't a phi
140 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000141 BasicBlock::iterator BBI = BI;
142 if (BBI != BB->begin()) {
143 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000144 while (isa<DbgInfoIntrinsic>(BBI)) {
145 if (BBI == BB->begin())
146 break;
147 --BBI;
148 }
149 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
150 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000151 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000152
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000153 // Do not break infinite loops.
154 BasicBlock *DestBB = BI->getSuccessor(0);
155 if (DestBB == BB)
156 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000157
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000158 if (!CanMergeBlocks(BB, DestBB))
159 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000160
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000161 EliminateMostlyEmptyBlock(BB);
162 MadeChange = true;
163 }
164 return MadeChange;
165}
166
167/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
168/// single uncond branch between them, and BB contains no other non-phi
169/// instructions.
170bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
171 const BasicBlock *DestBB) const {
172 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
173 // the successor. If there are more complex condition (e.g. preheaders),
174 // don't mess around with them.
175 BasicBlock::const_iterator BBI = BB->begin();
176 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000177 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000178 UI != E; ++UI) {
179 const Instruction *User = cast<Instruction>(*UI);
180 if (User->getParent() != DestBB || !isa<PHINode>(User))
181 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000182 // If User is inside DestBB block and it is a PHINode then check
183 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000184 // a complex condition (e.g. preheaders) we want to avoid here.
185 if (User->getParent() == DestBB) {
186 if (const PHINode *UPN = dyn_cast<PHINode>(User))
187 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
188 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
189 if (Insn && Insn->getParent() == BB &&
190 Insn->getParent() != UPN->getIncomingBlock(I))
191 return false;
192 }
193 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000194 }
195 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000196
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000197 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
198 // and DestBB may have conflicting incoming values for the block. If so, we
199 // can't merge the block.
200 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
201 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000202
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000204 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000205 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
206 // It is faster to get preds from a PHI than with pred_iterator.
207 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
208 BBPreds.insert(BBPN->getIncomingBlock(i));
209 } else {
210 BBPreds.insert(pred_begin(BB), pred_end(BB));
211 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000212
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000213 // Walk the preds of DestBB.
214 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
215 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
216 if (BBPreds.count(Pred)) { // Common predecessor?
217 BBI = DestBB->begin();
218 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
219 const Value *V1 = PN->getIncomingValueForBlock(Pred);
220 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000221
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000222 // If V2 is a phi node in BB, look up what the mapped value will be.
223 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
224 if (V2PN->getParent() == BB)
225 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000226
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000227 // If there is a conflict, bail out.
228 if (V1 != V2) return false;
229 }
230 }
231 }
232
233 return true;
234}
235
236
237/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
238/// an unconditional branch in it.
239void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
240 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
241 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000242
David Greene68d67fd2010-01-05 01:27:11 +0000243 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000244
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000245 // If the destination block has a single pred, then this is a trivial edge,
246 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000247 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000248 if (SinglePred != DestBB) {
249 // Remember if SinglePred was the entry block of the function. If so, we
250 // will need to move BB back to the entry position.
251 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000252 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000253
Chris Lattnerf5102a02008-11-28 19:54:49 +0000254 if (isEntry && BB != &BB->getParent()->getEntryBlock())
255 BB->moveBefore(&BB->getParent()->getEntryBlock());
256
David Greene68d67fd2010-01-05 01:27:11 +0000257 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000258 return;
259 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000260 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000261
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000262 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
263 // to handle the new incoming edges it is about to have.
264 PHINode *PN;
265 for (BasicBlock::iterator BBI = DestBB->begin();
266 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
267 // Remove the incoming value for BB, and remember it.
268 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000269
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270 // Two options: either the InVal is a phi node defined in BB or it is some
271 // value that dominates BB.
272 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
273 if (InValPhi && InValPhi->getParent() == BB) {
274 // Add all of the input values of the input PHI as inputs of this phi.
275 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
276 PN->addIncoming(InValPhi->getIncomingValue(i),
277 InValPhi->getIncomingBlock(i));
278 } else {
279 // Otherwise, add one instance of the dominating value for each edge that
280 // we will be adding.
281 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
282 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
283 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
284 } else {
285 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
286 PN->addIncoming(InVal, *PI);
287 }
288 }
289 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000290
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000291 // The PHIs are now updated, change everything that refers to BB to use
292 // DestBB and remove BB.
293 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000294 if (PFI) {
295 PFI->replaceAllUses(BB, DestBB);
296 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000297 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000298 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
David Greene68d67fd2010-01-05 01:27:11 +0000300 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000301}
302
Chris Lattner98d5c312010-02-13 05:35:08 +0000303/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
304/// lives in to see if there is a block that we can reuse as a critical edge
305/// from TIBB.
306static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
307 BasicBlock *Dest = DestPHI->getParent();
308
309 /// TIPHIValues - This array is lazily computed to determine the values of
310 /// PHIs in Dest that TI would provide.
311 SmallVector<Value*, 32> TIPHIValues;
312
313 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
314 unsigned TIBBEntryNo = 0;
315
316 // Check to see if Dest has any blocks that can be used as a split edge for
317 // this terminator.
318 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
319 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
320 // To be usable, the pred has to end with an uncond branch to the dest.
321 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
322 if (!PredBr || !PredBr->isUnconditional())
323 continue;
324 // Must be empty other than the branch and debug info.
325 BasicBlock::iterator I = Pred->begin();
326 while (isa<DbgInfoIntrinsic>(I))
327 I++;
328 if (&*I != PredBr)
329 continue;
330 // Cannot be the entry block; its label does not get emitted.
331 if (Pred == &Dest->getParent()->getEntryBlock())
332 continue;
333
334 // Finally, since we know that Dest has phi nodes in it, we have to make
335 // sure that jumping to Pred will have the same effect as going to Dest in
336 // terms of PHI values.
337 PHINode *PN;
338 unsigned PHINo = 0;
339 unsigned PredEntryNo = pi;
340
341 bool FoundMatch = true;
342 for (BasicBlock::iterator I = Dest->begin();
343 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
344 if (PHINo == TIPHIValues.size()) {
345 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
346 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
347 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
348 }
349
350 // If the PHI entry doesn't work, we can't use this pred.
351 if (PN->getIncomingBlock(PredEntryNo) != Pred)
352 PredEntryNo = PN->getBasicBlockIndex(Pred);
353
354 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
355 FoundMatch = false;
356 break;
357 }
358 }
359
360 // If we found a workable predecessor, change TI to branch to Succ.
361 if (FoundMatch)
362 return Pred;
363 }
364 return 0;
365}
366
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000367
Chris Lattnerebe80752007-12-24 19:32:55 +0000368/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000369/// successor if it will improve codegen. We only do this if the successor has
370/// phi nodes (otherwise critical edges are ok). If there is already another
371/// predecessor of the succ that is empty (and thus has no phi nodes), use it
372/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000373static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000374 SmallSet<std::pair<const BasicBlock*,
375 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000376 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000377 BasicBlock *TIBB = TI->getParent();
378 BasicBlock *Dest = TI->getSuccessor(SuccNum);
379 assert(isa<PHINode>(Dest->begin()) &&
380 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000381 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000382
Evan Chengfc0b80d2009-03-13 22:59:14 +0000383 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000384 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000385 if (Invoke->getSuccessor(1) == Dest)
386 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000387
Chris Lattnerebe80752007-12-24 19:32:55 +0000388 // As a hack, never split backedges of loops. Even though the copy for any
389 // PHIs inserted on the backedge would be dead for exits from the loop, we
390 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000391 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000392 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000393
Chris Lattnerc09687b2010-02-13 19:07:06 +0000394 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
395 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
396 if (PFI)
397 PFI->splitEdge(TIBB, Dest, ReuseBB);
398 Dest->removePredecessor(TIBB);
399 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000400 return;
401 }
402
Chris Lattnerc09687b2010-02-13 19:07:06 +0000403 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000404}
405
Evan Chengab631522008-12-19 18:03:11 +0000406
Chris Lattnerdd77df32007-04-13 20:30:56 +0000407/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000408/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
409/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000410/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000411///
412/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000413///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000414static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000416 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
417 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000418
Chris Lattnerdd77df32007-04-13 20:30:56 +0000419 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000420 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000421 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000422
Chris Lattnerdd77df32007-04-13 20:30:56 +0000423 // If this is an extension, it will be a zero or sign extension, which
424 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000425 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000426
Chris Lattnerdd77df32007-04-13 20:30:56 +0000427 // If these values will be promoted, find out what they will be promoted
428 // to. This helps us consider truncates on PPC as noop copies when they
429 // are.
Owen Anderson23b9b192009-08-12 00:36:31 +0000430 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
431 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
432 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
433 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434
Chris Lattnerdd77df32007-04-13 20:30:56 +0000435 // If, after promotion, these are the same types, this is a noop copy.
436 if (SrcVT != DstVT)
437 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000438
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000439 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000441 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000442 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000443
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000444 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000446 UI != E; ) {
447 Use &TheUse = UI.getUse();
448 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450 // Figure out which BB this cast is used in. For PHI's this is the
451 // appropriate predecessor block.
452 BasicBlock *UserBB = User->getParent();
453 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000454 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000455 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000456
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457 // Preincrement use iterator so we don't invalidate it.
458 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000459
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000460 // If this user is in the same block as the cast, don't change the cast.
461 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 // If we have already inserted a cast into this block, use it.
464 CastInst *&InsertedCast = InsertedCasts[UserBB];
465
466 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000467 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
469 InsertedCast =
470 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000471 InsertPt);
472 MadeChange = true;
473 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Dale Johannesence0b2372007-06-12 16:50:17 +0000475 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000476 TheUse = InsertedCast;
477 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000478
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000479 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000480 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000482 MadeChange = true;
483 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 return MadeChange;
486}
487
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000489/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000490/// a clear win except on targets with multiple condition code registers
491/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000492///
493/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000494static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000495 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496
Dale Johannesence0b2372007-06-12 16:50:17 +0000497 /// InsertedCmp - Only insert a cmp in each block once.
498 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499
Dale Johannesence0b2372007-06-12 16:50:17 +0000500 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000502 UI != E; ) {
503 Use &TheUse = UI.getUse();
504 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 // Preincrement use iterator so we don't invalidate it.
507 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000508
Dale Johannesence0b2372007-06-12 16:50:17 +0000509 // Don't bother for PHI nodes.
510 if (isa<PHINode>(User))
511 continue;
512
513 // Figure out which BB this cmp is used in.
514 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000515
Dale Johannesence0b2372007-06-12 16:50:17 +0000516 // If this user is in the same block as the cmp, don't change the cmp.
517 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 // If we have already inserted a cmp into this block, use it.
520 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
521
522 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000523 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
525 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000526 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000527 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 CI->getOperand(1), "", InsertPt);
529 MadeChange = true;
530 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000531
Dale Johannesence0b2372007-06-12 16:50:17 +0000532 // Replace a use of the cmp with a use of the new cmp.
533 TheUse = InsertedCmp;
534 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000535
Dale Johannesence0b2372007-06-12 16:50:17 +0000536 // If we removed all uses, nuke the cmp.
537 if (CI->use_empty())
538 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 return MadeChange;
541}
542
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000543namespace {
544class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
545protected:
546 void replaceCall(Value *With) {
547 CI->replaceAllUsesWith(With);
548 CI->eraseFromParent();
549 }
550 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000551 if (ConstantInt *SizeCI =
552 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
553 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000554 return false;
555 }
556};
557} // end anonymous namespace
558
Eric Christopher040056f2010-03-11 02:41:03 +0000559bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000560 // Lower all uses of llvm.objectsize.*
561 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
562 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000563 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000564 const Type *ReturnTy = CI->getType();
565 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
566 CI->replaceAllUsesWith(RetVal);
567 CI->eraseFromParent();
568 return true;
569 }
570
571 // From here on out we're working with named functions.
572 if (CI->getCalledFunction() == 0) return false;
573
574 // We'll need TargetData from here on out.
575 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
576 if (!TD) return false;
577
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000578 // Lower all default uses of _chk calls. This is very similar
579 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000580 // that have the default "don't know" as the objectsize. Anything else
581 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000582 CodeGenPrepareFortifiedLibCalls Simplifier;
583 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000584}
Chris Lattner88a5c832008-11-25 07:09:13 +0000585//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000586// Memory Optimization
587//===----------------------------------------------------------------------===//
588
Chris Lattnerdd77df32007-04-13 20:30:56 +0000589/// IsNonLocalValue - Return true if the specified values are defined in a
590/// different basic block than BB.
591static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
592 if (Instruction *I = dyn_cast<Instruction>(V))
593 return I->getParent() != BB;
594 return false;
595}
596
Bob Wilson4a8ee232009-12-03 21:47:07 +0000597/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000598/// addressing modes that can do significant amounts of computation. As such,
599/// instruction selection will try to get the load or store to do as much
600/// computation as possible for the program. The problem is that isel can only
601/// see within a single block. As such, we sink as much legal addressing mode
602/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000603///
604/// This method is used to optimize both load/store and inline asms with memory
605/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000606bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000607 const Type *AccessTy,
608 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000609 // Figure out what addressing mode will be built up for this operation.
610 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000611 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
612 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000613
Chris Lattnerdd77df32007-04-13 20:30:56 +0000614 // Check to see if any of the instructions supersumed by this addr mode are
615 // non-local to I's BB.
616 bool AnyNonLocal = false;
617 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000618 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000619 AnyNonLocal = true;
620 break;
621 }
622 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000623
Chris Lattnerdd77df32007-04-13 20:30:56 +0000624 // If all the instructions matched are already in this BB, don't do anything.
625 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000626 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000627 return false;
628 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000629
Chris Lattnerdd77df32007-04-13 20:30:56 +0000630 // Insert this computation right after this user. Since our caller is
631 // scanning from the top of the BB to the bottom, reuse of the expr are
632 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000633 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000634
Chris Lattnerdd77df32007-04-13 20:30:56 +0000635 // Now that we determined the addressing expression we want to use and know
636 // that we have to sink it into this block. Check to see if we have already
637 // done this for some other load/store instr in this block. If so, reuse the
638 // computation.
639 Value *&SunkAddr = SunkAddrs[Addr];
640 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000641 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000642 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000643 if (SunkAddr->getType() != Addr->getType())
644 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
645 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000646 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000647 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000648 const Type *IntPtrTy =
649 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000650
Chris Lattnerdd77df32007-04-13 20:30:56 +0000651 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000652
653 // Start with the base register. Do this first so that subsequent address
654 // matching finds it last, which will prevent it from trying to match it
655 // as the scaled value in case it happens to be a mul. That would be
656 // problematic if we've sunk a different mul for the scale, because then
657 // we'd end up sinking both muls.
658 if (AddrMode.BaseReg) {
659 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000660 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000661 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
662 if (V->getType() != IntPtrTy)
663 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
664 "sunkaddr", InsertPt);
665 Result = V;
666 }
667
668 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000669 if (AddrMode.Scale) {
670 Value *V = AddrMode.ScaledReg;
671 if (V->getType() == IntPtrTy) {
672 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000673 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000674 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
675 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
676 cast<IntegerType>(V->getType())->getBitWidth()) {
677 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
678 } else {
679 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
680 }
681 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000682 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000683 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000684 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000685 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000686 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000687 else
688 Result = V;
689 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000690
Chris Lattnerdd77df32007-04-13 20:30:56 +0000691 // Add in the BaseGV if present.
692 if (AddrMode.BaseGV) {
693 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
694 InsertPt);
695 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000696 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000697 else
698 Result = V;
699 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000700
Chris Lattnerdd77df32007-04-13 20:30:56 +0000701 // Add in the Base Offset if present.
702 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000703 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000704 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000705 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000706 else
707 Result = V;
708 }
709
710 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000711 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000712 else
713 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
714 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000715
Chris Lattner896617b2008-11-26 03:20:37 +0000716 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000717
Dale Johannesen536d31b2010-03-31 20:37:15 +0000718 if (Addr->use_empty()) {
Chris Lattner3481f242008-11-27 22:57:53 +0000719 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000720 // This address is now available for reassignment, so erase the table entry;
721 // we don't want to match some completely different instruction.
722 SunkAddrs[Addr] = 0;
723 }
Chris Lattnerdd77df32007-04-13 20:30:56 +0000724 return true;
725}
726
Evan Cheng9bf12b52008-02-26 02:42:37 +0000727/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000728/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000729/// possible / profitable.
730bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
731 DenseMap<Value*,Value*> &SunkAddrs) {
732 bool MadeChange = false;
733 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
734
735 // Do a prepass over the constraints, canonicalizing them, and building up the
736 // ConstraintOperands list.
737 std::vector<InlineAsm::ConstraintInfo>
738 ConstraintInfos = IA->ParseConstraints();
739
740 /// ConstraintOperands - Information about all of the constraints.
741 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
742 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
743 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
744 ConstraintOperands.
745 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
746 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
747
748 // Compute the value type for each operand.
749 switch (OpInfo.Type) {
750 case InlineAsm::isOutput:
751 if (OpInfo.isIndirect)
752 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
753 break;
754 case InlineAsm::isInput:
755 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
756 break;
757 case InlineAsm::isClobber:
758 // Nothing to do.
759 break;
760 }
761
762 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000763 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000764
Eli Friedman9ec80952008-02-26 18:37:49 +0000765 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
766 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000767 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000768 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000769 }
770 }
771
772 return MadeChange;
773}
774
Dan Gohmanb00f2362009-10-16 20:59:35 +0000775/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
776/// basic block as the load, unless conditions are unfavorable. This allows
777/// SelectionDAG to fold the extend into the load.
778///
779bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
780 // Look for a load being extended.
781 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
782 if (!LI) return false;
783
784 // If they're already in the same block, there's nothing to do.
785 if (LI->getParent() == I->getParent())
786 return false;
787
788 // If the load has other users and the truncate is not free, this probably
789 // isn't worthwhile.
790 if (!LI->hasOneUse() &&
791 TLI && !TLI->isTruncateFree(I->getType(), LI->getType()))
792 return false;
793
794 // Check whether the target supports casts folded into loads.
795 unsigned LType;
796 if (isa<ZExtInst>(I))
797 LType = ISD::ZEXTLOAD;
798 else {
799 assert(isa<SExtInst>(I) && "Unexpected ext type!");
800 LType = ISD::SEXTLOAD;
801 }
802 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
803 return false;
804
805 // Move the extend into the same block as the load, so that SelectionDAG
806 // can fold it.
807 I->removeFromParent();
808 I->insertAfter(LI);
809 return true;
810}
811
Evan Chengbdcb7262007-12-05 23:58:20 +0000812bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
813 BasicBlock *DefBB = I->getParent();
814
815 // If both result of the {s|z}xt and its source are live out, rewrite all
816 // other uses of the source with result of extension.
817 Value *Src = I->getOperand(0);
818 if (Src->hasOneUse())
819 return false;
820
Evan Cheng696e5c02007-12-13 07:50:36 +0000821 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000822 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000823 return false;
824
Evan Cheng772de512007-12-12 00:51:06 +0000825 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000826 // this block.
827 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000828 return false;
829
Evan Chengbdcb7262007-12-05 23:58:20 +0000830 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000831 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000832 UI != E; ++UI) {
833 Instruction *User = cast<Instruction>(*UI);
834
835 // Figure out which BB this ext is used in.
836 BasicBlock *UserBB = User->getParent();
837 if (UserBB == DefBB) continue;
838 DefIsLiveOut = true;
839 break;
840 }
841 if (!DefIsLiveOut)
842 return false;
843
Evan Cheng765dff22007-12-12 02:53:41 +0000844 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000845 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000846 UI != E; ++UI) {
847 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000848 BasicBlock *UserBB = User->getParent();
849 if (UserBB == DefBB) continue;
850 // Be conservative. We don't want this xform to end up introducing
851 // reloads just before load / store instructions.
852 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000853 return false;
854 }
855
Evan Chengbdcb7262007-12-05 23:58:20 +0000856 // InsertedTruncs - Only insert one trunc in each block once.
857 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
858
859 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000860 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000861 UI != E; ++UI) {
862 Use &TheUse = UI.getUse();
863 Instruction *User = cast<Instruction>(*UI);
864
865 // Figure out which BB this ext is used in.
866 BasicBlock *UserBB = User->getParent();
867 if (UserBB == DefBB) continue;
868
869 // Both src and def are live in this block. Rewrite the use.
870 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
871
872 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000873 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000874
Evan Chengbdcb7262007-12-05 23:58:20 +0000875 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
876 }
877
878 // Replace a use of the {s|z}ext source with a use of the result.
879 TheUse = InsertedTrunc;
880
881 MadeChange = true;
882 }
883
884 return MadeChange;
885}
886
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000887// In this pass we look for GEP and cast instructions that are used
888// across basic blocks and rewrite them to improve basic-block-at-a-time
889// selection.
890bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
891 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000892
Evan Chengab631522008-12-19 18:03:11 +0000893 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000894 TerminatorInst *BBTI = BB.getTerminator();
Chris Lattnera4b04212009-10-31 22:04:43 +0000895 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
Evan Chengab631522008-12-19 18:03:11 +0000896 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
897 BasicBlock *SuccBB = BBTI->getSuccessor(i);
898 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
899 SplitEdgeNicely(BBTI, i, BackEdges, this);
900 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000901 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000902
Chris Lattnerdd77df32007-04-13 20:30:56 +0000903 // Keep track of non-local addresses that have been sunk into this block.
904 // This allows us to avoid inserting duplicate code for blocks with multiple
905 // load/stores of the same address.
906 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000907
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000908 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
909 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000910
Chris Lattnerdd77df32007-04-13 20:30:56 +0000911 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000912 // If the source of the cast is a constant, then this should have
913 // already been constant folded. The only reason NOT to constant fold
914 // it is if something (e.g. LSR) was careful to place the constant
915 // evaluation in a block other than then one that uses it (e.g. to hoist
916 // the address of globals out of a loop). If this is the case, we don't
917 // want to forward-subst the cast.
918 if (isa<Constant>(CI->getOperand(0)))
919 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000920
Evan Chengbdcb7262007-12-05 23:58:20 +0000921 bool Change = false;
922 if (TLI) {
923 Change = OptimizeNoopCopyExpression(CI, *TLI);
924 MadeChange |= Change;
925 }
926
Dan Gohmanb00f2362009-10-16 20:59:35 +0000927 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
928 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000929 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000930 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000931 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
932 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000933 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
934 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000935 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
936 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000937 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
938 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000939 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
940 SI->getOperand(0)->getType(),
941 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000942 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000943 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000944 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000945 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000946 GEPI->getName(), GEPI);
947 GEPI->replaceAllUsesWith(NC);
948 GEPI->eraseFromParent();
949 MadeChange = true;
950 BBI = NC;
951 }
952 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
953 // If we found an inline asm expession, and if the target knows how to
954 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000955 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
956 if (TLI->ExpandInlineAsm(CI)) {
957 BBI = BB.begin();
958 // Avoid processing instructions out of order, which could cause
959 // reuse before a value is defined.
960 SunkAddrs.clear();
961 } else
962 // Sink address computing for memory operands into the block.
963 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +0000964 } else {
965 // Other CallInst optimizations that don't need to muck with the
966 // enclosing iterator here.
967 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +0000968 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000969 }
970 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000971
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000972 return MadeChange;
973}