blob: c490705f3ba6206116d64e2659cd97519c553c8a [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/DominatorInternals.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/ProfileInfo.h"
25#include "llvm/Assembly/Writer.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Constants.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000028#include "llvm/DerivedTypes.h"
29#include "llvm/Function.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000030#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000031#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000032#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000033#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000034#include "llvm/Pass.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000040#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000042#include "llvm/Target/TargetLibraryInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Transforms/Utils/AddrModeMatcher.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000050using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000051
Cameron Zwarich31ff1332011-01-05 17:27:27 +000052STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000053STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000055STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 "sunken Cmps");
57STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 "of sunken Casts");
59STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000061STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000064STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000065STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000066
Cameron Zwarich899eaa32011-03-11 21:52:04 +000067static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000071static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000074
Eric Christopher692bf6b2008-09-24 05:32:41 +000075namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000076 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000080 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000081 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000082 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000083
Chris Lattner75796092011-01-15 07:14:54 +000084 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
86 /// update it.
87 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000088
Evan Cheng485fafc2011-03-21 01:19:09 +000089 /// Keeps track of non-local addresses that have been sunk into a block.
90 /// This allows us to avoid inserting duplicate code for blocks with
91 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000092 DenseMap<Value*, Value*> SunkAddrs;
93
Devang Patel52e37df2011-03-24 15:35:25 +000094 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000095 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000096 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000097
Benjamin Kramer59957502012-05-05 12:49:22 +000098 /// OptSize - True if optimizing for size.
99 bool OptSize;
100
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000101 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000102 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
106 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000107 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000108
Andreas Neustifterad809812009-09-16 09:26:52 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000110 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000112 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 }
114
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000115 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000116 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000117 bool EliminateMostlyEmptyBlocks(Function &F);
118 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
119 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000120 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000121 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000122 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000123 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000124 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000125 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000126 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000127 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000128 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patelf56ea612011-08-18 00:50:51 +0000129 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000130 };
131}
Devang Patel794fd752007-05-01 21:15:47 +0000132
Devang Patel19974732007-05-03 01:11:54 +0000133char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000134INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
135 "Optimize for code generation", false, false)
136INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
137INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000138 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000139
140FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
141 return new CodeGenPrepare(TLI);
142}
143
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000144bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000145 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000146
Devang Patel52e37df2011-03-24 15:35:25 +0000147 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000148 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000149 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000150 PFI = getAnalysisIfAvailable<ProfileInfo>();
Bill Wendling034b94b2012-12-19 07:18:57 +0000151 OptSize = F.getFnAttributes().hasAttribute(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000152
Preston Gurd2e2efd92012-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.
155 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000156 const DenseMap<unsigned int, unsigned int> &BypassWidths =
157 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000158 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000159 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000160 }
161
162 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000163 // unconditional branch.
164 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000165
Devang Patelf56ea612011-08-18 00:50:51 +0000166 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000167 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000168 // find a node corresponding to the value.
169 EverMadeChange |= PlaceDbgValues(F);
170
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000171 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000172 while (MadeChange) {
173 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000174 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000175 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000176 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000177 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000178 EverMadeChange |= MadeChange;
179 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000180
181 SunkAddrs.clear();
182
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000183 if (!DisableBranchOpts) {
184 MadeChange = false;
Bill Wendlinge3e394d2012-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 Bommel5649ba72011-05-22 16:24:18 +0000188 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-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 Wendlingbf2ad732012-11-28 23:23:48 +0000197 // Delete the dead blocks and any of their dead successors.
Bill Wendling1c211642012-12-06 00:30:20 +0000198 MadeChange |= !WorkList.empty();
Bill Wendlingbf2ad732012-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);
205
206 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 Zwarich899eaa32011-03-11 21:52:04 +0000211
Nadav Rotem3e883732012-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 Cheng485fafc2011-03-21 01:19:09 +0000217 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000218 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000219 EverMadeChange |= MadeChange;
220 }
221
Devang Patel52e37df2011-03-24 15:35:25 +0000222 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000223 DT->DT->recalculate(F);
224
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000225 return EverMadeChange;
226}
227
Nadav Rotem3e883732012-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 Cheng46597072012-09-28 23:58:57 +0000240 // Don't merge if BB's address is taken.
241 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000242
243 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
244 if (Term && !Term->isConditional()) {
245 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000246 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-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 Rotem3e883732012-08-14 05:19:07 +0000257 }
258 }
259 return Changed;
260}
261
Dale Johannesen2d697242009-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 Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000277
Dale Johannesen2d697242009-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 Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 BasicBlock::iterator BBI = BI;
281 if (BBI != BB->begin()) {
282 --BBI;
Dale Johannesen2d697242009-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 Lattnerd9c3a0d2007-04-02 01:35:34 +0000290 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000291
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000292 // Do not break infinite loops.
293 BasicBlock *DestBB = BI->getSuccessor(0);
294 if (DestBB == BB)
295 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000296
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000297 if (!CanMergeBlocks(BB, DestBB))
298 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
Chris Lattnerd9c3a0d2007-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 Greif60ad7812010-03-25 23:06:16 +0000316 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-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 Patel75abc1e2007-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 Lattnerd9c3a0d2007-04-02 01:35:34 +0000333 }
334 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000335
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000341
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000342 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000343 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000360
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000365
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000381
David Greene68d67fd2010-01-05 01:27:11 +0000382 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Chris Lattnerd9c3a0d2007-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 Lattner9918fb52008-11-27 19:29:14 +0000386 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-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 Neustifterad809812009-09-16 09:26:52 +0000391 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000392
Chris Lattnerf5102a02008-11-28 19:54:49 +0000393 if (isEntry && BB != &BB->getParent()->getEntryBlock())
394 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000395
David Greene68d67fd2010-01-05 01:27:11 +0000396 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000397 return;
398 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000399 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000400
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000408
Chris Lattnerd9c3a0d2007-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 Christopher692bf6b2008-09-24 05:32:41 +0000429
Chris Lattnerd9c3a0d2007-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 Patel52e37df2011-03-24 15:35:25 +0000433 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-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 }
Evan Cheng04149f72009-12-17 09:39:49 +0000440 if (PFI) {
441 PFI->replaceAllUses(BB, DestBB);
442 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000443 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000444 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000445 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
David Greene68d67fd2010-01-05 01:27:11 +0000447 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000448}
449
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000451/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
452/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000453/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000454///
455/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000456///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000457static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000459 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
460 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461
Chris Lattnerdd77df32007-04-13 20:30:56 +0000462 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000463 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000464 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000465
Chris Lattnerdd77df32007-04-13 20:30:56 +0000466 // If this is an extension, it will be a zero or sign extension, which
467 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000468 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdd77df32007-04-13 20:30:56 +0000470 // If these values will be promoted, find out what they will be promoted
471 // to. This helps us consider truncates on PPC as noop copies when they
472 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000473 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
474 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000475 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000476 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
477 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000478 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000479
Chris Lattnerdd77df32007-04-13 20:30:56 +0000480 // If, after promotion, these are the same types, this is a noop copy.
481 if (SrcVT != DstVT)
482 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000483
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000484 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000485
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000487 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 UI != E; ) {
492 Use &TheUse = UI.getUse();
493 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000495 // Figure out which BB this cast is used in. For PHI's this is the
496 // appropriate predecessor block.
497 BasicBlock *UserBB = User->getParent();
498 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000499 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000500 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000502 // Preincrement use iterator so we don't invalidate it.
503 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 // If this user is in the same block as the cast, don't change the cast.
506 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 // If we have already inserted a cast into this block, use it.
509 CastInst *&InsertedCast = InsertedCasts[UserBB];
510
511 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000512 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000513 InsertedCast =
514 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000515 InsertPt);
516 MadeChange = true;
517 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000518
Dale Johannesence0b2372007-06-12 16:50:17 +0000519 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000520 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000521 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000522 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000523
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000524 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000525 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000526 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000527 MadeChange = true;
528 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000529
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000530 return MadeChange;
531}
532
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000534/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000535/// a clear win except on targets with multiple condition code registers
536/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000537///
538/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000539static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 /// InsertedCmp - Only insert a cmp in each block once.
543 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 UI != E; ) {
548 Use &TheUse = UI.getUse();
549 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000550
Dale Johannesence0b2372007-06-12 16:50:17 +0000551 // Preincrement use iterator so we don't invalidate it.
552 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000553
Dale Johannesence0b2372007-06-12 16:50:17 +0000554 // Don't bother for PHI nodes.
555 if (isa<PHINode>(User))
556 continue;
557
558 // Figure out which BB this cmp is used in.
559 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000560
Dale Johannesence0b2372007-06-12 16:50:17 +0000561 // If this user is in the same block as the cmp, don't change the cmp.
562 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000563
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 // If we have already inserted a cmp into this block, use it.
565 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
566
567 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000568 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000569 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000570 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000571 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000572 CI->getOperand(1), "", InsertPt);
573 MadeChange = true;
574 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000575
Dale Johannesence0b2372007-06-12 16:50:17 +0000576 // Replace a use of the cmp with a use of the new cmp.
577 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000578 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000579 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000580
Dale Johannesence0b2372007-06-12 16:50:17 +0000581 // If we removed all uses, nuke the cmp.
582 if (CI->use_empty())
583 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000584
Dale Johannesence0b2372007-06-12 16:50:17 +0000585 return MadeChange;
586}
587
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000588namespace {
589class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
590protected:
591 void replaceCall(Value *With) {
592 CI->replaceAllUsesWith(With);
593 CI->eraseFromParent();
594 }
595 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000596 if (ConstantInt *SizeCI =
597 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
598 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000599 return false;
600 }
601};
602} // end anonymous namespace
603
Eric Christopher040056f2010-03-11 02:41:03 +0000604bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000605 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000606
Chris Lattner75796092011-01-15 07:14:54 +0000607 // Lower inline assembly if we can.
608 // If we found an inline asm expession, and if the target knows how to
609 // lower it to normal LLVM code, do so now.
610 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
611 if (TLI->ExpandInlineAsm(CI)) {
612 // Avoid invalidating the iterator.
613 CurInstIterator = BB->begin();
614 // Avoid processing instructions out of order, which could cause
615 // reuse before a value is defined.
616 SunkAddrs.clear();
617 return true;
618 }
619 // Sink address computing for memory operands into the block.
620 if (OptimizeInlineAsmInst(CI))
621 return true;
622 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000623
Eric Christopher040056f2010-03-11 02:41:03 +0000624 // Lower all uses of llvm.objectsize.*
625 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
626 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000627 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000628 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000629 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
630
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000631 // Substituting this can cause recursive simplifications, which can
632 // invalidate our iterator. Use a WeakVH to hold onto it in case this
633 // happens.
634 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000635
Micah Villmow3574eca2012-10-08 16:38:25 +0000636 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000637 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000638
639 // If the iterator instruction was recursively deleted, start over at the
640 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000641 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000642 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000643 SunkAddrs.clear();
644 }
Eric Christopher040056f2010-03-11 02:41:03 +0000645 return true;
646 }
647
Pete Cooperf210b682012-03-13 20:59:56 +0000648 if (II && TLI) {
649 SmallVector<Value*, 2> PtrOps;
650 Type *AccessTy;
651 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
652 while (!PtrOps.empty())
653 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
654 return true;
655 }
656
Eric Christopher040056f2010-03-11 02:41:03 +0000657 // From here on out we're working with named functions.
658 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000659
Micah Villmow3574eca2012-10-08 16:38:25 +0000660 // We'll need DataLayout from here on out.
661 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000662 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000663
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000664 // Lower all default uses of _chk calls. This is very similar
665 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000666 // that have the default "don't know" as the objectsize. Anything else
667 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000668 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000669 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000670}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000671
Evan Cheng485fafc2011-03-21 01:19:09 +0000672/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
673/// instructions to the predecessor to enable tail call optimizations. The
674/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000675/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000676/// bb0:
677/// %tmp0 = tail call i32 @f0()
678/// br label %return
679/// bb1:
680/// %tmp1 = tail call i32 @f1()
681/// br label %return
682/// bb2:
683/// %tmp2 = tail call i32 @f2()
684/// br label %return
685/// return:
686/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
687/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000688/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000689///
690/// =>
691///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000692/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000693/// bb0:
694/// %tmp0 = tail call i32 @f0()
695/// ret i32 %tmp0
696/// bb1:
697/// %tmp1 = tail call i32 @f1()
698/// ret i32 %tmp1
699/// bb2:
700/// %tmp2 = tail call i32 @f2()
701/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000702/// @endcode
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000703bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000704 if (!TLI)
705 return false;
706
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000707 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
708 if (!RI)
709 return false;
710
Evan Cheng9c777a42012-07-27 21:21:26 +0000711 PHINode *PN = 0;
712 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000713 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000714 if (V) {
715 BCI = dyn_cast<BitCastInst>(V);
716 if (BCI)
717 V = BCI->getOperand(0);
718
719 PN = dyn_cast<PHINode>(V);
720 if (!PN)
721 return false;
722 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000723
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000724 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000725 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000726
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000727 // It's not safe to eliminate the sign / zero extension of the return value.
728 // See llvm::isInTailCallPosition().
729 const Function *F = BB->getParent();
Bill Wendling034b94b2012-12-19 07:18:57 +0000730 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
731 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
732 CallerRetAttr.hasAttribute(Attribute::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000733 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000734
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000735 // Make sure there are no instructions between the PHI and return, or that the
736 // return is the first instruction in the block.
737 if (PN) {
738 BasicBlock::iterator BI = BB->begin();
739 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000740 if (&*BI == BCI)
741 // Also skip over the bitcast.
742 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000743 if (&*BI != RI)
744 return false;
745 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000746 BasicBlock::iterator BI = BB->begin();
747 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
748 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000749 return false;
750 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000751
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000752 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
753 /// call.
754 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000755 if (PN) {
756 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
757 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
758 // Make sure the phi value is indeed produced by the tail call.
759 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
760 TLI->mayBeEmittedAsTailCall(CI))
761 TailCalls.push_back(CI);
762 }
763 } else {
764 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
765 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
766 if (!VisitedBBs.insert(*PI))
767 continue;
768
769 BasicBlock::InstListType &InstList = (*PI)->getInstList();
770 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
771 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000772 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
773 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000774 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000775
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000776 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000777 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000778 TailCalls.push_back(CI);
779 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000780 }
781
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000782 bool Changed = false;
783 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
784 CallInst *CI = TailCalls[i];
785 CallSite CS(CI);
786
787 // Conservatively require the attributes of the call to match those of the
788 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling034b94b2012-12-19 07:18:57 +0000789 Attribute CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000790 if (AttrBuilder(CalleeRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000791 removeAttribute(Attribute::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000792 AttrBuilder(CallerRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000793 removeAttribute(Attribute::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000794 continue;
795
796 // Make sure the call instruction is followed by an unconditional branch to
797 // the return block.
798 BasicBlock *CallBB = CI->getParent();
799 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
800 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
801 continue;
802
803 // Duplicate the return into CallBB.
804 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000805 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000806 ++NumRetsDup;
807 }
808
809 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000810 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000811 BB->eraseFromParent();
812
813 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000814}
815
Chris Lattner88a5c832008-11-25 07:09:13 +0000816//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000817// Memory Optimization
818//===----------------------------------------------------------------------===//
819
Chris Lattnerdd77df32007-04-13 20:30:56 +0000820/// IsNonLocalValue - Return true if the specified values are defined in a
821/// different basic block than BB.
822static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
823 if (Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() != BB;
825 return false;
826}
827
Bob Wilson4a8ee232009-12-03 21:47:07 +0000828/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000829/// addressing modes that can do significant amounts of computation. As such,
830/// instruction selection will try to get the load or store to do as much
831/// computation as possible for the program. The problem is that isel can only
832/// see within a single block. As such, we sink as much legal addressing mode
833/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000834///
835/// This method is used to optimize both load/store and inline asms with memory
836/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000837bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000838 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000839 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000840
841 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000842 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000843 SmallVector<Value*, 8> worklist;
844 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000845 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000846
Owen Anderson35bf4d62010-11-27 08:15:55 +0000847 // Use a worklist to iteratively look through PHI nodes, and ensure that
848 // the addressing mode obtained from the non-PHI roots of the graph
849 // are equivalent.
850 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000851 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000852 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000853 SmallVector<Instruction*, 16> AddrModeInsts;
854 ExtAddrMode AddrMode;
855 while (!worklist.empty()) {
856 Value *V = worklist.back();
857 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000858
Owen Anderson35bf4d62010-11-27 08:15:55 +0000859 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000860 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000861 Consensus = 0;
862 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000863 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000864
Owen Anderson35bf4d62010-11-27 08:15:55 +0000865 // For a PHI node, push all of its incoming values.
866 if (PHINode *P = dyn_cast<PHINode>(V)) {
867 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
868 worklist.push_back(P->getIncomingValue(i));
869 continue;
870 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000871
Owen Anderson35bf4d62010-11-27 08:15:55 +0000872 // For non-PHIs, determine the addressing mode being computed.
873 SmallVector<Instruction*, 16> NewAddrModeInsts;
874 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000875 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000876 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000877
878 // This check is broken into two cases with very similar code to avoid using
879 // getNumUses() as much as possible. Some values have a lot of uses, so
880 // calling getNumUses() unconditionally caused a significant compile-time
881 // regression.
882 if (!Consensus) {
883 Consensus = V;
884 AddrMode = NewAddrMode;
885 AddrModeInsts = NewAddrModeInsts;
886 continue;
887 } else if (NewAddrMode == AddrMode) {
888 if (!IsNumUsesConsensusValid) {
889 NumUsesConsensus = Consensus->getNumUses();
890 IsNumUsesConsensusValid = true;
891 }
892
893 // Ensure that the obtained addressing mode is equivalent to that obtained
894 // for all other roots of the PHI traversal. Also, when choosing one
895 // such root as representative, select the one with the most uses in order
896 // to keep the cost modeling heuristics in AddressingModeMatcher
897 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000898 unsigned NumUses = V->getNumUses();
899 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000900 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000901 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000902 AddrModeInsts = NewAddrModeInsts;
903 }
904 continue;
905 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000906
Owen Anderson35bf4d62010-11-27 08:15:55 +0000907 Consensus = 0;
908 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000909 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000910
Owen Anderson35bf4d62010-11-27 08:15:55 +0000911 // If the addressing mode couldn't be determined, or if multiple different
912 // ones were determined, bail out now.
913 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000914
Chris Lattnerdd77df32007-04-13 20:30:56 +0000915 // Check to see if any of the instructions supersumed by this addr mode are
916 // non-local to I's BB.
917 bool AnyNonLocal = false;
918 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000919 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000920 AnyNonLocal = true;
921 break;
922 }
923 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000924
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 // If all the instructions matched are already in this BB, don't do anything.
926 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000927 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000928 return false;
929 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000930
Chris Lattnerdd77df32007-04-13 20:30:56 +0000931 // Insert this computation right after this user. Since our caller is
932 // scanning from the top of the BB to the bottom, reuse of the expr are
933 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000934 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000935
Chris Lattnerdd77df32007-04-13 20:30:56 +0000936 // Now that we determined the addressing expression we want to use and know
937 // that we have to sink it into this block. Check to see if we have already
938 // done this for some other load/store instr in this block. If so, reuse the
939 // computation.
940 Value *&SunkAddr = SunkAddrs[Addr];
941 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000942 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000943 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000944 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000945 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000946 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000947 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000948 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000949 Type *IntPtrTy =
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000950 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000951
Chris Lattnerdd77df32007-04-13 20:30:56 +0000952 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000953
954 // Start with the base register. Do this first so that subsequent address
955 // matching finds it last, which will prevent it from trying to match it
956 // as the scaled value in case it happens to be a mul. That would be
957 // problematic if we've sunk a different mul for the scale, because then
958 // we'd end up sinking both muls.
959 if (AddrMode.BaseReg) {
960 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000961 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000962 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000963 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000964 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000965 Result = V;
966 }
967
968 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000969 if (AddrMode.Scale) {
970 Value *V = AddrMode.ScaledReg;
971 if (V->getType() == IntPtrTy) {
972 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000973 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000974 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000975 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
976 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000977 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000978 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000979 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000980 }
981 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000982 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
983 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000984 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000985 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000986 else
987 Result = V;
988 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000989
Chris Lattnerdd77df32007-04-13 20:30:56 +0000990 // Add in the BaseGV if present.
991 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000992 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000993 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000994 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000995 else
996 Result = V;
997 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000998
Chris Lattnerdd77df32007-04-13 20:30:56 +0000999 // Add in the Base Offset if present.
1000 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001001 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001002 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00001003 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001004 else
1005 Result = V;
1006 }
1007
1008 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +00001009 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +00001010 else
Devang Patel2048c372011-09-06 18:49:53 +00001011 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001012 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001013
Owen Andersond2f41742010-11-19 22:15:03 +00001014 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001015
Chris Lattner0403b472011-04-09 07:05:44 +00001016 // If we have no uses, recursively delete the value and all dead instructions
1017 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001018 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001019 // This can cause recursive deletion, which can invalidate our iterator.
1020 // Use a WeakVH to hold onto it in case this happens.
1021 WeakVH IterHandle(CurInstIterator);
1022 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001023
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001024 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001025
1026 if (IterHandle != CurInstIterator) {
1027 // If the iterator instruction was recursively deleted, start over at the
1028 // start of the block.
1029 CurInstIterator = BB->begin();
1030 SunkAddrs.clear();
1031 } else {
1032 // This address is now available for reassignment, so erase the table
1033 // entry; we don't want to match some completely different instruction.
1034 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001035 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001036 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001037 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001038 return true;
1039}
1040
Evan Cheng9bf12b52008-02-26 02:42:37 +00001041/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001042/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001043/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001044bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001045 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001046
Nadav Rotema94d6e82012-07-24 10:51:42 +00001047 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001048 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001049 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001050 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1051 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001052
Evan Cheng9bf12b52008-02-26 02:42:37 +00001053 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001054 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001055
Eli Friedman9ec80952008-02-26 18:37:49 +00001056 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1057 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001058 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001059 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001060 } else if (OpInfo.Type == InlineAsm::isInput)
1061 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001062 }
1063
1064 return MadeChange;
1065}
1066
Dan Gohmanb00f2362009-10-16 20:59:35 +00001067/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1068/// basic block as the load, unless conditions are unfavorable. This allows
1069/// SelectionDAG to fold the extend into the load.
1070///
1071bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1072 // Look for a load being extended.
1073 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1074 if (!LI) return false;
1075
1076 // If they're already in the same block, there's nothing to do.
1077 if (LI->getParent() == I->getParent())
1078 return false;
1079
1080 // If the load has other users and the truncate is not free, this probably
1081 // isn't worthwhile.
1082 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001083 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1084 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001085 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001086 return false;
1087
1088 // Check whether the target supports casts folded into loads.
1089 unsigned LType;
1090 if (isa<ZExtInst>(I))
1091 LType = ISD::ZEXTLOAD;
1092 else {
1093 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1094 LType = ISD::SEXTLOAD;
1095 }
Patrik Hagglund34525f92012-12-11 11:14:33 +00001096 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001097 return false;
1098
1099 // Move the extend into the same block as the load, so that SelectionDAG
1100 // can fold it.
1101 I->removeFromParent();
1102 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001103 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001104 return true;
1105}
1106
Evan Chengbdcb7262007-12-05 23:58:20 +00001107bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1108 BasicBlock *DefBB = I->getParent();
1109
Bob Wilson9120f5c2010-09-21 21:44:14 +00001110 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001111 // other uses of the source with result of extension.
1112 Value *Src = I->getOperand(0);
1113 if (Src->hasOneUse())
1114 return false;
1115
Evan Cheng696e5c02007-12-13 07:50:36 +00001116 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001117 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001118 return false;
1119
Evan Cheng772de512007-12-12 00:51:06 +00001120 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001121 // this block.
1122 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001123 return false;
1124
Evan Chengbdcb7262007-12-05 23:58:20 +00001125 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001126 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001127 UI != E; ++UI) {
1128 Instruction *User = cast<Instruction>(*UI);
1129
1130 // Figure out which BB this ext is used in.
1131 BasicBlock *UserBB = User->getParent();
1132 if (UserBB == DefBB) continue;
1133 DefIsLiveOut = true;
1134 break;
1135 }
1136 if (!DefIsLiveOut)
1137 return false;
1138
Evan Cheng765dff22007-12-12 02:53:41 +00001139 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001140 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001141 UI != E; ++UI) {
1142 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001143 BasicBlock *UserBB = User->getParent();
1144 if (UserBB == DefBB) continue;
1145 // Be conservative. We don't want this xform to end up introducing
1146 // reloads just before load / store instructions.
1147 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001148 return false;
1149 }
1150
Evan Chengbdcb7262007-12-05 23:58:20 +00001151 // InsertedTruncs - Only insert one trunc in each block once.
1152 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1153
1154 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001155 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001156 UI != E; ++UI) {
1157 Use &TheUse = UI.getUse();
1158 Instruction *User = cast<Instruction>(*UI);
1159
1160 // Figure out which BB this ext is used in.
1161 BasicBlock *UserBB = User->getParent();
1162 if (UserBB == DefBB) continue;
1163
1164 // Both src and def are live in this block. Rewrite the use.
1165 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1166
1167 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001168 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001169 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1170 }
1171
1172 // Replace a use of the {s|z}ext source with a use of the result.
1173 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001174 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001175 MadeChange = true;
1176 }
1177
1178 return MadeChange;
1179}
1180
Benjamin Kramer59957502012-05-05 12:49:22 +00001181/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1182/// turned into an explicit branch.
1183static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1184 // FIXME: This should use the same heuristics as IfConversion to determine
1185 // whether a select is better represented as a branch. This requires that
1186 // branch probability metadata is preserved for the select, which is not the
1187 // case currently.
1188
1189 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1190
1191 // If the branch is predicted right, an out of order CPU can avoid blocking on
1192 // the compare. Emit cmovs on compares with a memory operand as branches to
1193 // avoid stalls on the load from memory. If the compare has more than one use
1194 // there's probably another cmov or setcc around so it's not worth emitting a
1195 // branch.
1196 if (!Cmp)
1197 return false;
1198
1199 Value *CmpOp0 = Cmp->getOperand(0);
1200 Value *CmpOp1 = Cmp->getOperand(1);
1201
1202 // We check that the memory operand has one use to avoid uses of the loaded
1203 // value directly after the compare, making branches unprofitable.
1204 return Cmp->hasOneUse() &&
1205 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1206 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1207}
1208
1209
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001210/// If we have a SelectInst that will likely profit from branch prediction,
1211/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001212bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001213 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1214
1215 // Can we convert the 'select' to CF ?
1216 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001217 return false;
1218
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001219 TargetLowering::SelectSupportKind SelectKind;
1220 if (VectorCond)
1221 SelectKind = TargetLowering::VectorMaskSelect;
1222 else if (SI->getType()->isVectorTy())
1223 SelectKind = TargetLowering::ScalarCondVectorVal;
1224 else
1225 SelectKind = TargetLowering::ScalarValSelect;
1226
1227 // Do we have efficient codegen support for this kind of 'selects' ?
1228 if (TLI->isSelectSupported(SelectKind)) {
1229 // We have efficient codegen support for the select instruction.
1230 // Check if it is profitable to keep this 'select'.
1231 if (!TLI->isPredictableSelectExpensive() ||
1232 !isFormingBranchFromSelectProfitable(SI))
1233 return false;
1234 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001235
1236 ModifiedDT = true;
1237
1238 // First, we split the block containing the select into 2 blocks.
1239 BasicBlock *StartBlock = SI->getParent();
1240 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1241 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1242
1243 // Create a new block serving as the landing pad for the branch.
1244 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1245 NextBlock->getParent(), NextBlock);
1246
1247 // Move the unconditional branch from the block with the select in it into our
1248 // landing pad block.
1249 StartBlock->getTerminator()->eraseFromParent();
1250 BranchInst::Create(NextBlock, SmallBlock);
1251
1252 // Insert the real conditional branch based on the original condition.
1253 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1254
1255 // The select itself is replaced with a PHI Node.
1256 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1257 PN->takeName(SI);
1258 PN->addIncoming(SI->getTrueValue(), StartBlock);
1259 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1260 SI->replaceAllUsesWith(PN);
1261 SI->eraseFromParent();
1262
1263 // Instruct OptimizeBlock to skip to the next block.
1264 CurInstIterator = StartBlock->end();
1265 ++NumSelectsExpanded;
1266 return true;
1267}
1268
Cameron Zwarichc0611012011-01-06 02:37:26 +00001269bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001270 if (PHINode *P = dyn_cast<PHINode>(I)) {
1271 // It is possible for very late stage optimizations (such as SimplifyCFG)
1272 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1273 // trivial PHI, go ahead and zap it here.
1274 if (Value *V = SimplifyInstruction(P)) {
1275 P->replaceAllUsesWith(V);
1276 P->eraseFromParent();
1277 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001278 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001279 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001280 return false;
1281 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001282
Chris Lattner1a8943a2011-01-15 07:29:01 +00001283 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001284 // If the source of the cast is a constant, then this should have
1285 // already been constant folded. The only reason NOT to constant fold
1286 // it is if something (e.g. LSR) was careful to place the constant
1287 // evaluation in a block other than then one that uses it (e.g. to hoist
1288 // the address of globals out of a loop). If this is the case, we don't
1289 // want to forward-subst the cast.
1290 if (isa<Constant>(CI->getOperand(0)))
1291 return false;
1292
Chris Lattner1a8943a2011-01-15 07:29:01 +00001293 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1294 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001295
Chris Lattner1a8943a2011-01-15 07:29:01 +00001296 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1297 bool MadeChange = MoveExtToFormExtLoad(I);
1298 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001299 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001300 return false;
1301 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001302
Chris Lattner1a8943a2011-01-15 07:29:01 +00001303 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1304 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001305
Chris Lattner1a8943a2011-01-15 07:29:01 +00001306 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001307 if (TLI)
Hans Wennborg04d7d132012-10-30 11:23:25 +00001308 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1309 return false;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001310 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001311
Chris Lattner1a8943a2011-01-15 07:29:01 +00001312 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001313 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001314 return OptimizeMemoryInst(I, SI->getOperand(1),
1315 SI->getOperand(0)->getType());
1316 return false;
1317 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001318
Chris Lattner1a8943a2011-01-15 07:29:01 +00001319 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001320 if (GEPI->hasAllZeroIndices()) {
1321 /// The GEP operand must be a pointer, so must its result -> BitCast
1322 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1323 GEPI->getName(), GEPI);
1324 GEPI->replaceAllUsesWith(NC);
1325 GEPI->eraseFromParent();
1326 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001327 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001328 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001329 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001330 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001331 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001332
Chris Lattner1a8943a2011-01-15 07:29:01 +00001333 if (CallInst *CI = dyn_cast<CallInst>(I))
1334 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001335
Benjamin Kramer59957502012-05-05 12:49:22 +00001336 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1337 return OptimizeSelectInst(SI);
1338
Chris Lattner1a8943a2011-01-15 07:29:01 +00001339 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001340}
1341
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001342// In this pass we look for GEP and cast instructions that are used
1343// across basic blocks and rewrite them to improve basic-block-at-a-time
1344// selection.
1345bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001346 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001347 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001348
Chris Lattner75796092011-01-15 07:14:54 +00001349 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001350 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001351 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001352
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +00001353 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1354
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001355 return MadeChange;
1356}
Devang Patelf56ea612011-08-18 00:50:51 +00001357
1358// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001359// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001360// find a node corresponding to the value.
1361bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1362 bool MadeChange = false;
1363 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1364 Instruction *PrevNonDbgInst = NULL;
1365 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1366 Instruction *Insn = BI; ++BI;
1367 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1368 if (!DVI) {
1369 PrevNonDbgInst = Insn;
1370 continue;
1371 }
1372
1373 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1374 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1375 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1376 DVI->removeFromParent();
1377 if (isa<PHINode>(VI))
1378 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1379 else
1380 DVI->insertAfter(VI);
1381 MadeChange = true;
1382 ++NumDbgValueMoved;
1383 }
1384 }
1385 }
1386 return MadeChange;
1387}