blob: 84fa55131c18bbf629e226d7aa0d85b3a3d0fa82 [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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/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
Evan Chenga16422f2012-12-21 01:48:14 +0000109 const char *getPassName() const { return "CodeGen Prepare"; }
110
Andreas Neustifterad809812009-09-16 09:26:52 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000112 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000113 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000114 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000115 }
116
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000117 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000118 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000122 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000123 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000125 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000126 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000127 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000128 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000129 bool OptimizeSelectInst(SelectInst *SI);
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000130 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patelf56ea612011-08-18 00:50:51 +0000131 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000132 };
133}
Devang Patel794fd752007-05-01 21:15:47 +0000134
Devang Patel19974732007-05-03 01:11:54 +0000135char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000136INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000140 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000141
142FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
144}
145
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000146bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Devang Patel52e37df2011-03-24 15:35:25 +0000149 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000150 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000151 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000152 PFI = getAnalysisIfAvailable<ProfileInfo>();
Bill Wendling831737d2012-12-30 10:32:01 +0000153 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
154 Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000155
Preston Gurd2e2efd92012-09-04 18:22:17 +0000156 /// This optimization identifies DIV instructions that can be
157 /// profitably bypassed and carried out with a shorter, faster divide.
158 if (TLI && TLI->isSlowDivBypassed()) {
Preston Gurd8d662b52012-10-04 21:33:40 +0000159 const DenseMap<unsigned int, unsigned int> &BypassWidths =
160 TLI->getBypassSlowDivWidths();
Evan Cheng911908d2012-09-14 21:25:34 +0000161 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd8d662b52012-10-04 21:33:40 +0000162 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurd2e2efd92012-09-04 18:22:17 +0000163 }
164
165 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000166 // unconditional branch.
167 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000168
Devang Patelf56ea612011-08-18 00:50:51 +0000169 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000170 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000171 // find a node corresponding to the value.
172 EverMadeChange |= PlaceDbgValues(F);
173
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000174 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000175 while (MadeChange) {
176 MadeChange = false;
Hans Wennborg93ba1332012-09-19 07:48:16 +0000177 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng485fafc2011-03-21 01:19:09 +0000178 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000179 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000180 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000181 EverMadeChange |= MadeChange;
182 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000183
184 SunkAddrs.clear();
185
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000186 if (!DisableBranchOpts) {
187 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000188 SmallPtrSet<BasicBlock*, 8> WorkList;
189 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
190 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000191 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000192 if (!MadeChange) continue;
193
194 for (SmallVectorImpl<BasicBlock*>::iterator
195 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
196 if (pred_begin(*II) == pred_end(*II))
197 WorkList.insert(*II);
198 }
199
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000200 // Delete the dead blocks and any of their dead successors.
Bill Wendling1c211642012-12-06 00:30:20 +0000201 MadeChange |= !WorkList.empty();
Bill Wendlingbf2ad732012-11-28 23:23:48 +0000202 while (!WorkList.empty()) {
203 BasicBlock *BB = *WorkList.begin();
204 WorkList.erase(BB);
205 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
206
207 DeleteDeadBlock(BB);
208
209 for (SmallVectorImpl<BasicBlock*>::iterator
210 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
211 if (pred_begin(*II) == pred_end(*II))
212 WorkList.insert(*II);
213 }
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000214
Nadav Rotem3e883732012-08-14 05:19:07 +0000215 // Merge pairs of basic blocks with unconditional branches, connected by
216 // a single edge.
217 if (EverMadeChange || MadeChange)
218 MadeChange |= EliminateFallThrough(F);
219
Evan Cheng485fafc2011-03-21 01:19:09 +0000220 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000221 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000222 EverMadeChange |= MadeChange;
223 }
224
Devang Patel52e37df2011-03-24 15:35:25 +0000225 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000226 DT->DT->recalculate(F);
227
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000228 return EverMadeChange;
229}
230
Nadav Rotem3e883732012-08-14 05:19:07 +0000231/// EliminateFallThrough - Merge basic blocks which are connected
232/// by a single edge, where one of the basic blocks has a single successor
233/// pointing to the other basic block, which has a single predecessor.
234bool CodeGenPrepare::EliminateFallThrough(Function &F) {
235 bool Changed = false;
236 // Scan all of the blocks in the function, except for the entry block.
237 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
238 BasicBlock *BB = I++;
239 // If the destination block has a single pred, then this is a trivial
240 // edge, just collapse it.
241 BasicBlock *SinglePred = BB->getSinglePredecessor();
242
Evan Cheng46597072012-09-28 23:58:57 +0000243 // Don't merge if BB's address is taken.
244 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem3e883732012-08-14 05:19:07 +0000245
246 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
247 if (Term && !Term->isConditional()) {
248 Changed = true;
Michael Liao787ed032012-08-21 05:55:22 +0000249 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem3e883732012-08-14 05:19:07 +0000250 // Remember if SinglePred was the entry block of the function.
251 // If so, we will need to move BB back to the entry position.
252 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
253 MergeBasicBlockIntoOnlyPred(BB, this);
254
255 if (isEntry && BB != &BB->getParent()->getEntryBlock())
256 BB->moveBefore(&BB->getParent()->getEntryBlock());
257
258 // We have erased a block. Update the iterator.
259 I = BB;
Nadav Rotem3e883732012-08-14 05:19:07 +0000260 }
261 }
262 return Changed;
263}
264
Dale Johannesen2d697242009-03-27 01:13:37 +0000265/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
266/// debug info directives, and an unconditional branch. Passes before isel
267/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
268/// isel. Start by eliminating these blocks so we can split them the way we
269/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000270bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
271 bool MadeChange = false;
272 // Note that this intentionally skips the entry block.
273 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
274 BasicBlock *BB = I++;
275
276 // If this block doesn't end with an uncond branch, ignore it.
277 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
278 if (!BI || !BI->isUnconditional())
279 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000280
Dale Johannesen2d697242009-03-27 01:13:37 +0000281 // If the instruction before the branch (skipping debug info) isn't a phi
282 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000283 BasicBlock::iterator BBI = BI;
284 if (BBI != BB->begin()) {
285 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000286 while (isa<DbgInfoIntrinsic>(BBI)) {
287 if (BBI == BB->begin())
288 break;
289 --BBI;
290 }
291 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
292 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000293 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000294
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000295 // Do not break infinite loops.
296 BasicBlock *DestBB = BI->getSuccessor(0);
297 if (DestBB == BB)
298 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000299
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 if (!CanMergeBlocks(BB, DestBB))
301 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000302
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000303 EliminateMostlyEmptyBlock(BB);
304 MadeChange = true;
305 }
306 return MadeChange;
307}
308
309/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
310/// single uncond branch between them, and BB contains no other non-phi
311/// instructions.
312bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
313 const BasicBlock *DestBB) const {
314 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
315 // the successor. If there are more complex condition (e.g. preheaders),
316 // don't mess around with them.
317 BasicBlock::const_iterator BBI = BB->begin();
318 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000319 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000320 UI != E; ++UI) {
321 const Instruction *User = cast<Instruction>(*UI);
322 if (User->getParent() != DestBB || !isa<PHINode>(User))
323 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324 // If User is inside DestBB block and it is a PHINode then check
325 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000326 // a complex condition (e.g. preheaders) we want to avoid here.
327 if (User->getParent() == DestBB) {
328 if (const PHINode *UPN = dyn_cast<PHINode>(User))
329 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
330 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
331 if (Insn && Insn->getParent() == BB &&
332 Insn->getParent() != UPN->getIncomingBlock(I))
333 return false;
334 }
335 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000336 }
337 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000338
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000339 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
340 // and DestBB may have conflicting incoming values for the block. If so, we
341 // can't merge the block.
342 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
343 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000344
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000345 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000346 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000347 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
348 // It is faster to get preds from a PHI than with pred_iterator.
349 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
350 BBPreds.insert(BBPN->getIncomingBlock(i));
351 } else {
352 BBPreds.insert(pred_begin(BB), pred_end(BB));
353 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000354
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000355 // Walk the preds of DestBB.
356 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
357 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
358 if (BBPreds.count(Pred)) { // Common predecessor?
359 BBI = DestBB->begin();
360 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
361 const Value *V1 = PN->getIncomingValueForBlock(Pred);
362 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000363
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000364 // If V2 is a phi node in BB, look up what the mapped value will be.
365 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
366 if (V2PN->getParent() == BB)
367 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000368
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000369 // If there is a conflict, bail out.
370 if (V1 != V2) return false;
371 }
372 }
373 }
374
375 return true;
376}
377
378
379/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
380/// an unconditional branch in it.
381void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
382 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
383 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000384
David Greene68d67fd2010-01-05 01:27:11 +0000385 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000386
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000387 // If the destination block has a single pred, then this is a trivial edge,
388 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000389 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000390 if (SinglePred != DestBB) {
391 // Remember if SinglePred was the entry block of the function. If so, we
392 // will need to move BB back to the entry position.
393 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000394 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000395
Chris Lattnerf5102a02008-11-28 19:54:49 +0000396 if (isEntry && BB != &BB->getParent()->getEntryBlock())
397 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000398
David Greene68d67fd2010-01-05 01:27:11 +0000399 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000400 return;
401 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000402 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000403
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000404 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
405 // to handle the new incoming edges it is about to have.
406 PHINode *PN;
407 for (BasicBlock::iterator BBI = DestBB->begin();
408 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
409 // Remove the incoming value for BB, and remember it.
410 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000411
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000412 // Two options: either the InVal is a phi node defined in BB or it is some
413 // value that dominates BB.
414 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
415 if (InValPhi && InValPhi->getParent() == BB) {
416 // Add all of the input values of the input PHI as inputs of this phi.
417 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
418 PN->addIncoming(InValPhi->getIncomingValue(i),
419 InValPhi->getIncomingBlock(i));
420 } else {
421 // Otherwise, add one instance of the dominating value for each edge that
422 // we will be adding.
423 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
424 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
425 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
426 } else {
427 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
428 PN->addIncoming(InVal, *PI);
429 }
430 }
431 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000433 // The PHIs are now updated, change everything that refers to BB to use
434 // DestBB and remove BB.
435 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000436 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000437 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
438 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
439 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
440 DT->changeImmediateDominator(DestBB, NewIDom);
441 DT->eraseNode(BB);
442 }
Evan Cheng04149f72009-12-17 09:39:49 +0000443 if (PFI) {
444 PFI->replaceAllUses(BB, DestBB);
445 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000446 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000447 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000448 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
David Greene68d67fd2010-01-05 01:27:11 +0000450 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000451}
452
Chris Lattnerdd77df32007-04-13 20:30:56 +0000453/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000454/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
455/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000456/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000457///
458/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000459///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000460static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000461 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000462 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
463 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
Chris Lattnerdd77df32007-04-13 20:30:56 +0000465 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000466 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000467 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000468
Chris Lattnerdd77df32007-04-13 20:30:56 +0000469 // If this is an extension, it will be a zero or sign extension, which
470 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000471 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000472
Chris Lattnerdd77df32007-04-13 20:30:56 +0000473 // If these values will be promoted, find out what they will be promoted
474 // to. This helps us consider truncates on PPC as noop copies when they
475 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000476 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
477 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000478 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000479 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
480 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000481 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000482
Chris Lattnerdd77df32007-04-13 20:30:56 +0000483 // If, after promotion, these are the same types, this is a noop copy.
484 if (SrcVT != DstVT)
485 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000486
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000487 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000488
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000489 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000490 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000491
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000492 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000493 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000494 UI != E; ) {
495 Use &TheUse = UI.getUse();
496 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 // Figure out which BB this cast is used in. For PHI's this is the
499 // appropriate predecessor block.
500 BasicBlock *UserBB = User->getParent();
501 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000502 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 // Preincrement use iterator so we don't invalidate it.
506 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000508 // If this user is in the same block as the cast, don't change the cast.
509 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000510
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000511 // If we have already inserted a cast into this block, use it.
512 CastInst *&InsertedCast = InsertedCasts[UserBB];
513
514 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000515 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000516 InsertedCast =
517 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000518 InsertPt);
519 MadeChange = true;
520 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000523 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000524 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000525 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000526
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000527 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000528 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000529 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000530 MadeChange = true;
531 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000532
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000533 return MadeChange;
534}
535
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000537/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000538/// a clear win except on targets with multiple condition code registers
539/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000540///
541/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000542static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000543 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000544
Dale Johannesence0b2372007-06-12 16:50:17 +0000545 /// InsertedCmp - Only insert a cmp in each block once.
546 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000547
Dale Johannesence0b2372007-06-12 16:50:17 +0000548 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000549 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000550 UI != E; ) {
551 Use &TheUse = UI.getUse();
552 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000553
Dale Johannesence0b2372007-06-12 16:50:17 +0000554 // Preincrement use iterator so we don't invalidate it.
555 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000556
Dale Johannesence0b2372007-06-12 16:50:17 +0000557 // Don't bother for PHI nodes.
558 if (isa<PHINode>(User))
559 continue;
560
561 // Figure out which BB this cmp is used in.
562 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000563
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 // If this user is in the same block as the cmp, don't change the cmp.
565 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Dale Johannesence0b2372007-06-12 16:50:17 +0000567 // If we have already inserted a cmp into this block, use it.
568 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
569
570 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000571 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000572 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000573 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000574 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000575 CI->getOperand(1), "", InsertPt);
576 MadeChange = true;
577 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000578
Dale Johannesence0b2372007-06-12 16:50:17 +0000579 // Replace a use of the cmp with a use of the new cmp.
580 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000581 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000582 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000583
Dale Johannesence0b2372007-06-12 16:50:17 +0000584 // If we removed all uses, nuke the cmp.
585 if (CI->use_empty())
586 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000587
Dale Johannesence0b2372007-06-12 16:50:17 +0000588 return MadeChange;
589}
590
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000591namespace {
592class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
593protected:
594 void replaceCall(Value *With) {
595 CI->replaceAllUsesWith(With);
596 CI->eraseFromParent();
597 }
598 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000599 if (ConstantInt *SizeCI =
600 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
601 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000602 return false;
603 }
604};
605} // end anonymous namespace
606
Eric Christopher040056f2010-03-11 02:41:03 +0000607bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000608 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000609
Chris Lattner75796092011-01-15 07:14:54 +0000610 // Lower inline assembly if we can.
611 // If we found an inline asm expession, and if the target knows how to
612 // lower it to normal LLVM code, do so now.
613 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
614 if (TLI->ExpandInlineAsm(CI)) {
615 // Avoid invalidating the iterator.
616 CurInstIterator = BB->begin();
617 // Avoid processing instructions out of order, which could cause
618 // reuse before a value is defined.
619 SunkAddrs.clear();
620 return true;
621 }
622 // Sink address computing for memory operands into the block.
623 if (OptimizeInlineAsmInst(CI))
624 return true;
625 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000626
Eric Christopher040056f2010-03-11 02:41:03 +0000627 // Lower all uses of llvm.objectsize.*
628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
629 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000630 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000631 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000632 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
633
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000634 // Substituting this can cause recursive simplifications, which can
635 // invalidate our iterator. Use a WeakVH to hold onto it in case this
636 // happens.
637 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000638
Micah Villmow3574eca2012-10-08 16:38:25 +0000639 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
Chandler Carruth6b980542012-03-24 21:11:24 +0000640 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000641
642 // If the iterator instruction was recursively deleted, start over at the
643 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000644 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000645 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000646 SunkAddrs.clear();
647 }
Eric Christopher040056f2010-03-11 02:41:03 +0000648 return true;
649 }
650
Pete Cooperf210b682012-03-13 20:59:56 +0000651 if (II && TLI) {
652 SmallVector<Value*, 2> PtrOps;
653 Type *AccessTy;
654 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
655 while (!PtrOps.empty())
656 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
657 return true;
658 }
659
Eric Christopher040056f2010-03-11 02:41:03 +0000660 // From here on out we're working with named functions.
661 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000662
Micah Villmow3574eca2012-10-08 16:38:25 +0000663 // We'll need DataLayout from here on out.
664 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
Eric Christopher040056f2010-03-11 02:41:03 +0000665 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000666
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000667 // Lower all default uses of _chk calls. This is very similar
668 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000669 // that have the default "don't know" as the objectsize. Anything else
670 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000671 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000672 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000673}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000674
Evan Cheng485fafc2011-03-21 01:19:09 +0000675/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
676/// instructions to the predecessor to enable tail call optimizations. The
677/// case it is currently looking for is:
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/// br label %return
682/// bb1:
683/// %tmp1 = tail call i32 @f1()
684/// br label %return
685/// bb2:
686/// %tmp2 = tail call i32 @f2()
687/// br label %return
688/// return:
689/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
690/// ret i32 %retval
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000691/// @endcode
Evan Cheng485fafc2011-03-21 01:19:09 +0000692///
693/// =>
694///
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000695/// @code
Evan Cheng485fafc2011-03-21 01:19:09 +0000696/// bb0:
697/// %tmp0 = tail call i32 @f0()
698/// ret i32 %tmp0
699/// bb1:
700/// %tmp1 = tail call i32 @f1()
701/// ret i32 %tmp1
702/// bb2:
703/// %tmp2 = tail call i32 @f2()
704/// ret i32 %tmp2
Dmitri Gribenko2d9eb722012-09-13 12:34:29 +0000705/// @endcode
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000706bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000707 if (!TLI)
708 return false;
709
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +0000710 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
711 if (!RI)
712 return false;
713
Evan Cheng9c777a42012-07-27 21:21:26 +0000714 PHINode *PN = 0;
715 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000716 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000717 if (V) {
718 BCI = dyn_cast<BitCastInst>(V);
719 if (BCI)
720 V = BCI->getOperand(0);
721
722 PN = dyn_cast<PHINode>(V);
723 if (!PN)
724 return false;
725 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000726
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000727 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000728 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000729
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000730 // It's not safe to eliminate the sign / zero extension of the return value.
731 // See llvm::isInTailCallPosition().
732 const Function *F = BB->getParent();
Bill Wendling034b94b2012-12-19 07:18:57 +0000733 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
734 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
735 CallerRetAttr.hasAttribute(Attribute::SExt))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000736 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000737
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000738 // Make sure there are no instructions between the PHI and return, or that the
739 // return is the first instruction in the block.
740 if (PN) {
741 BasicBlock::iterator BI = BB->begin();
742 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000743 if (&*BI == BCI)
744 // Also skip over the bitcast.
745 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000746 if (&*BI != RI)
747 return false;
748 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000749 BasicBlock::iterator BI = BB->begin();
750 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
751 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000752 return false;
753 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000754
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000755 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
756 /// call.
757 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000758 if (PN) {
759 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
760 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
761 // Make sure the phi value is indeed produced by the tail call.
762 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
763 TLI->mayBeEmittedAsTailCall(CI))
764 TailCalls.push_back(CI);
765 }
766 } else {
767 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
768 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
769 if (!VisitedBBs.insert(*PI))
770 continue;
771
772 BasicBlock::InstListType &InstList = (*PI)->getInstList();
773 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
774 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000775 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
776 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000777 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000778
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000779 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000780 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000781 TailCalls.push_back(CI);
782 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000783 }
784
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000785 bool Changed = false;
786 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
787 CallInst *CI = TailCalls[i];
788 CallSite CS(CI);
789
790 // Conservatively require the attributes of the call to match those of the
791 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling034b94b2012-12-19 07:18:57 +0000792 Attribute CalleeRetAttr = CS.getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000793 if (AttrBuilder(CalleeRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000794 removeAttribute(Attribute::NoAlias) !=
Bill Wendling702cc912012-10-15 20:35:56 +0000795 AttrBuilder(CallerRetAttr).
Bill Wendling034b94b2012-12-19 07:18:57 +0000796 removeAttribute(Attribute::NoAlias))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000797 continue;
798
799 // Make sure the call instruction is followed by an unconditional branch to
800 // the return block.
801 BasicBlock *CallBB = CI->getParent();
802 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
803 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
804 continue;
805
806 // Duplicate the return into CallBB.
807 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000808 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000809 ++NumRetsDup;
810 }
811
812 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng46597072012-09-28 23:58:57 +0000813 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000814 BB->eraseFromParent();
815
816 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000817}
818
Chris Lattner88a5c832008-11-25 07:09:13 +0000819//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000820// Memory Optimization
821//===----------------------------------------------------------------------===//
822
Chris Lattnerdd77df32007-04-13 20:30:56 +0000823/// IsNonLocalValue - Return true if the specified values are defined in a
824/// different basic block than BB.
825static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
826 if (Instruction *I = dyn_cast<Instruction>(V))
827 return I->getParent() != BB;
828 return false;
829}
830
Bob Wilson4a8ee232009-12-03 21:47:07 +0000831/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000832/// addressing modes that can do significant amounts of computation. As such,
833/// instruction selection will try to get the load or store to do as much
834/// computation as possible for the program. The problem is that isel can only
835/// see within a single block. As such, we sink as much legal addressing mode
836/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000837///
838/// This method is used to optimize both load/store and inline asms with memory
839/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000840bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000841 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000842 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000843
844 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000845 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000846 SmallVector<Value*, 8> worklist;
847 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000848 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000849
Owen Anderson35bf4d62010-11-27 08:15:55 +0000850 // Use a worklist to iteratively look through PHI nodes, and ensure that
851 // the addressing mode obtained from the non-PHI roots of the graph
852 // are equivalent.
853 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000854 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000855 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000856 SmallVector<Instruction*, 16> AddrModeInsts;
857 ExtAddrMode AddrMode;
858 while (!worklist.empty()) {
859 Value *V = worklist.back();
860 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000861
Owen Anderson35bf4d62010-11-27 08:15:55 +0000862 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000863 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000864 Consensus = 0;
865 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000866 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000867
Owen Anderson35bf4d62010-11-27 08:15:55 +0000868 // For a PHI node, push all of its incoming values.
869 if (PHINode *P = dyn_cast<PHINode>(V)) {
870 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
871 worklist.push_back(P->getIncomingValue(i));
872 continue;
873 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000874
Owen Anderson35bf4d62010-11-27 08:15:55 +0000875 // For non-PHIs, determine the addressing mode being computed.
876 SmallVector<Instruction*, 16> NewAddrModeInsts;
877 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000878 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000879 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000880
881 // This check is broken into two cases with very similar code to avoid using
882 // getNumUses() as much as possible. Some values have a lot of uses, so
883 // calling getNumUses() unconditionally caused a significant compile-time
884 // regression.
885 if (!Consensus) {
886 Consensus = V;
887 AddrMode = NewAddrMode;
888 AddrModeInsts = NewAddrModeInsts;
889 continue;
890 } else if (NewAddrMode == AddrMode) {
891 if (!IsNumUsesConsensusValid) {
892 NumUsesConsensus = Consensus->getNumUses();
893 IsNumUsesConsensusValid = true;
894 }
895
896 // Ensure that the obtained addressing mode is equivalent to that obtained
897 // for all other roots of the PHI traversal. Also, when choosing one
898 // such root as representative, select the one with the most uses in order
899 // to keep the cost modeling heuristics in AddressingModeMatcher
900 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000901 unsigned NumUses = V->getNumUses();
902 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000903 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000904 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000905 AddrModeInsts = NewAddrModeInsts;
906 }
907 continue;
908 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000909
Owen Anderson35bf4d62010-11-27 08:15:55 +0000910 Consensus = 0;
911 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000912 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000913
Owen Anderson35bf4d62010-11-27 08:15:55 +0000914 // If the addressing mode couldn't be determined, or if multiple different
915 // ones were determined, bail out now.
916 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000917
Chris Lattnerdd77df32007-04-13 20:30:56 +0000918 // Check to see if any of the instructions supersumed by this addr mode are
919 // non-local to I's BB.
920 bool AnyNonLocal = false;
921 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000922 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000923 AnyNonLocal = true;
924 break;
925 }
926 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000927
Chris Lattnerdd77df32007-04-13 20:30:56 +0000928 // If all the instructions matched are already in this BB, don't do anything.
929 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000930 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000931 return false;
932 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000933
Chris Lattnerdd77df32007-04-13 20:30:56 +0000934 // Insert this computation right after this user. Since our caller is
935 // scanning from the top of the BB to the bottom, reuse of the expr are
936 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000937 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000938
Chris Lattnerdd77df32007-04-13 20:30:56 +0000939 // Now that we determined the addressing expression we want to use and know
940 // that we have to sink it into this block. Check to see if we have already
941 // done this for some other load/store instr in this block. If so, reuse the
942 // computation.
943 Value *&SunkAddr = SunkAddrs[Addr];
944 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000945 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000946 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000947 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000948 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000949 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000950 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000951 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000952 Type *IntPtrTy =
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000953 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000954
Chris Lattnerdd77df32007-04-13 20:30:56 +0000955 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000956
957 // Start with the base register. Do this first so that subsequent address
958 // matching finds it last, which will prevent it from trying to match it
959 // as the scaled value in case it happens to be a mul. That would be
960 // problematic if we've sunk a different mul for the scale, because then
961 // we'd end up sinking both muls.
962 if (AddrMode.BaseReg) {
963 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000964 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000965 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000966 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000967 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000968 Result = V;
969 }
970
971 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000972 if (AddrMode.Scale) {
973 Value *V = AddrMode.ScaledReg;
974 if (V->getType() == IntPtrTy) {
975 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000976 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000977 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000978 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
979 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000980 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000981 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000982 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000983 }
984 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000985 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
986 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000987 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000988 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000989 else
990 Result = V;
991 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000992
Chris Lattnerdd77df32007-04-13 20:30:56 +0000993 // Add in the BaseGV if present.
994 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000995 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000996 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000997 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000998 else
999 Result = V;
1000 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001001
Chris Lattnerdd77df32007-04-13 20:30:56 +00001002 // Add in the Base Offset if present.
1003 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001004 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +00001005 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +00001006 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001007 else
1008 Result = V;
1009 }
1010
1011 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +00001012 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +00001013 else
Devang Patel2048c372011-09-06 18:49:53 +00001014 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +00001015 }
Eric Christopher692bf6b2008-09-24 05:32:41 +00001016
Owen Andersond2f41742010-11-19 22:15:03 +00001017 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001018
Chris Lattner0403b472011-04-09 07:05:44 +00001019 // If we have no uses, recursively delete the value and all dead instructions
1020 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +00001021 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +00001022 // This can cause recursive deletion, which can invalidate our iterator.
1023 // Use a WeakVH to hold onto it in case this happens.
1024 WeakVH IterHandle(CurInstIterator);
1025 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001026
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +00001027 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattner0403b472011-04-09 07:05:44 +00001028
1029 if (IterHandle != CurInstIterator) {
1030 // If the iterator instruction was recursively deleted, start over at the
1031 // start of the block.
1032 CurInstIterator = BB->begin();
1033 SunkAddrs.clear();
1034 } else {
1035 // This address is now available for reassignment, so erase the table
1036 // entry; we don't want to match some completely different instruction.
1037 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001038 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001039 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001040 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001041 return true;
1042}
1043
Evan Cheng9bf12b52008-02-26 02:42:37 +00001044/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001045/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001046/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001047bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001048 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001049
Nadav Rotema94d6e82012-07-24 10:51:42 +00001050 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001051 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001052 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001053 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1054 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001055
Evan Cheng9bf12b52008-02-26 02:42:37 +00001056 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001057 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001058
Eli Friedman9ec80952008-02-26 18:37:49 +00001059 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1060 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001061 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001062 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001063 } else if (OpInfo.Type == InlineAsm::isInput)
1064 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001065 }
1066
1067 return MadeChange;
1068}
1069
Dan Gohmanb00f2362009-10-16 20:59:35 +00001070/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1071/// basic block as the load, unless conditions are unfavorable. This allows
1072/// SelectionDAG to fold the extend into the load.
1073///
1074bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1075 // Look for a load being extended.
1076 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1077 if (!LI) return false;
1078
1079 // If they're already in the same block, there's nothing to do.
1080 if (LI->getParent() == I->getParent())
1081 return false;
1082
1083 // If the load has other users and the truncate is not free, this probably
1084 // isn't worthwhile.
1085 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001086 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1087 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001088 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001089 return false;
1090
1091 // Check whether the target supports casts folded into loads.
1092 unsigned LType;
1093 if (isa<ZExtInst>(I))
1094 LType = ISD::ZEXTLOAD;
1095 else {
1096 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1097 LType = ISD::SEXTLOAD;
1098 }
Patrik Hagglund34525f92012-12-11 11:14:33 +00001099 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001100 return false;
1101
1102 // Move the extend into the same block as the load, so that SelectionDAG
1103 // can fold it.
1104 I->removeFromParent();
1105 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001106 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001107 return true;
1108}
1109
Evan Chengbdcb7262007-12-05 23:58:20 +00001110bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1111 BasicBlock *DefBB = I->getParent();
1112
Bob Wilson9120f5c2010-09-21 21:44:14 +00001113 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001114 // other uses of the source with result of extension.
1115 Value *Src = I->getOperand(0);
1116 if (Src->hasOneUse())
1117 return false;
1118
Evan Cheng696e5c02007-12-13 07:50:36 +00001119 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001120 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001121 return false;
1122
Evan Cheng772de512007-12-12 00:51:06 +00001123 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001124 // this block.
1125 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001126 return false;
1127
Evan Chengbdcb7262007-12-05 23:58:20 +00001128 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001129 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001130 UI != E; ++UI) {
1131 Instruction *User = cast<Instruction>(*UI);
1132
1133 // Figure out which BB this ext is used in.
1134 BasicBlock *UserBB = User->getParent();
1135 if (UserBB == DefBB) continue;
1136 DefIsLiveOut = true;
1137 break;
1138 }
1139 if (!DefIsLiveOut)
1140 return false;
1141
Evan Cheng765dff22007-12-12 02:53:41 +00001142 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001143 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001144 UI != E; ++UI) {
1145 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001146 BasicBlock *UserBB = User->getParent();
1147 if (UserBB == DefBB) continue;
1148 // Be conservative. We don't want this xform to end up introducing
1149 // reloads just before load / store instructions.
1150 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001151 return false;
1152 }
1153
Evan Chengbdcb7262007-12-05 23:58:20 +00001154 // InsertedTruncs - Only insert one trunc in each block once.
1155 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1156
1157 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001158 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001159 UI != E; ++UI) {
1160 Use &TheUse = UI.getUse();
1161 Instruction *User = cast<Instruction>(*UI);
1162
1163 // Figure out which BB this ext is used in.
1164 BasicBlock *UserBB = User->getParent();
1165 if (UserBB == DefBB) continue;
1166
1167 // Both src and def are live in this block. Rewrite the use.
1168 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1169
1170 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001171 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001172 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1173 }
1174
1175 // Replace a use of the {s|z}ext source with a use of the result.
1176 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001177 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001178 MadeChange = true;
1179 }
1180
1181 return MadeChange;
1182}
1183
Benjamin Kramer59957502012-05-05 12:49:22 +00001184/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1185/// turned into an explicit branch.
1186static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1187 // FIXME: This should use the same heuristics as IfConversion to determine
1188 // whether a select is better represented as a branch. This requires that
1189 // branch probability metadata is preserved for the select, which is not the
1190 // case currently.
1191
1192 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1193
1194 // If the branch is predicted right, an out of order CPU can avoid blocking on
1195 // the compare. Emit cmovs on compares with a memory operand as branches to
1196 // avoid stalls on the load from memory. If the compare has more than one use
1197 // there's probably another cmov or setcc around so it's not worth emitting a
1198 // branch.
1199 if (!Cmp)
1200 return false;
1201
1202 Value *CmpOp0 = Cmp->getOperand(0);
1203 Value *CmpOp1 = Cmp->getOperand(1);
1204
1205 // We check that the memory operand has one use to avoid uses of the loaded
1206 // value directly after the compare, making branches unprofitable.
1207 return Cmp->hasOneUse() &&
1208 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1209 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1210}
1211
1212
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001213/// If we have a SelectInst that will likely profit from branch prediction,
1214/// turn it into a branch.
Benjamin Kramer59957502012-05-05 12:49:22 +00001215bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001216 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1217
1218 // Can we convert the 'select' to CF ?
1219 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer59957502012-05-05 12:49:22 +00001220 return false;
1221
Nadav Rotem9f40cb32012-09-02 12:10:19 +00001222 TargetLowering::SelectSupportKind SelectKind;
1223 if (VectorCond)
1224 SelectKind = TargetLowering::VectorMaskSelect;
1225 else if (SI->getType()->isVectorTy())
1226 SelectKind = TargetLowering::ScalarCondVectorVal;
1227 else
1228 SelectKind = TargetLowering::ScalarValSelect;
1229
1230 // Do we have efficient codegen support for this kind of 'selects' ?
1231 if (TLI->isSelectSupported(SelectKind)) {
1232 // We have efficient codegen support for the select instruction.
1233 // Check if it is profitable to keep this 'select'.
1234 if (!TLI->isPredictableSelectExpensive() ||
1235 !isFormingBranchFromSelectProfitable(SI))
1236 return false;
1237 }
Benjamin Kramer59957502012-05-05 12:49:22 +00001238
1239 ModifiedDT = true;
1240
1241 // First, we split the block containing the select into 2 blocks.
1242 BasicBlock *StartBlock = SI->getParent();
1243 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1244 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1245
1246 // Create a new block serving as the landing pad for the branch.
1247 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1248 NextBlock->getParent(), NextBlock);
1249
1250 // Move the unconditional branch from the block with the select in it into our
1251 // landing pad block.
1252 StartBlock->getTerminator()->eraseFromParent();
1253 BranchInst::Create(NextBlock, SmallBlock);
1254
1255 // Insert the real conditional branch based on the original condition.
1256 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1257
1258 // The select itself is replaced with a PHI Node.
1259 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1260 PN->takeName(SI);
1261 PN->addIncoming(SI->getTrueValue(), StartBlock);
1262 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1263 SI->replaceAllUsesWith(PN);
1264 SI->eraseFromParent();
1265
1266 // Instruct OptimizeBlock to skip to the next block.
1267 CurInstIterator = StartBlock->end();
1268 ++NumSelectsExpanded;
1269 return true;
1270}
1271
Cameron Zwarichc0611012011-01-06 02:37:26 +00001272bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001273 if (PHINode *P = dyn_cast<PHINode>(I)) {
1274 // It is possible for very late stage optimizations (such as SimplifyCFG)
1275 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1276 // trivial PHI, go ahead and zap it here.
1277 if (Value *V = SimplifyInstruction(P)) {
1278 P->replaceAllUsesWith(V);
1279 P->eraseFromParent();
1280 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001281 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001282 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001283 return false;
1284 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001285
Chris Lattner1a8943a2011-01-15 07:29:01 +00001286 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001287 // If the source of the cast is a constant, then this should have
1288 // already been constant folded. The only reason NOT to constant fold
1289 // it is if something (e.g. LSR) was careful to place the constant
1290 // evaluation in a block other than then one that uses it (e.g. to hoist
1291 // the address of globals out of a loop). If this is the case, we don't
1292 // want to forward-subst the cast.
1293 if (isa<Constant>(CI->getOperand(0)))
1294 return false;
1295
Chris Lattner1a8943a2011-01-15 07:29:01 +00001296 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1297 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001298
Chris Lattner1a8943a2011-01-15 07:29:01 +00001299 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1300 bool MadeChange = MoveExtToFormExtLoad(I);
1301 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001302 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001303 return false;
1304 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001305
Chris Lattner1a8943a2011-01-15 07:29:01 +00001306 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1307 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001308
Chris Lattner1a8943a2011-01-15 07:29:01 +00001309 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001310 if (TLI)
Hans Wennborg04d7d132012-10-30 11:23:25 +00001311 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1312 return false;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001313 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001314
Chris Lattner1a8943a2011-01-15 07:29:01 +00001315 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001316 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001317 return OptimizeMemoryInst(I, SI->getOperand(1),
1318 SI->getOperand(0)->getType());
1319 return false;
1320 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001321
Chris Lattner1a8943a2011-01-15 07:29:01 +00001322 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001323 if (GEPI->hasAllZeroIndices()) {
1324 /// The GEP operand must be a pointer, so must its result -> BitCast
1325 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1326 GEPI->getName(), GEPI);
1327 GEPI->replaceAllUsesWith(NC);
1328 GEPI->eraseFromParent();
1329 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001330 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001331 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001332 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001333 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001334 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001335
Chris Lattner1a8943a2011-01-15 07:29:01 +00001336 if (CallInst *CI = dyn_cast<CallInst>(I))
1337 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001338
Benjamin Kramer59957502012-05-05 12:49:22 +00001339 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1340 return OptimizeSelectInst(SI);
1341
Chris Lattner1a8943a2011-01-15 07:29:01 +00001342 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001343}
1344
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001345// In this pass we look for GEP and cast instructions that are used
1346// across basic blocks and rewrite them to improve basic-block-at-a-time
1347// selection.
1348bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001349 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001350 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001351
Chris Lattner75796092011-01-15 07:14:54 +00001352 CurInstIterator = BB.begin();
Hans Wennborg93ba1332012-09-19 07:48:16 +00001353 while (CurInstIterator != BB.end())
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001354 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001355
Benjamin Kramer4ccb49a2012-11-23 19:17:06 +00001356 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1357
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001358 return MadeChange;
1359}
Devang Patelf56ea612011-08-18 00:50:51 +00001360
1361// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001362// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001363// find a node corresponding to the value.
1364bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1365 bool MadeChange = false;
1366 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1367 Instruction *PrevNonDbgInst = NULL;
1368 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1369 Instruction *Insn = BI; ++BI;
1370 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1371 if (!DVI) {
1372 PrevNonDbgInst = Insn;
1373 continue;
1374 }
1375
1376 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1377 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1378 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1379 DVI->removeFromParent();
1380 if (isa<PHINode>(VI))
1381 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1382 else
1383 DVI->insertAfter(VI);
1384 MadeChange = true;
1385 ++NumDbgValueMoved;
1386 }
1387 }
1388 }
1389 return MadeChange;
1390}