blob: 65249153bd043a82be10a9f847618741a51f9881 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000022#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000023#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000024#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Pass.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000026#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000027#include "llvm/ADT/SmallSet.h"
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000028#include "llvm/ADT/Statistic.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000029#include "llvm/Analysis/Dominators.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/ProfileInfo.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000032#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000033#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000034#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000035#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000036#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000037#include "llvm/Support/PatternMatch.h"
Chris Lattner94e8e0c2011-01-15 07:25:29 +000038#include "llvm/Support/ValueHandle.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000039#include "llvm/Support/raw_ostream.h"
40#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetLibraryInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Transforms/Utils/AddrModeMatcher.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurd2e2efd92012-09-04 18:22:17 +000046#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000049using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000050
Cameron Zwarich31ff1332011-01-05 17:27:27 +000051STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000052STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
53STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000054STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 "sunken Cmps");
56STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 "of sunken Casts");
58STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000060STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
61STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000063STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000064STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000065
Cameron Zwarich899eaa32011-03-11 21:52:04 +000066static cl::opt<bool> DisableBranchOpts(
67 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
68 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000070static cl::opt<bool> DisableSelectToBranch(
71 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
72 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000073
Eric Christopher692bf6b2008-09-24 05:32:41 +000074namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000075 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000076 /// TLI - Keep a pointer of a TargetLowering to consult for determining
77 /// transformation profitability.
78 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000079 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000080 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000081 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000082
Chris Lattner75796092011-01-15 07:14:54 +000083 /// CurInstIterator - As we scan instructions optimizing them, this is the
84 /// next instruction to optimize. Xforms that can invalidate this should
85 /// update it.
86 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000087
Evan Cheng485fafc2011-03-21 01:19:09 +000088 /// Keeps track of non-local addresses that have been sunk into a block.
89 /// This allows us to avoid inserting duplicate code for blocks with
90 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000091 DenseMap<Value*, Value*> SunkAddrs;
92
Devang Patel52e37df2011-03-24 15:35:25 +000093 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000094 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000095 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +000096
Benjamin Kramer59957502012-05-05 12:49:22 +000097 /// OptSize - True if optimizing for size.
98 bool OptSize;
99
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000100 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000101 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000102 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000103 : FunctionPass(ID), TLI(tli) {
104 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
105 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000106 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000107
Andreas Neustifterad809812009-09-16 09:26:52 +0000108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000109 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000110 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000111 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000112 }
113
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000114 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000115 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-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 Lattnerdbe0dec2007-03-31 04:06:36 +0000119 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000120 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000121 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000122 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000123 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000124 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000125 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000126 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000127 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000128 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000129 };
130}
Devang Patel794fd752007-05-01 21:15:47 +0000131
Devang Patel19974732007-05-03 01:11:54 +0000132char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-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 Andersonce665bd2010-10-07 22:25:06 +0000137 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000138
139FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
140 return new CodeGenPrepare(TLI);
141}
142
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000143bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000144 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000145
Devang Patel52e37df2011-03-24 15:35:25 +0000146 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000147 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000148 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000149 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000150 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000151
Preston Gurd2e2efd92012-09-04 18:22:17 +0000152 /// This optimization identifies DIV instructions that can be
153 /// profitably bypassed and carried out with a shorter, faster divide.
154 if (TLI && TLI->isSlowDivBypassed()) {
Evan Cheng911908d2012-09-14 21:25:34 +0000155 const DenseMap<Type*, Type*> &BypassTypeMap = TLI->getBypassSlowDivTypes();
156 for (Function::iterator I = F.begin(); I != F.end(); I++)
157 EverMadeChange |= bypassSlowDivision(F, I, BypassTypeMap);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000158 }
159
160 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000161 // unconditional branch.
162 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000163
Devang Patelf56ea612011-08-18 00:50:51 +0000164 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000165 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000166 // find a node corresponding to the value.
167 EverMadeChange |= PlaceDbgValues(F);
168
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000169 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000170 while (MadeChange) {
171 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000172 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
173 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000174 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000175 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000176 EverMadeChange |= MadeChange;
177 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000178
179 SunkAddrs.clear();
180
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000181 if (!DisableBranchOpts) {
182 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000183 SmallPtrSet<BasicBlock*, 8> WorkList;
184 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
185 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000186 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000187 if (!MadeChange) continue;
188
189 for (SmallVectorImpl<BasicBlock*>::iterator
190 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
191 if (pred_begin(*II) == pred_end(*II))
192 WorkList.insert(*II);
193 }
194
Bill Wendling8dd2e5b2012-08-15 21:18:10 +0000195 for (SmallPtrSet<BasicBlock*, 8>::iterator
196 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
197 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000198
Nadav Rotem3e883732012-08-14 05:19:07 +0000199 // Merge pairs of basic blocks with unconditional branches, connected by
200 // a single edge.
201 if (EverMadeChange || MadeChange)
202 MadeChange |= EliminateFallThrough(F);
203
Evan Cheng485fafc2011-03-21 01:19:09 +0000204 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000205 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000206 EverMadeChange |= MadeChange;
207 }
208
Devang Patel52e37df2011-03-24 15:35:25 +0000209 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000210 DT->DT->recalculate(F);
211
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000212 return EverMadeChange;
213}
214
Nadav Rotem3e883732012-08-14 05:19:07 +0000215/// EliminateFallThrough - Merge basic blocks which are connected
216/// by a single edge, where one of the basic blocks has a single successor
217/// pointing to the other basic block, which has a single predecessor.
218bool CodeGenPrepare::EliminateFallThrough(Function &F) {
219 bool Changed = false;
220 // Scan all of the blocks in the function, except for the entry block.
221 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
222 BasicBlock *BB = I++;
223 // If the destination block has a single pred, then this is a trivial
224 // edge, just collapse it.
225 BasicBlock *SinglePred = BB->getSinglePredecessor();
226
227 if (!SinglePred || SinglePred == BB) continue;
228
229 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
230 if (Term && !Term->isConditional()) {
231 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000232 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000233 // Remember if SinglePred was the entry block of the function.
234 // If so, we will need to move BB back to the entry position.
235 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
236 MergeBasicBlockIntoOnlyPred(BB, this);
237
238 if (isEntry && BB != &BB->getParent()->getEntryBlock())
239 BB->moveBefore(&BB->getParent()->getEntryBlock());
240
241 // We have erased a block. Update the iterator.
242 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000243 }
244 }
245 return Changed;
246}
247
Dale Johannesen2d697242009-03-27 01:13:37 +0000248/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
249/// debug info directives, and an unconditional branch. Passes before isel
250/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
251/// isel. Start by eliminating these blocks so we can split them the way we
252/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000253bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
254 bool MadeChange = false;
255 // Note that this intentionally skips the entry block.
256 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
257 BasicBlock *BB = I++;
258
259 // If this block doesn't end with an uncond branch, ignore it.
260 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
261 if (!BI || !BI->isUnconditional())
262 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000263
Dale Johannesen2d697242009-03-27 01:13:37 +0000264 // If the instruction before the branch (skipping debug info) isn't a phi
265 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000266 BasicBlock::iterator BBI = BI;
267 if (BBI != BB->begin()) {
268 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000269 while (isa<DbgInfoIntrinsic>(BBI)) {
270 if (BBI == BB->begin())
271 break;
272 --BBI;
273 }
274 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
275 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000277
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000278 // Do not break infinite loops.
279 BasicBlock *DestBB = BI->getSuccessor(0);
280 if (DestBB == BB)
281 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000282
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000283 if (!CanMergeBlocks(BB, DestBB))
284 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000285
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000286 EliminateMostlyEmptyBlock(BB);
287 MadeChange = true;
288 }
289 return MadeChange;
290}
291
292/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
293/// single uncond branch between them, and BB contains no other non-phi
294/// instructions.
295bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
296 const BasicBlock *DestBB) const {
297 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
298 // the successor. If there are more complex condition (e.g. preheaders),
299 // don't mess around with them.
300 BasicBlock::const_iterator BBI = BB->begin();
301 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000302 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000303 UI != E; ++UI) {
304 const Instruction *User = cast<Instruction>(*UI);
305 if (User->getParent() != DestBB || !isa<PHINode>(User))
306 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000307 // If User is inside DestBB block and it is a PHINode then check
308 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000309 // a complex condition (e.g. preheaders) we want to avoid here.
310 if (User->getParent() == DestBB) {
311 if (const PHINode *UPN = dyn_cast<PHINode>(User))
312 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
313 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
314 if (Insn && Insn->getParent() == BB &&
315 Insn->getParent() != UPN->getIncomingBlock(I))
316 return false;
317 }
318 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000319 }
320 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000321
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000322 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
323 // and DestBB may have conflicting incoming values for the block. If so, we
324 // can't merge the block.
325 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
326 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000327
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000328 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000329 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000330 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
331 // It is faster to get preds from a PHI than with pred_iterator.
332 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
333 BBPreds.insert(BBPN->getIncomingBlock(i));
334 } else {
335 BBPreds.insert(pred_begin(BB), pred_end(BB));
336 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000337
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000338 // Walk the preds of DestBB.
339 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
340 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
341 if (BBPreds.count(Pred)) { // Common predecessor?
342 BBI = DestBB->begin();
343 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
344 const Value *V1 = PN->getIncomingValueForBlock(Pred);
345 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000346
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000347 // If V2 is a phi node in BB, look up what the mapped value will be.
348 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
349 if (V2PN->getParent() == BB)
350 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000351
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000352 // If there is a conflict, bail out.
353 if (V1 != V2) return false;
354 }
355 }
356 }
357
358 return true;
359}
360
361
362/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
363/// an unconditional branch in it.
364void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
365 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
366 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000367
David Greene68d67fd2010-01-05 01:27:11 +0000368 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000369
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000370 // If the destination block has a single pred, then this is a trivial edge,
371 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000372 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000373 if (SinglePred != DestBB) {
374 // Remember if SinglePred was the entry block of the function. If so, we
375 // will need to move BB back to the entry position.
376 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000377 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000378
Chris Lattnerf5102a02008-11-28 19:54:49 +0000379 if (isEntry && BB != &BB->getParent()->getEntryBlock())
380 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000381
David Greene68d67fd2010-01-05 01:27:11 +0000382 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000383 return;
384 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000385 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000387 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
388 // to handle the new incoming edges it is about to have.
389 PHINode *PN;
390 for (BasicBlock::iterator BBI = DestBB->begin();
391 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
392 // Remove the incoming value for BB, and remember it.
393 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000394
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000395 // Two options: either the InVal is a phi node defined in BB or it is some
396 // value that dominates BB.
397 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
398 if (InValPhi && InValPhi->getParent() == BB) {
399 // Add all of the input values of the input PHI as inputs of this phi.
400 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
401 PN->addIncoming(InValPhi->getIncomingValue(i),
402 InValPhi->getIncomingBlock(i));
403 } else {
404 // Otherwise, add one instance of the dominating value for each edge that
405 // we will be adding.
406 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
407 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
408 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
409 } else {
410 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
411 PN->addIncoming(InVal, *PI);
412 }
413 }
414 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000415
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000416 // The PHIs are now updated, change everything that refers to BB to use
417 // DestBB and remove BB.
418 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000419 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000420 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
421 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
422 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
423 DT->changeImmediateDominator(DestBB, NewIDom);
424 DT->eraseNode(BB);
425 }
Evan Cheng04149f72009-12-17 09:39:49 +0000426 if (PFI) {
427 PFI->replaceAllUses(BB, DestBB);
428 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000429 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000430 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000431 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
David Greene68d67fd2010-01-05 01:27:11 +0000433 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000434}
435
Chris Lattnerdd77df32007-04-13 20:30:56 +0000436/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000437/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
438/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000439/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000440///
441/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000442///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000443static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000445 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
446 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000447
Chris Lattnerdd77df32007-04-13 20:30:56 +0000448 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000449 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000450 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000451
Chris Lattnerdd77df32007-04-13 20:30:56 +0000452 // If this is an extension, it will be a zero or sign extension, which
453 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000454 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Chris Lattnerdd77df32007-04-13 20:30:56 +0000456 // If these values will be promoted, find out what they will be promoted
457 // to. This helps us consider truncates on PPC as noop copies when they
458 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000459 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
460 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000461 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000462 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
463 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000464 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdd77df32007-04-13 20:30:56 +0000466 // If, after promotion, these are the same types, this is a noop copy.
467 if (SrcVT != DstVT)
468 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000469
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000470 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000473 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000476 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 UI != E; ) {
478 Use &TheUse = UI.getUse();
479 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 // Figure out which BB this cast is used in. For PHI's this is the
482 // appropriate predecessor block.
483 BasicBlock *UserBB = User->getParent();
484 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000485 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000486 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 // Preincrement use iterator so we don't invalidate it.
489 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 // If this user is in the same block as the cast, don't change the cast.
492 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 // If we have already inserted a cast into this block, use it.
495 CastInst *&InsertedCast = InsertedCasts[UserBB];
496
497 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000498 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000499 InsertedCast =
500 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000501 InsertPt);
502 MadeChange = true;
503 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Dale Johannesence0b2372007-06-12 16:50:17 +0000505 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000506 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000507 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000509
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000510 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000511 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000512 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000513 MadeChange = true;
514 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000515
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000516 return MadeChange;
517}
518
Eric Christopher692bf6b2008-09-24 05:32:41 +0000519/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000520/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000521/// a clear win except on targets with multiple condition code registers
522/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000523///
524/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000525static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000526 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 /// InsertedCmp - Only insert a cmp in each block once.
529 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000533 UI != E; ) {
534 Use &TheUse = UI.getUse();
535 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536
Dale Johannesence0b2372007-06-12 16:50:17 +0000537 // Preincrement use iterator so we don't invalidate it.
538 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000539
Dale Johannesence0b2372007-06-12 16:50:17 +0000540 // Don't bother for PHI nodes.
541 if (isa<PHINode>(User))
542 continue;
543
544 // Figure out which BB this cmp is used in.
545 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 // If this user is in the same block as the cmp, don't change the cmp.
548 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000549
Dale Johannesence0b2372007-06-12 16:50:17 +0000550 // If we have already inserted a cmp into this block, use it.
551 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
552
553 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000554 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000555 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000556 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000557 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000558 CI->getOperand(1), "", InsertPt);
559 MadeChange = true;
560 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000561
Dale Johannesence0b2372007-06-12 16:50:17 +0000562 // Replace a use of the cmp with a use of the new cmp.
563 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000564 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000565 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Dale Johannesence0b2372007-06-12 16:50:17 +0000567 // If we removed all uses, nuke the cmp.
568 if (CI->use_empty())
569 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000570
Dale Johannesence0b2372007-06-12 16:50:17 +0000571 return MadeChange;
572}
573
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000574namespace {
575class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
576protected:
577 void replaceCall(Value *With) {
578 CI->replaceAllUsesWith(With);
579 CI->eraseFromParent();
580 }
581 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000582 if (ConstantInt *SizeCI =
583 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
584 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000585 return false;
586 }
587};
588} // end anonymous namespace
589
Eric Christopher040056f2010-03-11 02:41:03 +0000590bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000591 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000592
Chris Lattner75796092011-01-15 07:14:54 +0000593 // Lower inline assembly if we can.
594 // If we found an inline asm expession, and if the target knows how to
595 // lower it to normal LLVM code, do so now.
596 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
597 if (TLI->ExpandInlineAsm(CI)) {
598 // Avoid invalidating the iterator.
599 CurInstIterator = BB->begin();
600 // Avoid processing instructions out of order, which could cause
601 // reuse before a value is defined.
602 SunkAddrs.clear();
603 return true;
604 }
605 // Sink address computing for memory operands into the block.
606 if (OptimizeInlineAsmInst(CI))
607 return true;
608 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000609
Eric Christopher040056f2010-03-11 02:41:03 +0000610 // Lower all uses of llvm.objectsize.*
611 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
612 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000613 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000614 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000615 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
616
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000617 // Substituting this can cause recursive simplifications, which can
618 // invalidate our iterator. Use a WeakVH to hold onto it in case this
619 // happens.
620 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000621
Chandler Carruth6b980542012-03-24 21:11:24 +0000622 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
623 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000624
625 // If the iterator instruction was recursively deleted, start over at the
626 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000627 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000628 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000629 SunkAddrs.clear();
630 }
Eric Christopher040056f2010-03-11 02:41:03 +0000631 return true;
632 }
633
Pete Cooperf210b682012-03-13 20:59:56 +0000634 if (II && TLI) {
635 SmallVector<Value*, 2> PtrOps;
636 Type *AccessTy;
637 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
638 while (!PtrOps.empty())
639 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
640 return true;
641 }
642
Eric Christopher040056f2010-03-11 02:41:03 +0000643 // From here on out we're working with named functions.
644 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000645
Eric Christopher040056f2010-03-11 02:41:03 +0000646 // We'll need TargetData from here on out.
647 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
648 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000649
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000650 // Lower all default uses of _chk calls. This is very similar
651 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000652 // that have the default "don't know" as the objectsize. Anything else
653 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000654 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000655 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000656}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000657
Evan Cheng485fafc2011-03-21 01:19:09 +0000658/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
659/// instructions to the predecessor to enable tail call optimizations. The
660/// case it is currently looking for is:
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000661/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000662/// bb0:
663/// %tmp0 = tail call i32 @f0()
664/// br label %return
665/// bb1:
666/// %tmp1 = tail call i32 @f1()
667/// br label %return
668/// bb2:
669/// %tmp2 = tail call i32 @f2()
670/// br label %return
671/// return:
672/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
673/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000674/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000675///
676/// =>
677///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000678/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000679/// bb0:
680/// %tmp0 = tail call i32 @f0()
681/// ret i32 %tmp0
682/// bb1:
683/// %tmp1 = tail call i32 @f1()
684/// ret i32 %tmp1
685/// bb2:
686/// %tmp2 = tail call i32 @f2()
687/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000688/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000689bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000690 if (!TLI)
691 return false;
692
Evan Cheng9c777a42012-07-27 21:21:26 +0000693 PHINode *PN = 0;
694 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000695 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000696 if (V) {
697 BCI = dyn_cast<BitCastInst>(V);
698 if (BCI)
699 V = BCI->getOperand(0);
700
701 PN = dyn_cast<PHINode>(V);
702 if (!PN)
703 return false;
704 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000705
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000706 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000707 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000708 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000709
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000710 // It's not safe to eliminate the sign / zero extension of the return value.
711 // See llvm::isInTailCallPosition().
712 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000713 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000714 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
715 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000716
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000717 // Make sure there are no instructions between the PHI and return, or that the
718 // return is the first instruction in the block.
719 if (PN) {
720 BasicBlock::iterator BI = BB->begin();
721 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000722 if (&*BI == BCI)
723 // Also skip over the bitcast.
724 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000725 if (&*BI != RI)
726 return false;
727 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000728 BasicBlock::iterator BI = BB->begin();
729 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
730 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000731 return false;
732 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000733
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000734 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
735 /// call.
736 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000737 if (PN) {
738 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
739 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
740 // Make sure the phi value is indeed produced by the tail call.
741 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
742 TLI->mayBeEmittedAsTailCall(CI))
743 TailCalls.push_back(CI);
744 }
745 } else {
746 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
747 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
748 if (!VisitedBBs.insert(*PI))
749 continue;
750
751 BasicBlock::InstListType &InstList = (*PI)->getInstList();
752 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
753 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000754 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
755 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000756 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000757
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000758 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000759 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000760 TailCalls.push_back(CI);
761 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000762 }
763
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000764 bool Changed = false;
765 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
766 CallInst *CI = TailCalls[i];
767 CallSite CS(CI);
768
769 // Conservatively require the attributes of the call to match those of the
770 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000771 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000772 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
773 continue;
774
775 // Make sure the call instruction is followed by an unconditional branch to
776 // the return block.
777 BasicBlock *CallBB = CI->getParent();
778 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
779 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
780 continue;
781
782 // Duplicate the return into CallBB.
783 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000784 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000785 ++NumRetsDup;
786 }
787
788 // If we eliminated all predecessors of the block, delete the block now.
789 if (Changed && pred_begin(BB) == pred_end(BB))
790 BB->eraseFromParent();
791
792 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000793}
794
Chris Lattner88a5c832008-11-25 07:09:13 +0000795//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000796// Memory Optimization
797//===----------------------------------------------------------------------===//
798
Chris Lattnerdd77df32007-04-13 20:30:56 +0000799/// IsNonLocalValue - Return true if the specified values are defined in a
800/// different basic block than BB.
801static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
802 if (Instruction *I = dyn_cast<Instruction>(V))
803 return I->getParent() != BB;
804 return false;
805}
806
Bob Wilson4a8ee232009-12-03 21:47:07 +0000807/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000808/// addressing modes that can do significant amounts of computation. As such,
809/// instruction selection will try to get the load or store to do as much
810/// computation as possible for the program. The problem is that isel can only
811/// see within a single block. As such, we sink as much legal addressing mode
812/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000813///
814/// This method is used to optimize both load/store and inline asms with memory
815/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000816bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000817 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000818 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000819
820 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000821 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000822 SmallVector<Value*, 8> worklist;
823 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000824 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000825
Owen Anderson35bf4d62010-11-27 08:15:55 +0000826 // Use a worklist to iteratively look through PHI nodes, and ensure that
827 // the addressing mode obtained from the non-PHI roots of the graph
828 // are equivalent.
829 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000830 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000831 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000832 SmallVector<Instruction*, 16> AddrModeInsts;
833 ExtAddrMode AddrMode;
834 while (!worklist.empty()) {
835 Value *V = worklist.back();
836 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000837
Owen Anderson35bf4d62010-11-27 08:15:55 +0000838 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000839 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000840 Consensus = 0;
841 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000842 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000843
Owen Anderson35bf4d62010-11-27 08:15:55 +0000844 // For a PHI node, push all of its incoming values.
845 if (PHINode *P = dyn_cast<PHINode>(V)) {
846 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
847 worklist.push_back(P->getIncomingValue(i));
848 continue;
849 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000850
Owen Anderson35bf4d62010-11-27 08:15:55 +0000851 // For non-PHIs, determine the addressing mode being computed.
852 SmallVector<Instruction*, 16> NewAddrModeInsts;
853 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000854 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000855 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000856
857 // This check is broken into two cases with very similar code to avoid using
858 // getNumUses() as much as possible. Some values have a lot of uses, so
859 // calling getNumUses() unconditionally caused a significant compile-time
860 // regression.
861 if (!Consensus) {
862 Consensus = V;
863 AddrMode = NewAddrMode;
864 AddrModeInsts = NewAddrModeInsts;
865 continue;
866 } else if (NewAddrMode == AddrMode) {
867 if (!IsNumUsesConsensusValid) {
868 NumUsesConsensus = Consensus->getNumUses();
869 IsNumUsesConsensusValid = true;
870 }
871
872 // Ensure that the obtained addressing mode is equivalent to that obtained
873 // for all other roots of the PHI traversal. Also, when choosing one
874 // such root as representative, select the one with the most uses in order
875 // to keep the cost modeling heuristics in AddressingModeMatcher
876 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000877 unsigned NumUses = V->getNumUses();
878 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000879 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000880 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000881 AddrModeInsts = NewAddrModeInsts;
882 }
883 continue;
884 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000885
Owen Anderson35bf4d62010-11-27 08:15:55 +0000886 Consensus = 0;
887 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000888 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000889
Owen Anderson35bf4d62010-11-27 08:15:55 +0000890 // If the addressing mode couldn't be determined, or if multiple different
891 // ones were determined, bail out now.
892 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000893
Chris Lattnerdd77df32007-04-13 20:30:56 +0000894 // Check to see if any of the instructions supersumed by this addr mode are
895 // non-local to I's BB.
896 bool AnyNonLocal = false;
897 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000898 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000899 AnyNonLocal = true;
900 break;
901 }
902 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000903
Chris Lattnerdd77df32007-04-13 20:30:56 +0000904 // If all the instructions matched are already in this BB, don't do anything.
905 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000906 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000907 return false;
908 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000909
Chris Lattnerdd77df32007-04-13 20:30:56 +0000910 // Insert this computation right after this user. Since our caller is
911 // scanning from the top of the BB to the bottom, reuse of the expr are
912 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000913 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000914
Chris Lattnerdd77df32007-04-13 20:30:56 +0000915 // Now that we determined the addressing expression we want to use and know
916 // that we have to sink it into this block. Check to see if we have already
917 // done this for some other load/store instr in this block. If so, reuse the
918 // computation.
919 Value *&SunkAddr = SunkAddrs[Addr];
920 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000921 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000922 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000924 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000926 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000927 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000928 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000929 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000930
Chris Lattnerdd77df32007-04-13 20:30:56 +0000931 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000932
933 // Start with the base register. Do this first so that subsequent address
934 // matching finds it last, which will prevent it from trying to match it
935 // as the scaled value in case it happens to be a mul. That would be
936 // problematic if we've sunk a different mul for the scale, because then
937 // we'd end up sinking both muls.
938 if (AddrMode.BaseReg) {
939 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000940 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000941 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000942 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000943 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000944 Result = V;
945 }
946
947 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000948 if (AddrMode.Scale) {
949 Value *V = AddrMode.ScaledReg;
950 if (V->getType() == IntPtrTy) {
951 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000952 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000953 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000954 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
955 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000956 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000958 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000959 }
960 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000961 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
962 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000963 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000964 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000965 else
966 Result = V;
967 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000968
Chris Lattnerdd77df32007-04-13 20:30:56 +0000969 // Add in the BaseGV if present.
970 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000971 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000972 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000973 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000974 else
975 Result = V;
976 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000977
Chris Lattnerdd77df32007-04-13 20:30:56 +0000978 // Add in the Base Offset if present.
979 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000980 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000981 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000982 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000983 else
984 Result = V;
985 }
986
987 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000988 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000989 else
Devang Patel2048c372011-09-06 18:49:53 +0000990 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000991 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000992
Owen Andersond2f41742010-11-19 22:15:03 +0000993 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000994
Chris Lattner0403b472011-04-09 07:05:44 +0000995 // If we have no uses, recursively delete the value and all dead instructions
996 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000997 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000998 // This can cause recursive deletion, which can invalidate our iterator.
999 // Use a WeakVH to hold onto it in case this happens.
1000 WeakVH IterHandle(CurInstIterator);
1001 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001002
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001003 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001004
1005 if (IterHandle != CurInstIterator) {
1006 // If the iterator instruction was recursively deleted, start over at the
1007 // start of the block.
1008 CurInstIterator = BB->begin();
1009 SunkAddrs.clear();
1010 } else {
1011 // This address is now available for reassignment, so erase the table
1012 // entry; we don't want to match some completely different instruction.
1013 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001014 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001015 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001016 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001017 return true;
1018}
1019
Evan Cheng9bf12b52008-02-26 02:42:37 +00001020/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001021/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001022/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001023bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001024 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001025
Nadav Rotema94d6e82012-07-24 10:51:42 +00001026 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001027 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001028 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001029 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1030 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001031
Evan Cheng9bf12b52008-02-26 02:42:37 +00001032 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001033 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001034
Eli Friedman9ec80952008-02-26 18:37:49 +00001035 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1036 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001037 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001038 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001039 } else if (OpInfo.Type == InlineAsm::isInput)
1040 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001041 }
1042
1043 return MadeChange;
1044}
1045
Dan Gohmanb00f2362009-10-16 20:59:35 +00001046/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1047/// basic block as the load, unless conditions are unfavorable. This allows
1048/// SelectionDAG to fold the extend into the load.
1049///
1050bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1051 // Look for a load being extended.
1052 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1053 if (!LI) return false;
1054
1055 // If they're already in the same block, there's nothing to do.
1056 if (LI->getParent() == I->getParent())
1057 return false;
1058
1059 // If the load has other users and the truncate is not free, this probably
1060 // isn't worthwhile.
1061 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001062 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1063 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001064 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001065 return false;
1066
1067 // Check whether the target supports casts folded into loads.
1068 unsigned LType;
1069 if (isa<ZExtInst>(I))
1070 LType = ISD::ZEXTLOAD;
1071 else {
1072 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1073 LType = ISD::SEXTLOAD;
1074 }
1075 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1076 return false;
1077
1078 // Move the extend into the same block as the load, so that SelectionDAG
1079 // can fold it.
1080 I->removeFromParent();
1081 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001082 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001083 return true;
1084}
1085
Evan Chengbdcb7262007-12-05 23:58:20 +00001086bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1087 BasicBlock *DefBB = I->getParent();
1088
Bob Wilson9120f5c2010-09-21 21:44:14 +00001089 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001090 // other uses of the source with result of extension.
1091 Value *Src = I->getOperand(0);
1092 if (Src->hasOneUse())
1093 return false;
1094
Evan Cheng696e5c02007-12-13 07:50:36 +00001095 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001096 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001097 return false;
1098
Evan Cheng772de512007-12-12 00:51:06 +00001099 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001100 // this block.
1101 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001102 return false;
1103
Evan Chengbdcb7262007-12-05 23:58:20 +00001104 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001105 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001106 UI != E; ++UI) {
1107 Instruction *User = cast<Instruction>(*UI);
1108
1109 // Figure out which BB this ext is used in.
1110 BasicBlock *UserBB = User->getParent();
1111 if (UserBB == DefBB) continue;
1112 DefIsLiveOut = true;
1113 break;
1114 }
1115 if (!DefIsLiveOut)
1116 return false;
1117
Evan Cheng765dff22007-12-12 02:53:41 +00001118 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001119 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001120 UI != E; ++UI) {
1121 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001122 BasicBlock *UserBB = User->getParent();
1123 if (UserBB == DefBB) continue;
1124 // Be conservative. We don't want this xform to end up introducing
1125 // reloads just before load / store instructions.
1126 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001127 return false;
1128 }
1129
Evan Chengbdcb7262007-12-05 23:58:20 +00001130 // InsertedTruncs - Only insert one trunc in each block once.
1131 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1132
1133 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001134 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001135 UI != E; ++UI) {
1136 Use &TheUse = UI.getUse();
1137 Instruction *User = cast<Instruction>(*UI);
1138
1139 // Figure out which BB this ext is used in.
1140 BasicBlock *UserBB = User->getParent();
1141 if (UserBB == DefBB) continue;
1142
1143 // Both src and def are live in this block. Rewrite the use.
1144 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1145
1146 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001147 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001148 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1149 }
1150
1151 // Replace a use of the {s|z}ext source with a use of the result.
1152 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001153 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001154 MadeChange = true;
1155 }
1156
1157 return MadeChange;
1158}
1159
Benjamin Kramer59957502012-05-05 12:49:22 +00001160/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1161/// turned into an explicit branch.
1162static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1163 // FIXME: This should use the same heuristics as IfConversion to determine
1164 // whether a select is better represented as a branch. This requires that
1165 // branch probability metadata is preserved for the select, which is not the
1166 // case currently.
1167
1168 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1169
1170 // If the branch is predicted right, an out of order CPU can avoid blocking on
1171 // the compare. Emit cmovs on compares with a memory operand as branches to
1172 // avoid stalls on the load from memory. If the compare has more than one use
1173 // there's probably another cmov or setcc around so it's not worth emitting a
1174 // branch.
1175 if (!Cmp)
1176 return false;
1177
1178 Value *CmpOp0 = Cmp->getOperand(0);
1179 Value *CmpOp1 = Cmp->getOperand(1);
1180
1181 // We check that the memory operand has one use to avoid uses of the loaded
1182 // value directly after the compare, making branches unprofitable.
1183 return Cmp->hasOneUse() &&
1184 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1185 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1186}
1187
1188
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001189/// If we have a SelectInst that will likely profit from branch prediction,
1190/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001191bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001192 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1193
1194 // Can we convert the 'select' to CF ?
1195 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001196 return false;
1197
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001198 TargetLowering::SelectSupportKind SelectKind;
1199 if (VectorCond)
1200 SelectKind = TargetLowering::VectorMaskSelect;
1201 else if (SI->getType()->isVectorTy())
1202 SelectKind = TargetLowering::ScalarCondVectorVal;
1203 else
1204 SelectKind = TargetLowering::ScalarValSelect;
1205
1206 // Do we have efficient codegen support for this kind of 'selects' ?
1207 if (TLI->isSelectSupported(SelectKind)) {
1208 // We have efficient codegen support for the select instruction.
1209 // Check if it is profitable to keep this 'select'.
1210 if (!TLI->isPredictableSelectExpensive() ||
1211 !isFormingBranchFromSelectProfitable(SI))
1212 return false;
1213 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001214
1215 ModifiedDT = true;
1216
1217 // First, we split the block containing the select into 2 blocks.
1218 BasicBlock *StartBlock = SI->getParent();
1219 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1220 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1221
1222 // Create a new block serving as the landing pad for the branch.
1223 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1224 NextBlock->getParent(), NextBlock);
1225
1226 // Move the unconditional branch from the block with the select in it into our
1227 // landing pad block.
1228 StartBlock->getTerminator()->eraseFromParent();
1229 BranchInst::Create(NextBlock, SmallBlock);
1230
1231 // Insert the real conditional branch based on the original condition.
1232 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1233
1234 // The select itself is replaced with a PHI Node.
1235 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1236 PN->takeName(SI);
1237 PN->addIncoming(SI->getTrueValue(), StartBlock);
1238 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1239 SI->replaceAllUsesWith(PN);
1240 SI->eraseFromParent();
1241
1242 // Instruct OptimizeBlock to skip to the next block.
1243 CurInstIterator = StartBlock->end();
1244 ++NumSelectsExpanded;
1245 return true;
1246}
1247
Cameron Zwarichc0611012011-01-06 02:37:26 +00001248bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001249 if (PHINode *P = dyn_cast<PHINode>(I)) {
1250 // It is possible for very late stage optimizations (such as SimplifyCFG)
1251 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1252 // trivial PHI, go ahead and zap it here.
1253 if (Value *V = SimplifyInstruction(P)) {
1254 P->replaceAllUsesWith(V);
1255 P->eraseFromParent();
1256 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001257 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001258 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001259 return false;
1260 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001261
Chris Lattner1a8943a2011-01-15 07:29:01 +00001262 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001263 // If the source of the cast is a constant, then this should have
1264 // already been constant folded. The only reason NOT to constant fold
1265 // it is if something (e.g. LSR) was careful to place the constant
1266 // evaluation in a block other than then one that uses it (e.g. to hoist
1267 // the address of globals out of a loop). If this is the case, we don't
1268 // want to forward-subst the cast.
1269 if (isa<Constant>(CI->getOperand(0)))
1270 return false;
1271
Chris Lattner1a8943a2011-01-15 07:29:01 +00001272 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1273 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001274
Chris Lattner1a8943a2011-01-15 07:29:01 +00001275 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1276 bool MadeChange = MoveExtToFormExtLoad(I);
1277 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001278 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001279 return false;
1280 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001281
Chris Lattner1a8943a2011-01-15 07:29:01 +00001282 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1283 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001284
Chris Lattner1a8943a2011-01-15 07:29:01 +00001285 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001286 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001287 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1288 return false;
1289 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001290
Chris Lattner1a8943a2011-01-15 07:29:01 +00001291 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001292 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001293 return OptimizeMemoryInst(I, SI->getOperand(1),
1294 SI->getOperand(0)->getType());
1295 return false;
1296 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001297
Chris Lattner1a8943a2011-01-15 07:29:01 +00001298 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001299 if (GEPI->hasAllZeroIndices()) {
1300 /// The GEP operand must be a pointer, so must its result -> BitCast
1301 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1302 GEPI->getName(), GEPI);
1303 GEPI->replaceAllUsesWith(NC);
1304 GEPI->eraseFromParent();
1305 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001306 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001307 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001308 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001309 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001310 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001311
Chris Lattner1a8943a2011-01-15 07:29:01 +00001312 if (CallInst *CI = dyn_cast<CallInst>(I))
1313 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001314
Evan Cheng485fafc2011-03-21 01:19:09 +00001315 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1316 return DupRetToEnableTailCallOpts(RI);
1317
Benjamin Kramer59957502012-05-05 12:49:22 +00001318 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1319 return OptimizeSelectInst(SI);
1320
Chris Lattner1a8943a2011-01-15 07:29:01 +00001321 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001322}
1323
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001324// In this pass we look for GEP and cast instructions that are used
1325// across basic blocks and rewrite them to improve basic-block-at-a-time
1326// selection.
1327bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001328 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001329 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001330
Chris Lattner75796092011-01-15 07:14:54 +00001331 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001332 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1333 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001334
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001335 return MadeChange;
1336}
Devang Patelf56ea612011-08-18 00:50:51 +00001337
1338// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001339// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001340// find a node corresponding to the value.
1341bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1342 bool MadeChange = false;
1343 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1344 Instruction *PrevNonDbgInst = NULL;
1345 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1346 Instruction *Insn = BI; ++BI;
1347 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1348 if (!DVI) {
1349 PrevNonDbgInst = Insn;
1350 continue;
1351 }
1352
1353 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1354 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1355 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1356 DVI->removeFromParent();
1357 if (isa<PHINode>(VI))
1358 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1359 else
1360 DVI->insertAfter(VI);
1361 MadeChange = true;
1362 ++NumDbgValueMoved;
1363 }
1364 }
1365 }
1366 return MadeChange;
1367}