blob: ed12b2e7537efb7a094ea2a75d34557a0994119b [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-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 Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Nick Lewycky5fb19632013-05-08 09:00:10 +000021#include "llvm/ADT/ValueMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/DominatorInternals.h"
23#include "llvm/Analysis/Dominators.h"
24#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InlineAsm.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000033#include "llvm/Pass.h"
Evan Cheng1da25002008-02-26 02:42:37 +000034#include "llvm/Support/CallSite.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000035#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000036#include "llvm/Support/Debug.h"
Chris Lattnerfeee64e2007-04-13 20:30:56 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd616ef52008-11-25 04:42:10 +000038#include "llvm/Support/PatternMatch.h"
Chris Lattner1b93be52011-01-15 07:25:29 +000039#include "llvm/Support/ValueHandle.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000040#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000041#include "llvm/Target/TargetLibraryInfo.h"
42#include "llvm/Target/TargetLowering.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000045#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000049
Cameron Zwarichced753f2011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000064
Cameron Zwarich338d3622011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Benjamin Kramer3d38c172012-05-06 14:25:16 +000069static cl::opt<bool> DisableSelectToBranch(
70 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000072
Eric Christopherc1ea1492008-09-24 05:32:41 +000073namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000074 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000075 /// TLI - Keep a pointer of a TargetLowering to consult for determining
76 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000077 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000078 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000079 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000080 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000081
Chris Lattner7a277142011-01-15 07:14:54 +000082 /// CurInstIterator - As we scan instructions optimizing them, this is the
83 /// next instruction to optimize. Xforms that can invalidate this should
84 /// update it.
85 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000086
Evan Cheng0663f232011-03-21 01:19:09 +000087 /// Keeps track of non-local addresses that have been sunk into a block.
88 /// This allows us to avoid inserting duplicate code for blocks with
89 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +000090 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +000091
Devang Patel8f606d72011-03-24 15:35:25 +000092 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +000093 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +000094 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +000095
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000096 /// OptSize - True if optimizing for size.
97 bool OptSize;
98
Chris Lattnerf2836d12007-03-31 04:06:36 +000099 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000100 static char ID; // Pass identification, replacement for typeid
Bill Wendling7a639ea2013-06-19 21:07:11 +0000101 explicit CodeGenPrepare(const TargetMachine *TM = 0)
102 : FunctionPass(ID), TM(TM), TLI(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000103 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
104 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000105 bool runOnFunction(Function &F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000106
Evan Cheng99cafb12012-12-21 01:48:14 +0000107 const char *getPassName() const { return "CodeGen Prepare"; }
108
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000110 AU.addPreserved<DominatorTree>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000111 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000112 }
113
Chris Lattnerf2836d12007-03-31 04:06:36 +0000114 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000115 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000116 bool EliminateMostlyEmptyBlocks(Function &F);
117 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
118 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000119 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000120 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000121 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000122 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000123 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000124 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000125 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000127 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000128 bool PlaceDbgValues(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000129 };
130}
Devang Patel09f162c2007-05-01 21:15:47 +0000131
Devang Patel8c78a0b2007-05-03 01:11:54 +0000132char CodeGenPrepare::ID = 0;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000133INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
134 "Optimize for code generation", false, false)
135INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
136INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000137 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000138
Bill Wendling7a639ea2013-06-19 21:07:11 +0000139FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
140 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000141}
142
Chris Lattnerf2836d12007-03-31 04:06:36 +0000143bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000144 bool EverMadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000145
Devang Patel8f606d72011-03-24 15:35:25 +0000146 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000147 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000148 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich84986b22011-01-08 17:01:52 +0000149 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling698e84f2012-12-30 10:32:01 +0000150 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
151 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000152
Preston Gurdcdf540d2012-09-04 18:22:17 +0000153 /// This optimization identifies DIV instructions that can be
154 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000155 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000156 const DenseMap<unsigned int, unsigned int> &BypassWidths =
157 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000158 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000159 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000160 }
161
162 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000163 // unconditional branch.
164 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000165
Devang Patel53771ba2011-08-18 00:50:51 +0000166 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000167 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000168 // find a node corresponding to the value.
169 EverMadeChange |= PlaceDbgValues(F);
170
Chris Lattnerc3748562007-04-02 01:35:34 +0000171 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000172 while (MadeChange) {
173 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000174 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000175 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000176 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000177 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000178 EverMadeChange |= MadeChange;
179 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000180
181 SunkAddrs.clear();
182
Cameron Zwarich338d3622011-03-11 21:52:04 +0000183 if (!DisableBranchOpts) {
184 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000185 SmallPtrSet<BasicBlock*, 8> WorkList;
186 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
187 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000188 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000189 if (!MadeChange) continue;
190
191 for (SmallVectorImpl<BasicBlock*>::iterator
192 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
193 if (pred_begin(*II) == pred_end(*II))
194 WorkList.insert(*II);
195 }
196
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000197 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000198 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000199 while (!WorkList.empty()) {
200 BasicBlock *BB = *WorkList.begin();
201 WorkList.erase(BB);
202 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
203
204 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000205
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000206 for (SmallVectorImpl<BasicBlock*>::iterator
207 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
208 if (pred_begin(*II) == pred_end(*II))
209 WorkList.insert(*II);
210 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000211
Nadav Rotem70409992012-08-14 05:19:07 +0000212 // Merge pairs of basic blocks with unconditional branches, connected by
213 // a single edge.
214 if (EverMadeChange || MadeChange)
215 MadeChange |= EliminateFallThrough(F);
216
Evan Cheng0663f232011-03-21 01:19:09 +0000217 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000218 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000219 EverMadeChange |= MadeChange;
220 }
221
Devang Patel8f606d72011-03-24 15:35:25 +0000222 if (ModifiedDT && DT)
Evan Cheng0663f232011-03-21 01:19:09 +0000223 DT->DT->recalculate(F);
224
Chris Lattnerf2836d12007-03-31 04:06:36 +0000225 return EverMadeChange;
226}
227
Nadav Rotem70409992012-08-14 05:19:07 +0000228/// EliminateFallThrough - Merge basic blocks which are connected
229/// by a single edge, where one of the basic blocks has a single successor
230/// pointing to the other basic block, which has a single predecessor.
231bool CodeGenPrepare::EliminateFallThrough(Function &F) {
232 bool Changed = false;
233 // Scan all of the blocks in the function, except for the entry block.
234 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
235 BasicBlock *BB = I++;
236 // If the destination block has a single pred, then this is a trivial
237 // edge, just collapse it.
238 BasicBlock *SinglePred = BB->getSinglePredecessor();
239
Evan Cheng64a223a2012-09-28 23:58:57 +0000240 // Don't merge if BB's address is taken.
241 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000242
243 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
244 if (Term && !Term->isConditional()) {
245 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000246 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000247 // Remember if SinglePred was the entry block of the function.
248 // If so, we will need to move BB back to the entry position.
249 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
250 MergeBasicBlockIntoOnlyPred(BB, this);
251
252 if (isEntry && BB != &BB->getParent()->getEntryBlock())
253 BB->moveBefore(&BB->getParent()->getEntryBlock());
254
255 // We have erased a block. Update the iterator.
256 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000257 }
258 }
259 return Changed;
260}
261
Dale Johannesen4026b042009-03-27 01:13:37 +0000262/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
263/// debug info directives, and an unconditional branch. Passes before isel
264/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
265/// isel. Start by eliminating these blocks so we can split them the way we
266/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000267bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
268 bool MadeChange = false;
269 // Note that this intentionally skips the entry block.
270 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
271 BasicBlock *BB = I++;
272
273 // If this block doesn't end with an uncond branch, ignore it.
274 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
275 if (!BI || !BI->isUnconditional())
276 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000277
Dale Johannesen4026b042009-03-27 01:13:37 +0000278 // If the instruction before the branch (skipping debug info) isn't a phi
279 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000280 BasicBlock::iterator BBI = BI;
281 if (BBI != BB->begin()) {
282 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000283 while (isa<DbgInfoIntrinsic>(BBI)) {
284 if (BBI == BB->begin())
285 break;
286 --BBI;
287 }
288 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
289 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000290 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000291
Chris Lattnerc3748562007-04-02 01:35:34 +0000292 // Do not break infinite loops.
293 BasicBlock *DestBB = BI->getSuccessor(0);
294 if (DestBB == BB)
295 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000296
Chris Lattnerc3748562007-04-02 01:35:34 +0000297 if (!CanMergeBlocks(BB, DestBB))
298 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000299
Chris Lattnerc3748562007-04-02 01:35:34 +0000300 EliminateMostlyEmptyBlock(BB);
301 MadeChange = true;
302 }
303 return MadeChange;
304}
305
306/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
307/// single uncond branch between them, and BB contains no other non-phi
308/// instructions.
309bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
310 const BasicBlock *DestBB) const {
311 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
312 // the successor. If there are more complex condition (e.g. preheaders),
313 // don't mess around with them.
314 BasicBlock::const_iterator BBI = BB->begin();
315 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greifc78d7202010-03-25 23:06:16 +0000316 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerc3748562007-04-02 01:35:34 +0000317 UI != E; ++UI) {
318 const Instruction *User = cast<Instruction>(*UI);
319 if (User->getParent() != DestBB || !isa<PHINode>(User))
320 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000321 // If User is inside DestBB block and it is a PHINode then check
322 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000323 // a complex condition (e.g. preheaders) we want to avoid here.
324 if (User->getParent() == DestBB) {
325 if (const PHINode *UPN = dyn_cast<PHINode>(User))
326 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
327 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
328 if (Insn && Insn->getParent() == BB &&
329 Insn->getParent() != UPN->getIncomingBlock(I))
330 return false;
331 }
332 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000333 }
334 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000335
Chris Lattnerc3748562007-04-02 01:35:34 +0000336 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
337 // and DestBB may have conflicting incoming values for the block. If so, we
338 // can't merge the block.
339 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
340 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000341
Chris Lattnerc3748562007-04-02 01:35:34 +0000342 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000343 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000344 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
345 // It is faster to get preds from a PHI than with pred_iterator.
346 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
347 BBPreds.insert(BBPN->getIncomingBlock(i));
348 } else {
349 BBPreds.insert(pred_begin(BB), pred_end(BB));
350 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000351
Chris Lattnerc3748562007-04-02 01:35:34 +0000352 // Walk the preds of DestBB.
353 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
354 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
355 if (BBPreds.count(Pred)) { // Common predecessor?
356 BBI = DestBB->begin();
357 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
358 const Value *V1 = PN->getIncomingValueForBlock(Pred);
359 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000360
Chris Lattnerc3748562007-04-02 01:35:34 +0000361 // If V2 is a phi node in BB, look up what the mapped value will be.
362 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
363 if (V2PN->getParent() == BB)
364 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000365
Chris Lattnerc3748562007-04-02 01:35:34 +0000366 // If there is a conflict, bail out.
367 if (V1 != V2) return false;
368 }
369 }
370 }
371
372 return true;
373}
374
375
376/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
377/// an unconditional branch in it.
378void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
379 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
380 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000381
David Greene74e2d492010-01-05 01:27:11 +0000382 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 // If the destination block has a single pred, then this is a trivial edge,
385 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000386 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000387 if (SinglePred != DestBB) {
388 // Remember if SinglePred was the entry block of the function. If so, we
389 // will need to move BB back to the entry position.
390 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000391 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000392
Chris Lattner8a172da2008-11-28 19:54:49 +0000393 if (isEntry && BB != &BB->getParent()->getEntryBlock())
394 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000395
David Greene74e2d492010-01-05 01:27:11 +0000396 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000397 return;
398 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000399 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000400
Chris Lattnerc3748562007-04-02 01:35:34 +0000401 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
402 // to handle the new incoming edges it is about to have.
403 PHINode *PN;
404 for (BasicBlock::iterator BBI = DestBB->begin();
405 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
406 // Remove the incoming value for BB, and remember it.
407 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000408
Chris Lattnerc3748562007-04-02 01:35:34 +0000409 // Two options: either the InVal is a phi node defined in BB or it is some
410 // value that dominates BB.
411 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
412 if (InValPhi && InValPhi->getParent() == BB) {
413 // Add all of the input values of the input PHI as inputs of this phi.
414 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
415 PN->addIncoming(InValPhi->getIncomingValue(i),
416 InValPhi->getIncomingBlock(i));
417 } else {
418 // Otherwise, add one instance of the dominating value for each edge that
419 // we will be adding.
420 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
421 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
422 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
423 } else {
424 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
425 PN->addIncoming(InVal, *PI);
426 }
427 }
428 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000429
Chris Lattnerc3748562007-04-02 01:35:34 +0000430 // The PHIs are now updated, change everything that refers to BB to use
431 // DestBB and remove BB.
432 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000433 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000434 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
435 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
436 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
437 DT->changeImmediateDominator(DestBB, NewIDom);
438 DT->eraseNode(BB);
439 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000440 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000441 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
David Greene74e2d492010-01-05 01:27:11 +0000443 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000444}
445
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000446/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohman4fe64de2009-06-14 23:30:43 +0000447/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
448/// sink it into user blocks to reduce the number of virtual
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000449/// registers that must be created and coalesced.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000450///
451/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000452///
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000453static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopherc1ea1492008-09-24 05:32:41 +0000454 // If this is a noop copy,
Owen Anderson53aa7a92009-08-10 22:56:29 +0000455 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
456 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000457
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000458 // This is an fp<->int conversion?
Duncan Sands13237ac2008-06-06 12:08:01 +0000459 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000460 return false;
Duncan Sands11dd4242008-06-08 20:54:56 +0000461
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000462 // If this is an extension, it will be a zero or sign extension, which
463 // isn't a noop.
Duncan Sands11dd4242008-06-08 20:54:56 +0000464 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000465
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000466 // If these values will be promoted, find out what they will be promoted
467 // to. This helps us consider truncates on PPC as noop copies when they
468 // are.
Nadav Rotem707f2d72011-05-29 08:10:47 +0000469 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
470 TargetLowering::TypePromoteInteger)
Owen Anderson117c9e82009-08-12 00:36:31 +0000471 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem707f2d72011-05-29 08:10:47 +0000472 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
473 TargetLowering::TypePromoteInteger)
Owen Anderson117c9e82009-08-12 00:36:31 +0000474 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000475
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000476 // If, after promotion, these are the same types, this is a noop copy.
477 if (SrcVT != DstVT)
478 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000479
Chris Lattnerf2836d12007-03-31 04:06:36 +0000480 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000481
Chris Lattnerf2836d12007-03-31 04:06:36 +0000482 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000483 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000484
Chris Lattnerf2836d12007-03-31 04:06:36 +0000485 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000486 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000487 UI != E; ) {
488 Use &TheUse = UI.getUse();
489 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerf2836d12007-03-31 04:06:36 +0000491 // Figure out which BB this cast is used in. For PHI's this is the
492 // appropriate predecessor block.
493 BasicBlock *UserBB = User->getParent();
494 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifeb61fcf2009-01-23 19:40:15 +0000495 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000496 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000497
Chris Lattnerf2836d12007-03-31 04:06:36 +0000498 // Preincrement use iterator so we don't invalidate it.
499 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000500
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 // If this user is in the same block as the cast, don't change the cast.
502 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000503
Chris Lattnerf2836d12007-03-31 04:06:36 +0000504 // If we have already inserted a cast into this block, use it.
505 CastInst *&InsertedCast = InsertedCasts[UserBB];
506
507 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000508 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000509 InsertedCast =
510 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 InsertPt);
512 MadeChange = true;
513 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000515 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000516 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000517 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000518 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
Chris Lattnerf2836d12007-03-31 04:06:36 +0000520 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000521 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000522 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000523 MadeChange = true;
524 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000525
Chris Lattnerf2836d12007-03-31 04:06:36 +0000526 return MadeChange;
527}
528
Eric Christopherc1ea1492008-09-24 05:32:41 +0000529/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000530/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000531/// a clear win except on targets with multiple condition code registers
532/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000533///
534/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000535static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000536 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000537
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000538 /// InsertedCmp - Only insert a cmp in each block once.
539 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000540
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000541 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000542 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000543 UI != E; ) {
544 Use &TheUse = UI.getUse();
545 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000546
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000547 // Preincrement use iterator so we don't invalidate it.
548 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000549
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000550 // Don't bother for PHI nodes.
551 if (isa<PHINode>(User))
552 continue;
553
554 // Figure out which BB this cmp is used in.
555 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000556
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000557 // If this user is in the same block as the cmp, don't change the cmp.
558 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000559
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000560 // If we have already inserted a cmp into this block, use it.
561 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
562
563 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000564 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000565 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000566 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000567 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000568 CI->getOperand(1), "", InsertPt);
569 MadeChange = true;
570 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000571
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000572 // Replace a use of the cmp with a use of the new cmp.
573 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000574 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000575 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000576
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000577 // If we removed all uses, nuke the cmp.
578 if (CI->use_empty())
579 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000580
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000581 return MadeChange;
582}
583
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000584namespace {
585class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
586protected:
587 void replaceCall(Value *With) {
588 CI->replaceAllUsesWith(With);
589 CI->eraseFromParent();
590 }
591 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greif6d673952010-07-16 09:38:02 +0000592 if (ConstantInt *SizeCI =
593 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
594 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000595 return false;
596 }
597};
598} // end anonymous namespace
599
Eric Christopher4b7948e2010-03-11 02:41:03 +0000600bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000601 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000602
Chris Lattner7a277142011-01-15 07:14:54 +0000603 // Lower inline assembly if we can.
604 // If we found an inline asm expession, and if the target knows how to
605 // lower it to normal LLVM code, do so now.
606 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
607 if (TLI->ExpandInlineAsm(CI)) {
608 // Avoid invalidating the iterator.
609 CurInstIterator = BB->begin();
610 // Avoid processing instructions out of order, which could cause
611 // reuse before a value is defined.
612 SunkAddrs.clear();
613 return true;
614 }
615 // Sink address computing for memory operands into the block.
616 if (OptimizeInlineAsmInst(CI))
617 return true;
618 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000619
Eric Christopher4b7948e2010-03-11 02:41:03 +0000620 // Lower all uses of llvm.objectsize.*
621 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
622 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000623 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000624 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000625 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
626
Chris Lattner1b93be52011-01-15 07:25:29 +0000627 // Substituting this can cause recursive simplifications, which can
628 // invalidate our iterator. Use a WeakVH to hold onto it in case this
629 // happens.
630 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000631
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000632 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruthcf1b5852012-03-24 21:11:24 +0000633 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000634
635 // If the iterator instruction was recursively deleted, start over at the
636 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000637 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000638 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000639 SunkAddrs.clear();
640 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000641 return true;
642 }
643
Pete Cooper615fd892012-03-13 20:59:56 +0000644 if (II && TLI) {
645 SmallVector<Value*, 2> PtrOps;
646 Type *AccessTy;
647 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
648 while (!PtrOps.empty())
649 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
650 return true;
651 }
652
Eric Christopher4b7948e2010-03-11 02:41:03 +0000653 // From here on out we're working with named functions.
654 if (CI->getCalledFunction() == 0) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000655
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000656 // We'll need DataLayout from here on out.
657 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000658 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000659
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000660 // Lower all default uses of _chk calls. This is very similar
661 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000662 // that have the default "don't know" as the objectsize. Anything else
663 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000664 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000665 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000666}
Chris Lattner1b93be52011-01-15 07:25:29 +0000667
Evan Cheng0663f232011-03-21 01:19:09 +0000668/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
669/// instructions to the predecessor to enable tail call optimizations. The
670/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000671/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000672/// bb0:
673/// %tmp0 = tail call i32 @f0()
674/// br label %return
675/// bb1:
676/// %tmp1 = tail call i32 @f1()
677/// br label %return
678/// bb2:
679/// %tmp2 = tail call i32 @f2()
680/// br label %return
681/// return:
682/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
683/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000684/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000685///
686/// =>
687///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000688/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000689/// bb0:
690/// %tmp0 = tail call i32 @f0()
691/// ret i32 %tmp0
692/// bb1:
693/// %tmp1 = tail call i32 @f1()
694/// ret i32 %tmp1
695/// bb2:
696/// %tmp2 = tail call i32 @f2()
697/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000698/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000699bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000700 if (!TLI)
701 return false;
702
Benjamin Kramer455fa352012-11-23 19:17:06 +0000703 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
704 if (!RI)
705 return false;
706
Evan Cheng249716e2012-07-27 21:21:26 +0000707 PHINode *PN = 0;
708 BitCastInst *BCI = 0;
Evan Cheng0663f232011-03-21 01:19:09 +0000709 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000710 if (V) {
711 BCI = dyn_cast<BitCastInst>(V);
712 if (BCI)
713 V = BCI->getOperand(0);
714
715 PN = dyn_cast<PHINode>(V);
716 if (!PN)
717 return false;
718 }
Evan Cheng0663f232011-03-21 01:19:09 +0000719
Cameron Zwarich4649f172011-03-24 04:52:10 +0000720 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000721 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000722
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000723 // It's not safe to eliminate the sign / zero extension of the return value.
724 // See llvm::isInTailCallPosition().
725 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000726 AttributeSet CallerAttrs = F->getAttributes();
727 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
728 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000729 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000730
Cameron Zwarich4649f172011-03-24 04:52:10 +0000731 // Make sure there are no instructions between the PHI and return, or that the
732 // return is the first instruction in the block.
733 if (PN) {
734 BasicBlock::iterator BI = BB->begin();
735 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000736 if (&*BI == BCI)
737 // Also skip over the bitcast.
738 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000739 if (&*BI != RI)
740 return false;
741 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000742 BasicBlock::iterator BI = BB->begin();
743 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
744 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000745 return false;
746 }
Evan Cheng0663f232011-03-21 01:19:09 +0000747
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000748 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
749 /// call.
750 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000751 if (PN) {
752 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
753 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
754 // Make sure the phi value is indeed produced by the tail call.
755 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
756 TLI->mayBeEmittedAsTailCall(CI))
757 TailCalls.push_back(CI);
758 }
759 } else {
760 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
761 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
762 if (!VisitedBBs.insert(*PI))
763 continue;
764
765 BasicBlock::InstListType &InstList = (*PI)->getInstList();
766 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
767 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000768 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
769 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000770 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000771
Cameron Zwarich4649f172011-03-24 04:52:10 +0000772 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000773 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000774 TailCalls.push_back(CI);
775 }
Evan Cheng0663f232011-03-21 01:19:09 +0000776 }
777
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000778 bool Changed = false;
779 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
780 CallInst *CI = TailCalls[i];
781 CallSite CS(CI);
782
783 // Conservatively require the attributes of the call to match those of the
784 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +0000785 AttributeSet CalleeAttrs = CS.getAttributes();
786 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000787 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +0000788 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000789 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000790 continue;
791
792 // Make sure the call instruction is followed by an unconditional branch to
793 // the return block.
794 BasicBlock *CallBB = CI->getParent();
795 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
796 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
797 continue;
798
799 // Duplicate the return into CallBB.
800 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000801 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000802 ++NumRetsDup;
803 }
804
805 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +0000806 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000807 BB->eraseFromParent();
808
809 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +0000810}
811
Chris Lattner728f9022008-11-25 07:09:13 +0000812//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +0000813// Memory Optimization
814//===----------------------------------------------------------------------===//
815
Chandler Carruthc8925912013-01-05 02:09:22 +0000816namespace {
817
818/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
819/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +0000820struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +0000821 Value *BaseReg;
822 Value *ScaledReg;
823 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
824 void print(raw_ostream &OS) const;
825 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +0000826
Chandler Carruthc8925912013-01-05 02:09:22 +0000827 bool operator==(const ExtAddrMode& O) const {
828 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
829 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
830 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
831 }
832};
833
Eli Friedmanc1f1f852013-09-10 23:09:24 +0000834#ifndef NDEBUG
835static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
836 AM.print(OS);
837 return OS;
838}
839#endif
840
Chandler Carruthc8925912013-01-05 02:09:22 +0000841void ExtAddrMode::print(raw_ostream &OS) const {
842 bool NeedPlus = false;
843 OS << "[";
844 if (BaseGV) {
845 OS << (NeedPlus ? " + " : "")
846 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000847 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000848 NeedPlus = true;
849 }
850
851 if (BaseOffs)
852 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
853
854 if (BaseReg) {
855 OS << (NeedPlus ? " + " : "")
856 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000857 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000858 NeedPlus = true;
859 }
860 if (Scale) {
861 OS << (NeedPlus ? " + " : "")
862 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000863 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +0000864 }
865
866 OS << ']';
867}
868
869#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
870void ExtAddrMode::dump() const {
871 print(dbgs());
872 dbgs() << '\n';
873}
874#endif
875
876
877/// \brief A helper class for matching addressing modes.
878///
879/// This encapsulates the logic for matching the target-legal addressing modes.
880class AddressingModeMatcher {
881 SmallVectorImpl<Instruction*> &AddrModeInsts;
882 const TargetLowering &TLI;
883
884 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
885 /// the memory instruction that we're computing this address for.
886 Type *AccessTy;
887 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +0000888
Chandler Carruthc8925912013-01-05 02:09:22 +0000889 /// AddrMode - This is the addressing mode that we're building up. This is
890 /// part of the return value of this addressing mode matching stuff.
891 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +0000892
Chandler Carruthc8925912013-01-05 02:09:22 +0000893 /// IgnoreProfitability - This is set to true when we should not do
894 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
895 /// always returns true.
896 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +0000897
Chandler Carruthc8925912013-01-05 02:09:22 +0000898 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
899 const TargetLowering &T, Type *AT,
900 Instruction *MI, ExtAddrMode &AM)
901 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
902 IgnoreProfitability = false;
903 }
904public:
Stephen Lin837bba12013-07-15 17:55:02 +0000905
Chandler Carruthc8925912013-01-05 02:09:22 +0000906 /// Match - Find the maximal addressing mode that a load/store of V can fold,
907 /// give an access type of AccessTy. This returns a list of involved
908 /// instructions in AddrModeInsts.
909 static ExtAddrMode Match(Value *V, Type *AccessTy,
910 Instruction *MemoryInst,
911 SmallVectorImpl<Instruction*> &AddrModeInsts,
912 const TargetLowering &TLI) {
913 ExtAddrMode Result;
914
Stephen Lin837bba12013-07-15 17:55:02 +0000915 bool Success =
Chandler Carruthc8925912013-01-05 02:09:22 +0000916 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
917 MemoryInst, Result).MatchAddr(V, 0);
918 (void)Success; assert(Success && "Couldn't select *anything*?");
919 return Result;
920 }
921private:
922 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
923 bool MatchAddr(Value *V, unsigned Depth);
924 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
925 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
926 ExtAddrMode &AMBefore,
927 ExtAddrMode &AMAfter);
928 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
929};
930
931/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
932/// Return true and update AddrMode if this addr mode is legal for the target,
933/// false if not.
934bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
935 unsigned Depth) {
936 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
937 // mode. Just process that directly.
938 if (Scale == 1)
939 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +0000940
Chandler Carruthc8925912013-01-05 02:09:22 +0000941 // If the scale is 0, it takes nothing to add this.
942 if (Scale == 0)
943 return true;
Stephen Lin837bba12013-07-15 17:55:02 +0000944
Chandler Carruthc8925912013-01-05 02:09:22 +0000945 // If we already have a scale of this value, we can add to it, otherwise, we
946 // need an available scale field.
947 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
948 return false;
949
950 ExtAddrMode TestAddrMode = AddrMode;
951
952 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
953 // [A+B + A*7] -> [B+A*8].
954 TestAddrMode.Scale += Scale;
955 TestAddrMode.ScaledReg = ScaleReg;
956
957 // If the new address isn't legal, bail out.
958 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
959 return false;
960
961 // It was legal, so commit it.
962 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +0000963
Chandler Carruthc8925912013-01-05 02:09:22 +0000964 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
965 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
966 // X*Scale + C*Scale to addr mode.
967 ConstantInt *CI = 0; Value *AddLHS = 0;
968 if (isa<Instruction>(ScaleReg) && // not a constant expr.
969 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
970 TestAddrMode.ScaledReg = AddLHS;
971 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +0000972
Chandler Carruthc8925912013-01-05 02:09:22 +0000973 // If this addressing mode is legal, commit it and remember that we folded
974 // this instruction.
975 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
976 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
977 AddrMode = TestAddrMode;
978 return true;
979 }
980 }
981
982 // Otherwise, not (x+c)*scale, just return what we have.
983 return true;
984}
985
986/// MightBeFoldableInst - This is a little filter, which returns true if an
987/// addressing computation involving I might be folded into a load/store
988/// accessing it. This doesn't need to be perfect, but needs to accept at least
989/// the set of instructions that MatchOperationAddr can.
990static bool MightBeFoldableInst(Instruction *I) {
991 switch (I->getOpcode()) {
992 case Instruction::BitCast:
993 // Don't touch identity bitcasts.
994 if (I->getType() == I->getOperand(0)->getType())
995 return false;
996 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
997 case Instruction::PtrToInt:
998 // PtrToInt is always a noop, as we know that the int type is pointer sized.
999 return true;
1000 case Instruction::IntToPtr:
1001 // We know the input is intptr_t, so this is foldable.
1002 return true;
1003 case Instruction::Add:
1004 return true;
1005 case Instruction::Mul:
1006 case Instruction::Shl:
1007 // Can only handle X*C and X << C.
1008 return isa<ConstantInt>(I->getOperand(1));
1009 case Instruction::GetElementPtr:
1010 return true;
1011 default:
1012 return false;
1013 }
1014}
1015
1016/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1017/// fold the operation into the addressing mode. If so, update the addressing
1018/// mode and return true, otherwise return false without modifying AddrMode.
1019bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1020 unsigned Depth) {
1021 // Avoid exponential behavior on extremely deep expression trees.
1022 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001023
Chandler Carruthc8925912013-01-05 02:09:22 +00001024 switch (Opcode) {
1025 case Instruction::PtrToInt:
1026 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1027 return MatchAddr(AddrInst->getOperand(0), Depth);
1028 case Instruction::IntToPtr:
1029 // This inttoptr is a no-op if the integer type is pointer sized.
1030 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001031 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001032 return MatchAddr(AddrInst->getOperand(0), Depth);
1033 return false;
1034 case Instruction::BitCast:
1035 // BitCast is always a noop, and we can handle it as long as it is
1036 // int->int or pointer->pointer (we don't want int<->fp or something).
1037 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1038 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1039 // Don't touch identity bitcasts. These were probably put here by LSR,
1040 // and we don't want to mess around with them. Assume it knows what it
1041 // is doing.
1042 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1043 return MatchAddr(AddrInst->getOperand(0), Depth);
1044 return false;
1045 case Instruction::Add: {
1046 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1047 ExtAddrMode BackupAddrMode = AddrMode;
1048 unsigned OldSize = AddrModeInsts.size();
1049 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1050 MatchAddr(AddrInst->getOperand(0), Depth+1))
1051 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001052
Chandler Carruthc8925912013-01-05 02:09:22 +00001053 // Restore the old addr mode info.
1054 AddrMode = BackupAddrMode;
1055 AddrModeInsts.resize(OldSize);
Stephen Lin837bba12013-07-15 17:55:02 +00001056
Chandler Carruthc8925912013-01-05 02:09:22 +00001057 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1058 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1059 MatchAddr(AddrInst->getOperand(1), Depth+1))
1060 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001061
Chandler Carruthc8925912013-01-05 02:09:22 +00001062 // Otherwise we definitely can't merge the ADD in.
1063 AddrMode = BackupAddrMode;
1064 AddrModeInsts.resize(OldSize);
1065 break;
1066 }
1067 //case Instruction::Or:
1068 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1069 //break;
1070 case Instruction::Mul:
1071 case Instruction::Shl: {
1072 // Can only handle X*C and X << C.
1073 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1074 if (!RHS) return false;
1075 int64_t Scale = RHS->getSExtValue();
1076 if (Opcode == Instruction::Shl)
1077 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001078
Chandler Carruthc8925912013-01-05 02:09:22 +00001079 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1080 }
1081 case Instruction::GetElementPtr: {
1082 // Scan the GEP. We check it if it contains constant offsets and at most
1083 // one variable offset.
1084 int VariableOperand = -1;
1085 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00001086
Chandler Carruthc8925912013-01-05 02:09:22 +00001087 int64_t ConstantOffset = 0;
1088 const DataLayout *TD = TLI.getDataLayout();
1089 gep_type_iterator GTI = gep_type_begin(AddrInst);
1090 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1091 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1092 const StructLayout *SL = TD->getStructLayout(STy);
1093 unsigned Idx =
1094 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1095 ConstantOffset += SL->getElementOffset(Idx);
1096 } else {
1097 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1098 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1099 ConstantOffset += CI->getSExtValue()*TypeSize;
1100 } else if (TypeSize) { // Scales of zero don't do anything.
1101 // We only allow one variable index at the moment.
1102 if (VariableOperand != -1)
1103 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001104
Chandler Carruthc8925912013-01-05 02:09:22 +00001105 // Remember the variable index.
1106 VariableOperand = i;
1107 VariableScale = TypeSize;
1108 }
1109 }
1110 }
Stephen Lin837bba12013-07-15 17:55:02 +00001111
Chandler Carruthc8925912013-01-05 02:09:22 +00001112 // A common case is for the GEP to only do a constant offset. In this case,
1113 // just add it to the disp field and check validity.
1114 if (VariableOperand == -1) {
1115 AddrMode.BaseOffs += ConstantOffset;
1116 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1117 // Check to see if we can fold the base pointer in too.
1118 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1119 return true;
1120 }
1121 AddrMode.BaseOffs -= ConstantOffset;
1122 return false;
1123 }
1124
1125 // Save the valid addressing mode in case we can't match.
1126 ExtAddrMode BackupAddrMode = AddrMode;
1127 unsigned OldSize = AddrModeInsts.size();
1128
1129 // See if the scale and offset amount is valid for this target.
1130 AddrMode.BaseOffs += ConstantOffset;
1131
1132 // Match the base operand of the GEP.
1133 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1134 // If it couldn't be matched, just stuff the value in a register.
1135 if (AddrMode.HasBaseReg) {
1136 AddrMode = BackupAddrMode;
1137 AddrModeInsts.resize(OldSize);
1138 return false;
1139 }
1140 AddrMode.HasBaseReg = true;
1141 AddrMode.BaseReg = AddrInst->getOperand(0);
1142 }
1143
1144 // Match the remaining variable portion of the GEP.
1145 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1146 Depth)) {
1147 // If it couldn't be matched, try stuffing the base into a register
1148 // instead of matching it, and retrying the match of the scale.
1149 AddrMode = BackupAddrMode;
1150 AddrModeInsts.resize(OldSize);
1151 if (AddrMode.HasBaseReg)
1152 return false;
1153 AddrMode.HasBaseReg = true;
1154 AddrMode.BaseReg = AddrInst->getOperand(0);
1155 AddrMode.BaseOffs += ConstantOffset;
1156 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1157 VariableScale, Depth)) {
1158 // If even that didn't work, bail.
1159 AddrMode = BackupAddrMode;
1160 AddrModeInsts.resize(OldSize);
1161 return false;
1162 }
1163 }
1164
1165 return true;
1166 }
1167 }
1168 return false;
1169}
1170
1171/// MatchAddr - If we can, try to add the value of 'Addr' into the current
1172/// addressing mode. If Addr can't be added to AddrMode this returns false and
1173/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
1174/// or intptr_t for the target.
1175///
1176bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
1177 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1178 // Fold in immediates if legal for the target.
1179 AddrMode.BaseOffs += CI->getSExtValue();
1180 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1181 return true;
1182 AddrMode.BaseOffs -= CI->getSExtValue();
1183 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
1184 // If this is a global variable, try to fold it into the addressing mode.
1185 if (AddrMode.BaseGV == 0) {
1186 AddrMode.BaseGV = GV;
1187 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1188 return true;
1189 AddrMode.BaseGV = 0;
1190 }
1191 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
1192 ExtAddrMode BackupAddrMode = AddrMode;
1193 unsigned OldSize = AddrModeInsts.size();
1194
1195 // Check to see if it is possible to fold this operation.
1196 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
1197 // Okay, it's possible to fold this. Check to see if it is actually
1198 // *profitable* to do so. We use a simple cost model to avoid increasing
1199 // register pressure too much.
1200 if (I->hasOneUse() ||
1201 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
1202 AddrModeInsts.push_back(I);
1203 return true;
1204 }
Stephen Lin837bba12013-07-15 17:55:02 +00001205
Chandler Carruthc8925912013-01-05 02:09:22 +00001206 // It isn't profitable to do this, roll back.
1207 //cerr << "NOT FOLDING: " << *I;
1208 AddrMode = BackupAddrMode;
1209 AddrModeInsts.resize(OldSize);
1210 }
1211 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1212 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
1213 return true;
1214 } else if (isa<ConstantPointerNull>(Addr)) {
1215 // Null pointer gets folded without affecting the addressing mode.
1216 return true;
1217 }
1218
1219 // Worse case, the target should support [reg] addressing modes. :)
1220 if (!AddrMode.HasBaseReg) {
1221 AddrMode.HasBaseReg = true;
1222 AddrMode.BaseReg = Addr;
1223 // Still check for legality in case the target supports [imm] but not [i+r].
1224 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1225 return true;
1226 AddrMode.HasBaseReg = false;
1227 AddrMode.BaseReg = 0;
1228 }
1229
1230 // If the base register is already taken, see if we can do [r+r].
1231 if (AddrMode.Scale == 0) {
1232 AddrMode.Scale = 1;
1233 AddrMode.ScaledReg = Addr;
1234 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1235 return true;
1236 AddrMode.Scale = 0;
1237 AddrMode.ScaledReg = 0;
1238 }
1239 // Couldn't match.
1240 return false;
1241}
1242
1243/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
1244/// inline asm call are due to memory operands. If so, return true, otherwise
1245/// return false.
1246static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
1247 const TargetLowering &TLI) {
1248 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
1249 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1250 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00001251
Chandler Carruthc8925912013-01-05 02:09:22 +00001252 // Compute the constraint code and ConstraintType to use.
1253 TLI.ComputeConstraintToUse(OpInfo, SDValue());
1254
1255 // If this asm operand is our Value*, and if it isn't an indirect memory
1256 // operand, we can't fold it!
1257 if (OpInfo.CallOperandVal == OpVal &&
1258 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1259 !OpInfo.isIndirect))
1260 return false;
1261 }
1262
1263 return true;
1264}
1265
1266/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1267/// memory use. If we find an obviously non-foldable instruction, return true.
1268/// Add the ultimately found memory instructions to MemoryUses.
1269static bool FindAllMemoryUses(Instruction *I,
1270 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
1271 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1272 const TargetLowering &TLI) {
1273 // If we already considered this instruction, we're done.
1274 if (!ConsideredInsts.insert(I))
1275 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001276
Chandler Carruthc8925912013-01-05 02:09:22 +00001277 // If this is an obviously unfoldable instruction, bail out.
1278 if (!MightBeFoldableInst(I))
1279 return true;
1280
1281 // Loop over all the uses, recursively processing them.
1282 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1283 UI != E; ++UI) {
1284 User *U = *UI;
1285
1286 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1287 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1288 continue;
1289 }
Stephen Lin837bba12013-07-15 17:55:02 +00001290
Chandler Carruthc8925912013-01-05 02:09:22 +00001291 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1292 unsigned opNo = UI.getOperandNo();
1293 if (opNo == 0) return true; // Storing addr, not into addr.
1294 MemoryUses.push_back(std::make_pair(SI, opNo));
1295 continue;
1296 }
Stephen Lin837bba12013-07-15 17:55:02 +00001297
Chandler Carruthc8925912013-01-05 02:09:22 +00001298 if (CallInst *CI = dyn_cast<CallInst>(U)) {
1299 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1300 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001301
Chandler Carruthc8925912013-01-05 02:09:22 +00001302 // If this is a memory operand, we're cool, otherwise bail out.
1303 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1304 return true;
1305 continue;
1306 }
Stephen Lin837bba12013-07-15 17:55:02 +00001307
Chandler Carruthc8925912013-01-05 02:09:22 +00001308 if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
1309 TLI))
1310 return true;
1311 }
1312
1313 return false;
1314}
1315
1316/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1317/// the use site that we're folding it into. If so, there is no cost to
1318/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
1319/// that we know are live at the instruction already.
1320bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1321 Value *KnownLive2) {
1322 // If Val is either of the known-live values, we know it is live!
1323 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1324 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001325
Chandler Carruthc8925912013-01-05 02:09:22 +00001326 // All values other than instructions and arguments (e.g. constants) are live.
1327 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001328
Chandler Carruthc8925912013-01-05 02:09:22 +00001329 // If Val is a constant sized alloca in the entry block, it is live, this is
1330 // true because it is just a reference to the stack/frame pointer, which is
1331 // live for the whole function.
1332 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1333 if (AI->isStaticAlloca())
1334 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001335
Chandler Carruthc8925912013-01-05 02:09:22 +00001336 // Check to see if this value is already used in the memory instruction's
1337 // block. If so, it's already live into the block at the very least, so we
1338 // can reasonably fold it.
1339 return Val->isUsedInBasicBlock(MemoryInst->getParent());
1340}
1341
1342/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1343/// mode of the machine to fold the specified instruction into a load or store
1344/// that ultimately uses it. However, the specified instruction has multiple
1345/// uses. Given this, it may actually increase register pressure to fold it
1346/// into the load. For example, consider this code:
1347///
1348/// X = ...
1349/// Y = X+1
1350/// use(Y) -> nonload/store
1351/// Z = Y+1
1352/// load Z
1353///
1354/// In this case, Y has multiple uses, and can be folded into the load of Z
1355/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1356/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1357/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1358/// number of computations either.
1359///
1360/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1361/// X was live across 'load Z' for other reasons, we actually *would* want to
1362/// fold the addressing mode in the Z case. This would make Y die earlier.
1363bool AddressingModeMatcher::
1364IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1365 ExtAddrMode &AMAfter) {
1366 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001367
Chandler Carruthc8925912013-01-05 02:09:22 +00001368 // AMBefore is the addressing mode before this instruction was folded into it,
1369 // and AMAfter is the addressing mode after the instruction was folded. Get
1370 // the set of registers referenced by AMAfter and subtract out those
1371 // referenced by AMBefore: this is the set of values which folding in this
1372 // address extends the lifetime of.
1373 //
1374 // Note that there are only two potential values being referenced here,
1375 // BaseReg and ScaleReg (global addresses are always available, as are any
1376 // folded immediates).
1377 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00001378
Chandler Carruthc8925912013-01-05 02:09:22 +00001379 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1380 // lifetime wasn't extended by adding this instruction.
1381 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1382 BaseReg = 0;
1383 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1384 ScaledReg = 0;
1385
1386 // If folding this instruction (and it's subexprs) didn't extend any live
1387 // ranges, we're ok with it.
1388 if (BaseReg == 0 && ScaledReg == 0)
1389 return true;
1390
1391 // If all uses of this instruction are ultimately load/store/inlineasm's,
1392 // check to see if their addressing modes will include this instruction. If
1393 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1394 // uses.
1395 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1396 SmallPtrSet<Instruction*, 16> ConsideredInsts;
1397 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1398 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00001399
Chandler Carruthc8925912013-01-05 02:09:22 +00001400 // Now that we know that all uses of this instruction are part of a chain of
1401 // computation involving only operations that could theoretically be folded
1402 // into a memory use, loop over each of these uses and see if they could
1403 // *actually* fold the instruction.
1404 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1405 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1406 Instruction *User = MemoryUses[i].first;
1407 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00001408
Chandler Carruthc8925912013-01-05 02:09:22 +00001409 // Get the access type of this use. If the use isn't a pointer, we don't
1410 // know what it accesses.
1411 Value *Address = User->getOperand(OpNo);
1412 if (!Address->getType()->isPointerTy())
1413 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00001414 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00001415
Chandler Carruthc8925912013-01-05 02:09:22 +00001416 // Do a match against the root of this address, ignoring profitability. This
1417 // will tell us if the addressing mode for the memory operation will
1418 // *actually* cover the shared instruction.
1419 ExtAddrMode Result;
1420 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1421 MemoryInst, Result);
1422 Matcher.IgnoreProfitability = true;
1423 bool Success = Matcher.MatchAddr(Address, 0);
1424 (void)Success; assert(Success && "Couldn't select *anything*?");
1425
1426 // If the match didn't cover I, then it won't be shared by it.
1427 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1428 I) == MatchedAddrModeInsts.end())
1429 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001430
Chandler Carruthc8925912013-01-05 02:09:22 +00001431 MatchedAddrModeInsts.clear();
1432 }
Stephen Lin837bba12013-07-15 17:55:02 +00001433
Chandler Carruthc8925912013-01-05 02:09:22 +00001434 return true;
1435}
1436
1437} // end anonymous namespace
1438
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001439/// IsNonLocalValue - Return true if the specified values are defined in a
1440/// different basic block than BB.
1441static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1442 if (Instruction *I = dyn_cast<Instruction>(V))
1443 return I->getParent() != BB;
1444 return false;
1445}
1446
Bob Wilson53bdae32009-12-03 21:47:07 +00001447/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001448/// addressing modes that can do significant amounts of computation. As such,
1449/// instruction selection will try to get the load or store to do as much
1450/// computation as possible for the program. The problem is that isel can only
1451/// see within a single block. As such, we sink as much legal addressing mode
1452/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00001453///
1454/// This method is used to optimize both load/store and inline asms with memory
1455/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00001456bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00001457 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00001458 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001459
1460 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00001461 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00001462 SmallVector<Value*, 8> worklist;
1463 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00001464 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00001465
Owen Anderson8ba5f392010-11-27 08:15:55 +00001466 // Use a worklist to iteratively look through PHI nodes, and ensure that
1467 // the addressing mode obtained from the non-PHI roots of the graph
1468 // are equivalent.
1469 Value *Consensus = 0;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00001470 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00001471 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00001472 SmallVector<Instruction*, 16> AddrModeInsts;
1473 ExtAddrMode AddrMode;
1474 while (!worklist.empty()) {
1475 Value *V = worklist.back();
1476 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00001477
Owen Anderson8ba5f392010-11-27 08:15:55 +00001478 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00001479 if (!Visited.insert(V)) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00001480 Consensus = 0;
1481 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00001482 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001483
Owen Anderson8ba5f392010-11-27 08:15:55 +00001484 // For a PHI node, push all of its incoming values.
1485 if (PHINode *P = dyn_cast<PHINode>(V)) {
1486 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
1487 worklist.push_back(P->getIncomingValue(i));
1488 continue;
1489 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001490
Owen Anderson8ba5f392010-11-27 08:15:55 +00001491 // For non-PHIs, determine the addressing mode being computed.
1492 SmallVector<Instruction*, 16> NewAddrModeInsts;
1493 ExtAddrMode NewAddrMode =
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00001494 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson8ba5f392010-11-27 08:15:55 +00001495 NewAddrModeInsts, *TLI);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00001496
1497 // This check is broken into two cases with very similar code to avoid using
1498 // getNumUses() as much as possible. Some values have a lot of uses, so
1499 // calling getNumUses() unconditionally caused a significant compile-time
1500 // regression.
1501 if (!Consensus) {
1502 Consensus = V;
1503 AddrMode = NewAddrMode;
1504 AddrModeInsts = NewAddrModeInsts;
1505 continue;
1506 } else if (NewAddrMode == AddrMode) {
1507 if (!IsNumUsesConsensusValid) {
1508 NumUsesConsensus = Consensus->getNumUses();
1509 IsNumUsesConsensusValid = true;
1510 }
1511
1512 // Ensure that the obtained addressing mode is equivalent to that obtained
1513 // for all other roots of the PHI traversal. Also, when choosing one
1514 // such root as representative, select the one with the most uses in order
1515 // to keep the cost modeling heuristics in AddressingModeMatcher
1516 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00001517 unsigned NumUses = V->getNumUses();
1518 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00001519 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00001520 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00001521 AddrModeInsts = NewAddrModeInsts;
1522 }
1523 continue;
1524 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001525
Owen Anderson8ba5f392010-11-27 08:15:55 +00001526 Consensus = 0;
1527 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00001528 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001529
Owen Anderson8ba5f392010-11-27 08:15:55 +00001530 // If the addressing mode couldn't be determined, or if multiple different
1531 // ones were determined, bail out now.
1532 if (!Consensus) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001533
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001534 // Check to see if any of the instructions supersumed by this addr mode are
1535 // non-local to I's BB.
1536 bool AnyNonLocal = false;
1537 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00001538 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001539 AnyNonLocal = true;
1540 break;
1541 }
1542 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001543
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001544 // If all the instructions matched are already in this BB, don't do anything.
1545 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00001546 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001547 return false;
1548 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001549
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001550 // Insert this computation right after this user. Since our caller is
1551 // scanning from the top of the BB to the bottom, reuse of the expr are
1552 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00001553 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001554
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001555 // Now that we determined the addressing expression we want to use and know
1556 // that we have to sink it into this block. Check to see if we have already
1557 // done this for some other load/store instr in this block. If so, reuse the
1558 // computation.
1559 Value *&SunkAddr = SunkAddrs[Addr];
1560 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00001561 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00001562 << *MemoryInst);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001563 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001564 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001565 } else {
David Greene74e2d492010-01-05 01:27:11 +00001566 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman29f2baf2009-07-25 01:13:51 +00001567 << *MemoryInst);
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001568 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001569 Value *Result = 0;
Dan Gohmanca194452010-01-19 22:45:06 +00001570
1571 // Start with the base register. Do this first so that subsequent address
1572 // matching finds it last, which will prevent it from trying to match it
1573 // as the scaled value in case it happens to be a mul. That would be
1574 // problematic if we've sunk a different mul for the scale, because then
1575 // we'd end up sinking both muls.
1576 if (AddrMode.BaseReg) {
1577 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00001578 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00001579 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00001580 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00001581 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00001582 Result = V;
1583 }
1584
1585 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001586 if (AddrMode.Scale) {
1587 Value *V = AddrMode.ScaledReg;
1588 if (V->getType() == IntPtrTy) {
1589 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00001590 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00001591 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001592 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1593 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00001594 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001595 } else {
Devang Patelc10e52a2011-09-06 18:49:53 +00001596 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001597 }
1598 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00001599 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
1600 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001601 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00001602 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001603 else
1604 Result = V;
1605 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001606
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001607 // Add in the BaseGV if present.
1608 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00001609 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001610 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00001611 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001612 else
1613 Result = V;
1614 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001615
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001616 // Add in the Base Offset if present.
1617 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00001618 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001619 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00001620 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001621 else
1622 Result = V;
1623 }
1624
1625 if (Result == 0)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001626 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001627 else
Devang Patelc10e52a2011-09-06 18:49:53 +00001628 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001629 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001630
Owen Andersondfb8c3b2010-11-19 22:15:03 +00001631 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001632
Chris Lattneraf1bcce2011-04-09 07:05:44 +00001633 // If we have no uses, recursively delete the value and all dead instructions
1634 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00001635 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00001636 // This can cause recursive deletion, which can invalidate our iterator.
1637 // Use a WeakVH to hold onto it in case this happens.
1638 WeakVH IterHandle(CurInstIterator);
1639 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001640
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001641 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00001642
1643 if (IterHandle != CurInstIterator) {
1644 // If the iterator instruction was recursively deleted, start over at the
1645 // start of the block.
1646 CurInstIterator = BB->begin();
1647 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00001648 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00001649 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00001650 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00001651 return true;
1652}
1653
Evan Cheng1da25002008-02-26 02:42:37 +00001654/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00001655/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00001656/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00001657bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00001658 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00001659
Nadav Rotem465834c2012-07-24 10:51:42 +00001660 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00001661 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00001662 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00001663 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1664 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00001665
Evan Cheng1da25002008-02-26 02:42:37 +00001666 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00001667 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00001668
Eli Friedman666bbe32008-02-26 18:37:49 +00001669 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1670 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00001671 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00001672 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00001673 } else if (OpInfo.Type == InlineAsm::isInput)
1674 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00001675 }
1676
1677 return MadeChange;
1678}
1679
Dan Gohman99429a02009-10-16 20:59:35 +00001680/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1681/// basic block as the load, unless conditions are unfavorable. This allows
1682/// SelectionDAG to fold the extend into the load.
1683///
1684bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1685 // Look for a load being extended.
1686 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1687 if (!LI) return false;
1688
1689 // If they're already in the same block, there's nothing to do.
1690 if (LI->getParent() == I->getParent())
1691 return false;
1692
1693 // If the load has other users and the truncate is not free, this probably
1694 // isn't worthwhile.
1695 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00001696 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1697 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00001698 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00001699 return false;
1700
1701 // Check whether the target supports casts folded into loads.
1702 unsigned LType;
1703 if (isa<ZExtInst>(I))
1704 LType = ISD::ZEXTLOAD;
1705 else {
1706 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1707 LType = ISD::SEXTLOAD;
1708 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001709 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00001710 return false;
1711
1712 // Move the extend into the same block as the load, so that SelectionDAG
1713 // can fold it.
1714 I->removeFromParent();
1715 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00001716 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00001717 return true;
1718}
1719
Evan Chengd3d80172007-12-05 23:58:20 +00001720bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1721 BasicBlock *DefBB = I->getParent();
1722
Bob Wilsonff714f92010-09-21 21:44:14 +00001723 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00001724 // other uses of the source with result of extension.
1725 Value *Src = I->getOperand(0);
1726 if (Src->hasOneUse())
1727 return false;
1728
Evan Cheng2011df42007-12-13 07:50:36 +00001729 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00001730 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00001731 return false;
1732
Evan Cheng7bc89422007-12-12 00:51:06 +00001733 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00001734 // this block.
1735 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00001736 return false;
1737
Evan Chengd3d80172007-12-05 23:58:20 +00001738 bool DefIsLiveOut = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001739 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengd3d80172007-12-05 23:58:20 +00001740 UI != E; ++UI) {
1741 Instruction *User = cast<Instruction>(*UI);
1742
1743 // Figure out which BB this ext is used in.
1744 BasicBlock *UserBB = User->getParent();
1745 if (UserBB == DefBB) continue;
1746 DefIsLiveOut = true;
1747 break;
1748 }
1749 if (!DefIsLiveOut)
1750 return false;
1751
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00001752 // Make sure none of the uses are PHI nodes.
Eric Christopherc1ea1492008-09-24 05:32:41 +00001753 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng63d33cf2007-12-12 02:53:41 +00001754 UI != E; ++UI) {
1755 Instruction *User = cast<Instruction>(*UI);
Evan Cheng37c36ed2007-12-13 03:32:53 +00001756 BasicBlock *UserBB = User->getParent();
1757 if (UserBB == DefBB) continue;
1758 // Be conservative. We don't want this xform to end up introducing
1759 // reloads just before load / store instructions.
1760 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng63d33cf2007-12-12 02:53:41 +00001761 return false;
1762 }
1763
Evan Chengd3d80172007-12-05 23:58:20 +00001764 // InsertedTruncs - Only insert one trunc in each block once.
1765 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1766
1767 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001768 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengd3d80172007-12-05 23:58:20 +00001769 UI != E; ++UI) {
1770 Use &TheUse = UI.getUse();
1771 Instruction *User = cast<Instruction>(*UI);
1772
1773 // Figure out which BB this ext is used in.
1774 BasicBlock *UserBB = User->getParent();
1775 if (UserBB == DefBB) continue;
1776
1777 // Both src and def are live in this block. Rewrite the use.
1778 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1779
1780 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001781 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00001782 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1783 }
1784
1785 // Replace a use of the {s|z}ext source with a use of the result.
1786 TheUse = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001787 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00001788 MadeChange = true;
1789 }
1790
1791 return MadeChange;
1792}
1793
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00001794/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1795/// turned into an explicit branch.
1796static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1797 // FIXME: This should use the same heuristics as IfConversion to determine
1798 // whether a select is better represented as a branch. This requires that
1799 // branch probability metadata is preserved for the select, which is not the
1800 // case currently.
1801
1802 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1803
1804 // If the branch is predicted right, an out of order CPU can avoid blocking on
1805 // the compare. Emit cmovs on compares with a memory operand as branches to
1806 // avoid stalls on the load from memory. If the compare has more than one use
1807 // there's probably another cmov or setcc around so it's not worth emitting a
1808 // branch.
1809 if (!Cmp)
1810 return false;
1811
1812 Value *CmpOp0 = Cmp->getOperand(0);
1813 Value *CmpOp1 = Cmp->getOperand(1);
1814
1815 // We check that the memory operand has one use to avoid uses of the loaded
1816 // value directly after the compare, making branches unprofitable.
1817 return Cmp->hasOneUse() &&
1818 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1819 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1820}
1821
1822
Nadav Rotem9d832022012-09-02 12:10:19 +00001823/// If we have a SelectInst that will likely profit from branch prediction,
1824/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00001825bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00001826 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1827
1828 // Can we convert the 'select' to CF ?
1829 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00001830 return false;
1831
Nadav Rotem9d832022012-09-02 12:10:19 +00001832 TargetLowering::SelectSupportKind SelectKind;
1833 if (VectorCond)
1834 SelectKind = TargetLowering::VectorMaskSelect;
1835 else if (SI->getType()->isVectorTy())
1836 SelectKind = TargetLowering::ScalarCondVectorVal;
1837 else
1838 SelectKind = TargetLowering::ScalarValSelect;
1839
1840 // Do we have efficient codegen support for this kind of 'selects' ?
1841 if (TLI->isSelectSupported(SelectKind)) {
1842 // We have efficient codegen support for the select instruction.
1843 // Check if it is profitable to keep this 'select'.
1844 if (!TLI->isPredictableSelectExpensive() ||
1845 !isFormingBranchFromSelectProfitable(SI))
1846 return false;
1847 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00001848
1849 ModifiedDT = true;
1850
1851 // First, we split the block containing the select into 2 blocks.
1852 BasicBlock *StartBlock = SI->getParent();
1853 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1854 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1855
1856 // Create a new block serving as the landing pad for the branch.
1857 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1858 NextBlock->getParent(), NextBlock);
1859
1860 // Move the unconditional branch from the block with the select in it into our
1861 // landing pad block.
1862 StartBlock->getTerminator()->eraseFromParent();
1863 BranchInst::Create(NextBlock, SmallBlock);
1864
1865 // Insert the real conditional branch based on the original condition.
1866 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1867
1868 // The select itself is replaced with a PHI Node.
1869 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1870 PN->takeName(SI);
1871 PN->addIncoming(SI->getTrueValue(), StartBlock);
1872 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1873 SI->replaceAllUsesWith(PN);
1874 SI->eraseFromParent();
1875
1876 // Instruct OptimizeBlock to skip to the next block.
1877 CurInstIterator = StartBlock->end();
1878 ++NumSelectsExpanded;
1879 return true;
1880}
1881
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001882bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001883 if (PHINode *P = dyn_cast<PHINode>(I)) {
1884 // It is possible for very late stage optimizations (such as SimplifyCFG)
1885 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1886 // trivial PHI, go ahead and zap it here.
Benjamin Kramer30d249a2013-09-24 16:37:40 +00001887 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
1888 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001889 P->replaceAllUsesWith(V);
1890 P->eraseFromParent();
1891 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00001892 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001893 }
Chris Lattneree588de2011-01-15 07:29:01 +00001894 return false;
1895 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001896
Chris Lattneree588de2011-01-15 07:29:01 +00001897 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001898 // If the source of the cast is a constant, then this should have
1899 // already been constant folded. The only reason NOT to constant fold
1900 // it is if something (e.g. LSR) was careful to place the constant
1901 // evaluation in a block other than then one that uses it (e.g. to hoist
1902 // the address of globals out of a loop). If this is the case, we don't
1903 // want to forward-subst the cast.
1904 if (isa<Constant>(CI->getOperand(0)))
1905 return false;
1906
Chris Lattneree588de2011-01-15 07:29:01 +00001907 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1908 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001909
Chris Lattneree588de2011-01-15 07:29:01 +00001910 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1911 bool MadeChange = MoveExtToFormExtLoad(I);
1912 return MadeChange | OptimizeExtUses(I);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001913 }
Chris Lattneree588de2011-01-15 07:29:01 +00001914 return false;
1915 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001916
Chris Lattneree588de2011-01-15 07:29:01 +00001917 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00001918 if (!TLI || !TLI->hasMultipleConditionRegisters())
1919 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001920
Chris Lattneree588de2011-01-15 07:29:01 +00001921 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001922 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00001923 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1924 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00001925 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001926
Chris Lattneree588de2011-01-15 07:29:01 +00001927 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001928 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00001929 return OptimizeMemoryInst(I, SI->getOperand(1),
1930 SI->getOperand(0)->getType());
1931 return false;
1932 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001933
Chris Lattneree588de2011-01-15 07:29:01 +00001934 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00001935 if (GEPI->hasAllZeroIndices()) {
1936 /// The GEP operand must be a pointer, so must its result -> BitCast
1937 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1938 GEPI->getName(), GEPI);
1939 GEPI->replaceAllUsesWith(NC);
1940 GEPI->eraseFromParent();
1941 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00001942 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00001943 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00001944 }
Chris Lattneree588de2011-01-15 07:29:01 +00001945 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001946 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001947
Chris Lattneree588de2011-01-15 07:29:01 +00001948 if (CallInst *CI = dyn_cast<CallInst>(I))
1949 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001950
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00001951 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1952 return OptimizeSelectInst(SI);
1953
Chris Lattneree588de2011-01-15 07:29:01 +00001954 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00001955}
1956
Chris Lattnerf2836d12007-03-31 04:06:36 +00001957// In this pass we look for GEP and cast instructions that are used
1958// across basic blocks and rewrite them to improve basic-block-at-a-time
1959// selection.
1960bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00001961 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00001962 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001963
Chris Lattner7a277142011-01-15 07:14:54 +00001964 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00001965 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00001966 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001967
Benjamin Kramer455fa352012-11-23 19:17:06 +00001968 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1969
Chris Lattnerf2836d12007-03-31 04:06:36 +00001970 return MadeChange;
1971}
Devang Patel53771ba2011-08-18 00:50:51 +00001972
1973// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00001974// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00001975// find a node corresponding to the value.
1976bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1977 bool MadeChange = false;
1978 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1979 Instruction *PrevNonDbgInst = NULL;
1980 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1981 Instruction *Insn = BI; ++BI;
1982 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1983 if (!DVI) {
1984 PrevNonDbgInst = Insn;
1985 continue;
1986 }
1987
1988 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1989 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1990 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1991 DVI->removeFromParent();
1992 if (isa<PHINode>(VI))
1993 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1994 else
1995 DVI->insertAfter(VI);
1996 MadeChange = true;
1997 ++NumDbgValueMoved;
1998 }
1999 }
2000 }
2001 return MadeChange;
2002}