blob: bc87106b3d21652a34973d9d14c18c9a7c2f5c5f [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"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000047using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000048using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000049
Cameron Zwarich31ff1332011-01-05 17:27:27 +000050STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng485fafc2011-03-21 01:19:09 +000051STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarich31ff1332011-01-05 17:27:27 +000053STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 "sunken Cmps");
55STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 "of sunken Casts");
57STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
Evan Cheng485fafc2011-03-21 01:19:09 +000059STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patelf56ea612011-08-18 00:50:51 +000062STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer59957502012-05-05 12:49:22 +000063STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Jakob Stoklund Olesen7eb589d2010-09-30 20:51:52 +000064
Cameron Zwarich899eaa32011-03-11 21:52:04 +000065static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
Bill Wendlinge3e394d2012-03-04 10:46:01 +000069// FIXME: Remove this abomination once all of the tests pass without it!
70static cl::opt<bool> DisableDeleteDeadBlocks(
71 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
73
Benjamin Kramer77c4ef82012-05-06 14:25:16 +000074static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
Benjamin Kramer59957502012-05-05 12:49:22 +000077
Eric Christopher692bf6b2008-09-24 05:32:41 +000078namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000079 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000080 /// TLI - Keep a pointer of a TargetLowering to consult for determining
81 /// transformation profitability.
82 const TargetLowering *TLI;
Chad Rosier618c1db2011-12-01 03:08:23 +000083 const TargetLibraryInfo *TLInfo;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000084 DominatorTree *DT;
Evan Cheng04149f72009-12-17 09:39:49 +000085 ProfileInfo *PFI;
Nadav Rotema94d6e82012-07-24 10:51:42 +000086
Chris Lattner75796092011-01-15 07:14:54 +000087 /// CurInstIterator - As we scan instructions optimizing them, this is the
88 /// next instruction to optimize. Xforms that can invalidate this should
89 /// update it.
90 BasicBlock::iterator CurInstIterator;
Evan Chengab631522008-12-19 18:03:11 +000091
Evan Cheng485fafc2011-03-21 01:19:09 +000092 /// Keeps track of non-local addresses that have been sunk into a block.
93 /// This allows us to avoid inserting duplicate code for blocks with
94 /// multiple load/stores of the same address.
Cameron Zwarich8c3527e2011-01-06 00:42:50 +000095 DenseMap<Value*, Value*> SunkAddrs;
96
Devang Patel52e37df2011-03-24 15:35:25 +000097 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng485fafc2011-03-21 01:19:09 +000098 /// be updated.
Devang Patel52e37df2011-03-24 15:35:25 +000099 bool ModifiedDT;
Evan Cheng485fafc2011-03-21 01:19:09 +0000100
Benjamin Kramer59957502012-05-05 12:49:22 +0000101 /// OptSize - True if optimizing for size.
102 bool OptSize;
103
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000104 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000105 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +0000106 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson081c34b2010-10-19 17:21:58 +0000107 : FunctionPass(ID), TLI(tli) {
108 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
109 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000110 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000111
Andreas Neustifterad809812009-09-16 09:26:52 +0000112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000113 AU.addPreserved<DominatorTree>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000114 AU.addPreserved<ProfileInfo>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000115 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterad809812009-09-16 09:26:52 +0000116 }
117
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000118 private:
Nadav Rotem3e883732012-08-14 05:19:07 +0000119 bool EliminateFallThrough(Function &F);
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000120 bool EliminateMostlyEmptyBlocks(Function &F);
121 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
122 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000123 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarichc0611012011-01-06 02:37:26 +0000124 bool OptimizeInst(Instruction *I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000125 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner75796092011-01-15 07:14:54 +0000126 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher040056f2010-03-11 02:41:03 +0000127 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000128 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000129 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer59957502012-05-05 12:49:22 +0000130 bool OptimizeSelectInst(SelectInst *SI);
Evan Cheng485fafc2011-03-21 01:19:09 +0000131 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
Devang Patelf56ea612011-08-18 00:50:51 +0000132 bool PlaceDbgValues(Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000133 };
134}
Devang Patel794fd752007-05-01 21:15:47 +0000135
Devang Patel19974732007-05-03 01:11:54 +0000136char CodeGenPrepare::ID = 0;
Chad Rosier618c1db2011-12-01 03:08:23 +0000137INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
138 "Optimize for code generation", false, false)
139INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
140INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
Owen Andersonce665bd2010-10-07 22:25:06 +0000141 "Optimize for code generation", false, false)
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000142
143FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
144 return new CodeGenPrepare(TLI);
145}
146
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000147bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000148 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000149
Devang Patel52e37df2011-03-24 15:35:25 +0000150 ModifiedDT = false;
Chad Rosier618c1db2011-12-01 03:08:23 +0000151 TLInfo = &getAnalysis<TargetLibraryInfo>();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000152 DT = getAnalysisIfAvailable<DominatorTree>();
Evan Cheng04149f72009-12-17 09:39:49 +0000153 PFI = getAnalysisIfAvailable<ProfileInfo>();
Benjamin Kramer59957502012-05-05 12:49:22 +0000154 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
Evan Cheng485fafc2011-03-21 01:19:09 +0000155
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000156 // First pass, eliminate blocks that contain only PHI nodes and an
157 // unconditional branch.
158 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000159
Devang Patelf56ea612011-08-18 00:50:51 +0000160 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +0000161 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +0000162 // find a node corresponding to the value.
163 EverMadeChange |= PlaceDbgValues(F);
164
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000165 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000166 while (MadeChange) {
167 MadeChange = false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000168 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
169 BasicBlock *BB = I++;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000170 MadeChange |= OptimizeBlock(*BB);
Evan Cheng485fafc2011-03-21 01:19:09 +0000171 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000172 EverMadeChange |= MadeChange;
173 }
Cameron Zwarich8c3527e2011-01-06 00:42:50 +0000174
175 SunkAddrs.clear();
176
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000177 if (!DisableBranchOpts) {
178 MadeChange = false;
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000179 SmallPtrSet<BasicBlock*, 8> WorkList;
180 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
181 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommel5649ba72011-05-22 16:24:18 +0000182 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendlinge3e394d2012-03-04 10:46:01 +0000183 if (!MadeChange) continue;
184
185 for (SmallVectorImpl<BasicBlock*>::iterator
186 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
187 if (pred_begin(*II) == pred_end(*II))
188 WorkList.insert(*II);
189 }
190
191 if (!DisableDeleteDeadBlocks)
192 for (SmallPtrSet<BasicBlock*, 8>::iterator
193 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
194 DeleteDeadBlock(*I);
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000195
Nadav Rotem3e883732012-08-14 05:19:07 +0000196 // Merge pairs of basic blocks with unconditional branches, connected by
197 // a single edge.
198 if (EverMadeChange || MadeChange)
199 MadeChange |= EliminateFallThrough(F);
200
Evan Cheng485fafc2011-03-21 01:19:09 +0000201 if (MadeChange)
Devang Patel52e37df2011-03-24 15:35:25 +0000202 ModifiedDT = true;
Cameron Zwarich899eaa32011-03-11 21:52:04 +0000203 EverMadeChange |= MadeChange;
204 }
205
Devang Patel52e37df2011-03-24 15:35:25 +0000206 if (ModifiedDT && DT)
Evan Cheng485fafc2011-03-21 01:19:09 +0000207 DT->DT->recalculate(F);
208
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000209 return EverMadeChange;
210}
211
Nadav Rotem3e883732012-08-14 05:19:07 +0000212/// EliminateFallThrough - Merge basic blocks which are connected
213/// by a single edge, where one of the basic blocks has a single successor
214/// pointing to the other basic block, which has a single predecessor.
215bool CodeGenPrepare::EliminateFallThrough(Function &F) {
216 bool Changed = false;
217 // Scan all of the blocks in the function, except for the entry block.
218 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
219 BasicBlock *BB = I++;
220 // If the destination block has a single pred, then this is a trivial
221 // edge, just collapse it.
222 BasicBlock *SinglePred = BB->getSinglePredecessor();
223
224 if (!SinglePred || SinglePred == BB) continue;
225
226 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
227 if (Term && !Term->isConditional()) {
228 Changed = true;
229 // Remember if SinglePred was the entry block of the function.
230 // If so, we will need to move BB back to the entry position.
231 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
232 MergeBasicBlockIntoOnlyPred(BB, this);
233
234 if (isEntry && BB != &BB->getParent()->getEntryBlock())
235 BB->moveBefore(&BB->getParent()->getEntryBlock());
236
237 // We have erased a block. Update the iterator.
238 I = BB;
239 DEBUG(dbgs() << "Merged:\n"<< *SinglePred << "\n\n\n");
240 }
241 }
242 return Changed;
243}
244
Dale Johannesen2d697242009-03-27 01:13:37 +0000245/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
246/// debug info directives, and an unconditional branch. Passes before isel
247/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
248/// isel. Start by eliminating these blocks so we can split them the way we
249/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000250bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
251 bool MadeChange = false;
252 // Note that this intentionally skips the entry block.
253 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
254 BasicBlock *BB = I++;
255
256 // If this block doesn't end with an uncond branch, ignore it.
257 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
258 if (!BI || !BI->isUnconditional())
259 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Dale Johannesen2d697242009-03-27 01:13:37 +0000261 // If the instruction before the branch (skipping debug info) isn't a phi
262 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000263 BasicBlock::iterator BBI = BI;
264 if (BBI != BB->begin()) {
265 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000266 while (isa<DbgInfoIntrinsic>(BBI)) {
267 if (BBI == BB->begin())
268 break;
269 --BBI;
270 }
271 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
272 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000273 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000274
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000275 // Do not break infinite loops.
276 BasicBlock *DestBB = BI->getSuccessor(0);
277 if (DestBB == BB)
278 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000279
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000280 if (!CanMergeBlocks(BB, DestBB))
281 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000282
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000283 EliminateMostlyEmptyBlock(BB);
284 MadeChange = true;
285 }
286 return MadeChange;
287}
288
289/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
290/// single uncond branch between them, and BB contains no other non-phi
291/// instructions.
292bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
293 const BasicBlock *DestBB) const {
294 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
295 // the successor. If there are more complex condition (e.g. preheaders),
296 // don't mess around with them.
297 BasicBlock::const_iterator BBI = BB->begin();
298 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000299 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000300 UI != E; ++UI) {
301 const Instruction *User = cast<Instruction>(*UI);
302 if (User->getParent() != DestBB || !isa<PHINode>(User))
303 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304 // If User is inside DestBB block and it is a PHINode then check
305 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000306 // a complex condition (e.g. preheaders) we want to avoid here.
307 if (User->getParent() == DestBB) {
308 if (const PHINode *UPN = dyn_cast<PHINode>(User))
309 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
310 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
311 if (Insn && Insn->getParent() == BB &&
312 Insn->getParent() != UPN->getIncomingBlock(I))
313 return false;
314 }
315 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000316 }
317 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000318
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000319 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
320 // and DestBB may have conflicting incoming values for the block. If so, we
321 // can't merge the block.
322 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
323 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000324
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000325 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000326 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000327 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
328 // It is faster to get preds from a PHI than with pred_iterator.
329 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
330 BBPreds.insert(BBPN->getIncomingBlock(i));
331 } else {
332 BBPreds.insert(pred_begin(BB), pred_end(BB));
333 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000334
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000335 // Walk the preds of DestBB.
336 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
337 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
338 if (BBPreds.count(Pred)) { // Common predecessor?
339 BBI = DestBB->begin();
340 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
341 const Value *V1 = PN->getIncomingValueForBlock(Pred);
342 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000343
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000344 // If V2 is a phi node in BB, look up what the mapped value will be.
345 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
346 if (V2PN->getParent() == BB)
347 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000348
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000349 // If there is a conflict, bail out.
350 if (V1 != V2) return false;
351 }
352 }
353 }
354
355 return true;
356}
357
358
359/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
360/// an unconditional branch in it.
361void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
362 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
363 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000364
David Greene68d67fd2010-01-05 01:27:11 +0000365 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000366
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000367 // If the destination block has a single pred, then this is a trivial edge,
368 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000369 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000370 if (SinglePred != DestBB) {
371 // Remember if SinglePred was the entry block of the function. If so, we
372 // will need to move BB back to the entry position.
373 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000374 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000375
Chris Lattnerf5102a02008-11-28 19:54:49 +0000376 if (isEntry && BB != &BB->getParent()->getEntryBlock())
377 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000378
David Greene68d67fd2010-01-05 01:27:11 +0000379 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000380 return;
381 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000382 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000383
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000384 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
385 // to handle the new incoming edges it is about to have.
386 PHINode *PN;
387 for (BasicBlock::iterator BBI = DestBB->begin();
388 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
389 // Remove the incoming value for BB, and remember it.
390 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000391
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000392 // Two options: either the InVal is a phi node defined in BB or it is some
393 // value that dominates BB.
394 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
395 if (InValPhi && InValPhi->getParent() == BB) {
396 // Add all of the input values of the input PHI as inputs of this phi.
397 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
398 PN->addIncoming(InValPhi->getIncomingValue(i),
399 InValPhi->getIncomingBlock(i));
400 } else {
401 // Otherwise, add one instance of the dominating value for each edge that
402 // we will be adding.
403 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
404 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
405 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
406 } else {
407 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
408 PN->addIncoming(InVal, *PI);
409 }
410 }
411 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000412
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000413 // The PHIs are now updated, change everything that refers to BB to use
414 // DestBB and remove BB.
415 BB->replaceAllUsesWith(DestBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000416 if (DT && !ModifiedDT) {
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000417 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
418 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
419 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
420 DT->changeImmediateDominator(DestBB, NewIDom);
421 DT->eraseNode(BB);
422 }
Evan Cheng04149f72009-12-17 09:39:49 +0000423 if (PFI) {
424 PFI->replaceAllUses(BB, DestBB);
425 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000426 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000427 BB->eraseFromParent();
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000428 ++NumBlocksElim;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000429
David Greene68d67fd2010-01-05 01:27:11 +0000430 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000431}
432
Chris Lattnerdd77df32007-04-13 20:30:56 +0000433/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000434/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
435/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000436/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000437///
438/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000439///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000440static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000442 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
443 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdd77df32007-04-13 20:30:56 +0000445 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000446 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000447 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000448
Chris Lattnerdd77df32007-04-13 20:30:56 +0000449 // If this is an extension, it will be a zero or sign extension, which
450 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000451 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Chris Lattnerdd77df32007-04-13 20:30:56 +0000453 // If these values will be promoted, find out what they will be promoted
454 // to. This helps us consider truncates on PPC as noop copies when they
455 // are.
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000456 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
457 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000458 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Nadav Rotem0ccc12a2011-05-29 08:10:47 +0000459 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
460 TargetLowering::TypePromoteInteger)
Owen Anderson23b9b192009-08-12 00:36:31 +0000461 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdd77df32007-04-13 20:30:56 +0000463 // If, after promotion, these are the same types, this is a noop copy.
464 if (SrcVT != DstVT)
465 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000466
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000467 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000470 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000471
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000473 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000474 UI != E; ) {
475 Use &TheUse = UI.getUse();
476 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000477
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000478 // Figure out which BB this cast is used in. For PHI's this is the
479 // appropriate predecessor block.
480 BasicBlock *UserBB = User->getParent();
481 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000482 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000483 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // Preincrement use iterator so we don't invalidate it.
486 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000487
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000488 // If this user is in the same block as the cast, don't change the cast.
489 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 // If we have already inserted a cast into this block, use it.
492 CastInst *&InsertedCast = InsertedCasts[UserBB];
493
494 if (!InsertedCast) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000495 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000496 InsertedCast =
497 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000498 InsertPt);
499 MadeChange = true;
500 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501
Dale Johannesence0b2372007-06-12 16:50:17 +0000502 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000503 TheUse = InsertedCast;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000504 ++NumCastUses;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000505 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000506
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000507 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000508 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000509 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000510 MadeChange = true;
511 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000512
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000513 return MadeChange;
514}
515
Eric Christopher692bf6b2008-09-24 05:32:41 +0000516/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000517/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000518/// a clear win except on targets with multiple condition code registers
519/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000520///
521/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000522static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 /// InsertedCmp - Only insert a cmp in each block once.
526 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000527
Dale Johannesence0b2372007-06-12 16:50:17 +0000528 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000529 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000530 UI != E; ) {
531 Use &TheUse = UI.getUse();
532 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000533
Dale Johannesence0b2372007-06-12 16:50:17 +0000534 // Preincrement use iterator so we don't invalidate it.
535 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000536
Dale Johannesence0b2372007-06-12 16:50:17 +0000537 // Don't bother for PHI nodes.
538 if (isa<PHINode>(User))
539 continue;
540
541 // Figure out which BB this cmp is used in.
542 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000543
Dale Johannesence0b2372007-06-12 16:50:17 +0000544 // If this user is in the same block as the cmp, don't change the cmp.
545 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000546
Dale Johannesence0b2372007-06-12 16:50:17 +0000547 // If we have already inserted a cmp into this block, use it.
548 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
549
550 if (!InsertedCmp) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +0000551 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000552 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000553 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000554 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000555 CI->getOperand(1), "", InsertPt);
556 MadeChange = true;
557 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000558
Dale Johannesence0b2372007-06-12 16:50:17 +0000559 // Replace a use of the cmp with a use of the new cmp.
560 TheUse = InsertedCmp;
Cameron Zwarich31ff1332011-01-05 17:27:27 +0000561 ++NumCmpUses;
Dale Johannesence0b2372007-06-12 16:50:17 +0000562 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000563
Dale Johannesence0b2372007-06-12 16:50:17 +0000564 // If we removed all uses, nuke the cmp.
565 if (CI->use_empty())
566 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000567
Dale Johannesence0b2372007-06-12 16:50:17 +0000568 return MadeChange;
569}
570
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000571namespace {
572class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
573protected:
574 void replaceCall(Value *With) {
575 CI->replaceAllUsesWith(With);
576 CI->eraseFromParent();
577 }
578 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000579 if (ConstantInt *SizeCI =
580 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
581 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000582 return false;
583 }
584};
585} // end anonymous namespace
586
Eric Christopher040056f2010-03-11 02:41:03 +0000587bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner75796092011-01-15 07:14:54 +0000588 BasicBlock *BB = CI->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000589
Chris Lattner75796092011-01-15 07:14:54 +0000590 // Lower inline assembly if we can.
591 // If we found an inline asm expession, and if the target knows how to
592 // lower it to normal LLVM code, do so now.
593 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
594 if (TLI->ExpandInlineAsm(CI)) {
595 // Avoid invalidating the iterator.
596 CurInstIterator = BB->begin();
597 // Avoid processing instructions out of order, which could cause
598 // reuse before a value is defined.
599 SunkAddrs.clear();
600 return true;
601 }
602 // Sink address computing for memory operands into the block.
603 if (OptimizeInlineAsmInst(CI))
604 return true;
605 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000606
Eric Christopher040056f2010-03-11 02:41:03 +0000607 // Lower all uses of llvm.objectsize.*
608 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
609 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000610 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000611 Type *ReturnTy = CI->getType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000612 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
613
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000614 // Substituting this can cause recursive simplifications, which can
615 // invalidate our iterator. Use a WeakVH to hold onto it in case this
616 // happens.
617 WeakVH IterHandle(CurInstIterator);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000618
Chandler Carruth6b980542012-03-24 21:11:24 +0000619 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
620 TLInfo, ModifiedDT ? 0 : DT);
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000621
622 // If the iterator instruction was recursively deleted, start over at the
623 // start of the block.
Chris Lattner435b4d22011-01-18 20:53:04 +0000624 if (IterHandle != CurInstIterator) {
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000625 CurInstIterator = BB->begin();
Chris Lattner435b4d22011-01-18 20:53:04 +0000626 SunkAddrs.clear();
627 }
Eric Christopher040056f2010-03-11 02:41:03 +0000628 return true;
629 }
630
Pete Cooperf210b682012-03-13 20:59:56 +0000631 if (II && TLI) {
632 SmallVector<Value*, 2> PtrOps;
633 Type *AccessTy;
634 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
635 while (!PtrOps.empty())
636 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
637 return true;
638 }
639
Eric Christopher040056f2010-03-11 02:41:03 +0000640 // From here on out we're working with named functions.
641 if (CI->getCalledFunction() == 0) return false;
Devang Patel97de92c2011-05-26 21:51:06 +0000642
Eric Christopher040056f2010-03-11 02:41:03 +0000643 // We'll need TargetData from here on out.
644 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
645 if (!TD) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000646
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000647 // Lower all default uses of _chk calls. This is very similar
648 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000649 // that have the default "don't know" as the objectsize. Anything else
650 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000651 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes51004df2012-07-25 16:46:31 +0000652 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher040056f2010-03-11 02:41:03 +0000653}
Chris Lattner94e8e0c2011-01-15 07:25:29 +0000654
Evan Cheng485fafc2011-03-21 01:19:09 +0000655/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
656/// instructions to the predecessor to enable tail call optimizations. The
657/// case it is currently looking for is:
658/// bb0:
659/// %tmp0 = tail call i32 @f0()
660/// br label %return
661/// bb1:
662/// %tmp1 = tail call i32 @f1()
663/// br label %return
664/// bb2:
665/// %tmp2 = tail call i32 @f2()
666/// br label %return
667/// return:
668/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
669/// ret i32 %retval
670///
671/// =>
672///
673/// bb0:
674/// %tmp0 = tail call i32 @f0()
675/// ret i32 %tmp0
676/// bb1:
677/// %tmp1 = tail call i32 @f1()
678/// ret i32 %tmp1
679/// bb2:
680/// %tmp2 = tail call i32 @f2()
681/// ret i32 %tmp2
682///
683bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
Cameron Zwarich661a3902011-03-24 04:51:51 +0000684 if (!TLI)
685 return false;
686
Evan Cheng9c777a42012-07-27 21:21:26 +0000687 PHINode *PN = 0;
688 BitCastInst *BCI = 0;
Evan Cheng485fafc2011-03-21 01:19:09 +0000689 Value *V = RI->getReturnValue();
Evan Cheng9c777a42012-07-27 21:21:26 +0000690 if (V) {
691 BCI = dyn_cast<BitCastInst>(V);
692 if (BCI)
693 V = BCI->getOperand(0);
694
695 PN = dyn_cast<PHINode>(V);
696 if (!PN)
697 return false;
698 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000699
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000700 BasicBlock *BB = RI->getParent();
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000701 if (PN && PN->getParent() != BB)
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000702 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000703
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000704 // It's not safe to eliminate the sign / zero extension of the return value.
705 // See llvm::isInTailCallPosition().
706 const Function *F = BB->getParent();
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000707 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000708 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
709 return false;
Evan Cheng485fafc2011-03-21 01:19:09 +0000710
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000711 // Make sure there are no instructions between the PHI and return, or that the
712 // return is the first instruction in the block.
713 if (PN) {
714 BasicBlock::iterator BI = BB->begin();
715 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng9c777a42012-07-27 21:21:26 +0000716 if (&*BI == BCI)
717 // Also skip over the bitcast.
718 ++BI;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000719 if (&*BI != RI)
720 return false;
721 } else {
Cameron Zwarich90354842011-03-24 16:34:59 +0000722 BasicBlock::iterator BI = BB->begin();
723 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
724 if (&*BI != RI)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000725 return false;
726 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000727
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000728 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
729 /// call.
730 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000731 if (PN) {
732 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
733 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
734 // Make sure the phi value is indeed produced by the tail call.
735 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
736 TLI->mayBeEmittedAsTailCall(CI))
737 TailCalls.push_back(CI);
738 }
739 } else {
740 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
741 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
742 if (!VisitedBBs.insert(*PI))
743 continue;
744
745 BasicBlock::InstListType &InstList = (*PI)->getInstList();
746 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
747 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich90354842011-03-24 16:34:59 +0000748 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
749 if (RI == RE)
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000750 continue;
Cameron Zwarich90354842011-03-24 16:34:59 +0000751
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000752 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarichdc31cfe2011-03-24 15:54:11 +0000753 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich6e8ffc12011-03-24 04:52:10 +0000754 TailCalls.push_back(CI);
755 }
Evan Cheng485fafc2011-03-21 01:19:09 +0000756 }
757
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000758 bool Changed = false;
759 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
760 CallInst *CI = TailCalls[i];
761 CallSite CS(CI);
762
763 // Conservatively require the attributes of the call to match those of the
764 // return. Ignore noalias because it doesn't affect the call sequence.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000765 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000766 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
767 continue;
768
769 // Make sure the call instruction is followed by an unconditional branch to
770 // the return block.
771 BasicBlock *CallBB = CI->getParent();
772 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
773 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
774 continue;
775
776 // Duplicate the return into CallBB.
777 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel52e37df2011-03-24 15:35:25 +0000778 ModifiedDT = Changed = true;
Cameron Zwarich4bae5882011-03-24 04:52:07 +0000779 ++NumRetsDup;
780 }
781
782 // If we eliminated all predecessors of the block, delete the block now.
783 if (Changed && pred_begin(BB) == pred_end(BB))
784 BB->eraseFromParent();
785
786 return Changed;
Evan Cheng485fafc2011-03-21 01:19:09 +0000787}
788
Chris Lattner88a5c832008-11-25 07:09:13 +0000789//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000790// Memory Optimization
791//===----------------------------------------------------------------------===//
792
Chris Lattnerdd77df32007-04-13 20:30:56 +0000793/// IsNonLocalValue - Return true if the specified values are defined in a
794/// different basic block than BB.
795static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
796 if (Instruction *I = dyn_cast<Instruction>(V))
797 return I->getParent() != BB;
798 return false;
799}
800
Bob Wilson4a8ee232009-12-03 21:47:07 +0000801/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000802/// addressing modes that can do significant amounts of computation. As such,
803/// instruction selection will try to get the load or store to do as much
804/// computation as possible for the program. The problem is that isel can only
805/// see within a single block. As such, we sink as much legal addressing mode
806/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000807///
808/// This method is used to optimize both load/store and inline asms with memory
809/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000810bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000811 Type *AccessTy) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000812 Value *Repl = Addr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000813
814 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersond2f41742010-11-19 22:15:03 +0000815 // unprofitable PRE transformations.
Cameron Zwarich7cb4fa22011-01-03 06:33:01 +0000816 SmallVector<Value*, 8> worklist;
817 SmallPtrSet<Value*, 16> Visited;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000818 worklist.push_back(Addr);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000819
Owen Anderson35bf4d62010-11-27 08:15:55 +0000820 // Use a worklist to iteratively look through PHI nodes, and ensure that
821 // the addressing mode obtained from the non-PHI roots of the graph
822 // are equivalent.
823 Value *Consensus = 0;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000824 unsigned NumUsesConsensus = 0;
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000825 bool IsNumUsesConsensusValid = false;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000826 SmallVector<Instruction*, 16> AddrModeInsts;
827 ExtAddrMode AddrMode;
828 while (!worklist.empty()) {
829 Value *V = worklist.back();
830 worklist.pop_back();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000831
Owen Anderson35bf4d62010-11-27 08:15:55 +0000832 // Break use-def graph loops.
Nick Lewycky48105282011-09-29 23:40:12 +0000833 if (!Visited.insert(V)) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000834 Consensus = 0;
835 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000836 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000837
Owen Anderson35bf4d62010-11-27 08:15:55 +0000838 // For a PHI node, push all of its incoming values.
839 if (PHINode *P = dyn_cast<PHINode>(V)) {
840 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
841 worklist.push_back(P->getIncomingValue(i));
842 continue;
843 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000844
Owen Anderson35bf4d62010-11-27 08:15:55 +0000845 // For non-PHIs, determine the addressing mode being computed.
846 SmallVector<Instruction*, 16> NewAddrModeInsts;
847 ExtAddrMode NewAddrMode =
Nick Lewycky48105282011-09-29 23:40:12 +0000848 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
Owen Anderson35bf4d62010-11-27 08:15:55 +0000849 NewAddrModeInsts, *TLI);
Cameron Zwarich7c8d3512011-03-05 08:12:26 +0000850
851 // This check is broken into two cases with very similar code to avoid using
852 // getNumUses() as much as possible. Some values have a lot of uses, so
853 // calling getNumUses() unconditionally caused a significant compile-time
854 // regression.
855 if (!Consensus) {
856 Consensus = V;
857 AddrMode = NewAddrMode;
858 AddrModeInsts = NewAddrModeInsts;
859 continue;
860 } else if (NewAddrMode == AddrMode) {
861 if (!IsNumUsesConsensusValid) {
862 NumUsesConsensus = Consensus->getNumUses();
863 IsNumUsesConsensusValid = true;
864 }
865
866 // Ensure that the obtained addressing mode is equivalent to that obtained
867 // for all other roots of the PHI traversal. Also, when choosing one
868 // such root as representative, select the one with the most uses in order
869 // to keep the cost modeling heuristics in AddressingModeMatcher
870 // applicable.
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000871 unsigned NumUses = V->getNumUses();
872 if (NumUses > NumUsesConsensus) {
Owen Anderson35bf4d62010-11-27 08:15:55 +0000873 Consensus = V;
Cameron Zwarich4c078f02011-03-01 21:13:53 +0000874 NumUsesConsensus = NumUses;
Owen Anderson35bf4d62010-11-27 08:15:55 +0000875 AddrModeInsts = NewAddrModeInsts;
876 }
877 continue;
878 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000879
Owen Anderson35bf4d62010-11-27 08:15:55 +0000880 Consensus = 0;
881 break;
Owen Andersond2f41742010-11-19 22:15:03 +0000882 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000883
Owen Anderson35bf4d62010-11-27 08:15:55 +0000884 // If the addressing mode couldn't be determined, or if multiple different
885 // ones were determined, bail out now.
886 if (!Consensus) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000887
Chris Lattnerdd77df32007-04-13 20:30:56 +0000888 // Check to see if any of the instructions supersumed by this addr mode are
889 // non-local to I's BB.
890 bool AnyNonLocal = false;
891 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000892 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000893 AnyNonLocal = true;
894 break;
895 }
896 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000897
Chris Lattnerdd77df32007-04-13 20:30:56 +0000898 // If all the instructions matched are already in this BB, don't do anything.
899 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000900 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000901 return false;
902 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000903
Chris Lattnerdd77df32007-04-13 20:30:56 +0000904 // Insert this computation right after this user. Since our caller is
905 // scanning from the top of the BB to the bottom, reuse of the expr are
906 // guaranteed to happen later.
Devang Patel2048c372011-09-06 18:49:53 +0000907 IRBuilder<> Builder(MemoryInst);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000908
Chris Lattnerdd77df32007-04-13 20:30:56 +0000909 // Now that we determined the addressing expression we want to use and know
910 // that we have to sink it into this block. Check to see if we have already
911 // done this for some other load/store instr in this block. If so, reuse the
912 // computation.
913 Value *&SunkAddr = SunkAddrs[Addr];
914 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000915 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000916 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000917 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000918 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000919 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000920 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000921 << *MemoryInst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000922 Type *IntPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +0000923 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000924
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000926
927 // Start with the base register. Do this first so that subsequent address
928 // matching finds it last, which will prevent it from trying to match it
929 // as the scaled value in case it happens to be a mul. That would be
930 // problematic if we've sunk a different mul for the scale, because then
931 // we'd end up sinking both muls.
932 if (AddrMode.BaseReg) {
933 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000934 if (V->getType()->isPointerTy())
Devang Patel2048c372011-09-06 18:49:53 +0000935 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000936 if (V->getType() != IntPtrTy)
Devang Patel2048c372011-09-06 18:49:53 +0000937 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000938 Result = V;
939 }
940
941 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000942 if (AddrMode.Scale) {
943 Value *V = AddrMode.ScaledReg;
944 if (V->getType() == IntPtrTy) {
945 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000946 } else if (V->getType()->isPointerTy()) {
Devang Patel2048c372011-09-06 18:49:53 +0000947 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000948 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
949 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patel2048c372011-09-06 18:49:53 +0000950 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000951 } else {
Devang Patel2048c372011-09-06 18:49:53 +0000952 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000953 }
954 if (AddrMode.Scale != 1)
Devang Patel2048c372011-09-06 18:49:53 +0000955 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
956 "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000957 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000958 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000959 else
960 Result = V;
961 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000962
Chris Lattnerdd77df32007-04-13 20:30:56 +0000963 // Add in the BaseGV if present.
964 if (AddrMode.BaseGV) {
Devang Patel2048c372011-09-06 18:49:53 +0000965 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000966 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000967 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000968 else
969 Result = V;
970 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000971
Chris Lattnerdd77df32007-04-13 20:30:56 +0000972 // Add in the Base Offset if present.
973 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000974 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000975 if (Result)
Devang Patel2048c372011-09-06 18:49:53 +0000976 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000977 else
978 Result = V;
979 }
980
981 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000982 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000983 else
Devang Patel2048c372011-09-06 18:49:53 +0000984 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000985 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000986
Owen Andersond2f41742010-11-19 22:15:03 +0000987 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000988
Chris Lattner0403b472011-04-09 07:05:44 +0000989 // If we have no uses, recursively delete the value and all dead instructions
990 // using it.
Owen Andersond2f41742010-11-19 22:15:03 +0000991 if (Repl->use_empty()) {
Chris Lattner0403b472011-04-09 07:05:44 +0000992 // This can cause recursive deletion, which can invalidate our iterator.
993 // Use a WeakVH to hold onto it in case this happens.
994 WeakVH IterHandle(CurInstIterator);
995 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000996
Owen Andersond2f41742010-11-19 22:15:03 +0000997 RecursivelyDeleteTriviallyDeadInstructions(Repl);
Chris Lattner0403b472011-04-09 07:05:44 +0000998
999 if (IterHandle != CurInstIterator) {
1000 // If the iterator instruction was recursively deleted, start over at the
1001 // start of the block.
1002 CurInstIterator = BB->begin();
1003 SunkAddrs.clear();
1004 } else {
1005 // This address is now available for reassignment, so erase the table
1006 // entry; we don't want to match some completely different instruction.
1007 SunkAddrs[Addr] = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001008 }
Dale Johannesen536d31b2010-03-31 20:37:15 +00001009 }
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001010 ++NumMemoryInsts;
Chris Lattnerdd77df32007-04-13 20:30:56 +00001011 return true;
1012}
1013
Evan Cheng9bf12b52008-02-26 02:42:37 +00001014/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +00001015/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +00001016/// possible / profitable.
Chris Lattner75796092011-01-15 07:14:54 +00001017bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng9bf12b52008-02-26 02:42:37 +00001018 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001019
Nadav Rotema94d6e82012-07-24 10:51:42 +00001020 TargetLowering::AsmOperandInfoVector
Chris Lattner75796092011-01-15 07:14:54 +00001021 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001022 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +00001023 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1024 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotema94d6e82012-07-24 10:51:42 +00001025
Evan Cheng9bf12b52008-02-26 02:42:37 +00001026 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00001027 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +00001028
Eli Friedman9ec80952008-02-26 18:37:49 +00001029 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1030 OpInfo.isIndirect) {
Chris Lattner75796092011-01-15 07:14:54 +00001031 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001032 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesen677c6ec2010-09-16 18:30:55 +00001033 } else if (OpInfo.Type == InlineAsm::isInput)
1034 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +00001035 }
1036
1037 return MadeChange;
1038}
1039
Dan Gohmanb00f2362009-10-16 20:59:35 +00001040/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1041/// basic block as the load, unless conditions are unfavorable. This allows
1042/// SelectionDAG to fold the extend into the load.
1043///
1044bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1045 // Look for a load being extended.
1046 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1047 if (!LI) return false;
1048
1049 // If they're already in the same block, there's nothing to do.
1050 if (LI->getParent() == I->getParent())
1051 return false;
1052
1053 // If the load has other users and the truncate is not free, this probably
1054 // isn't worthwhile.
1055 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +00001056 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1057 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +00001058 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +00001059 return false;
1060
1061 // Check whether the target supports casts folded into loads.
1062 unsigned LType;
1063 if (isa<ZExtInst>(I))
1064 LType = ISD::ZEXTLOAD;
1065 else {
1066 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1067 LType = ISD::SEXTLOAD;
1068 }
1069 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1070 return false;
1071
1072 // Move the extend into the same block as the load, so that SelectionDAG
1073 // can fold it.
1074 I->removeFromParent();
1075 I->insertAfter(LI);
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001076 ++NumExtsMoved;
Dan Gohmanb00f2362009-10-16 20:59:35 +00001077 return true;
1078}
1079
Evan Chengbdcb7262007-12-05 23:58:20 +00001080bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1081 BasicBlock *DefBB = I->getParent();
1082
Bob Wilson9120f5c2010-09-21 21:44:14 +00001083 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +00001084 // other uses of the source with result of extension.
1085 Value *Src = I->getOperand(0);
1086 if (Src->hasOneUse())
1087 return false;
1088
Evan Cheng696e5c02007-12-13 07:50:36 +00001089 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +00001090 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +00001091 return false;
1092
Evan Cheng772de512007-12-12 00:51:06 +00001093 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +00001094 // this block.
1095 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +00001096 return false;
1097
Evan Chengbdcb7262007-12-05 23:58:20 +00001098 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001099 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001100 UI != E; ++UI) {
1101 Instruction *User = cast<Instruction>(*UI);
1102
1103 // Figure out which BB this ext is used in.
1104 BasicBlock *UserBB = User->getParent();
1105 if (UserBB == DefBB) continue;
1106 DefIsLiveOut = true;
1107 break;
1108 }
1109 if (!DefIsLiveOut)
1110 return false;
1111
Evan Cheng765dff22007-12-12 02:53:41 +00001112 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +00001113 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +00001114 UI != E; ++UI) {
1115 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +00001116 BasicBlock *UserBB = User->getParent();
1117 if (UserBB == DefBB) continue;
1118 // Be conservative. We don't want this xform to end up introducing
1119 // reloads just before load / store instructions.
1120 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +00001121 return false;
1122 }
1123
Evan Chengbdcb7262007-12-05 23:58:20 +00001124 // InsertedTruncs - Only insert one trunc in each block once.
1125 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1126
1127 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001128 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +00001129 UI != E; ++UI) {
1130 Use &TheUse = UI.getUse();
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
1137 // Both src and def are live in this block. Rewrite the use.
1138 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1139
1140 if (!InsertedTrunc) {
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001141 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengbdcb7262007-12-05 23:58:20 +00001142 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1143 }
1144
1145 // Replace a use of the {s|z}ext source with a use of the result.
1146 TheUse = InsertedTrunc;
Cameron Zwarich31ff1332011-01-05 17:27:27 +00001147 ++NumExtUses;
Evan Chengbdcb7262007-12-05 23:58:20 +00001148 MadeChange = true;
1149 }
1150
1151 return MadeChange;
1152}
1153
Benjamin Kramer59957502012-05-05 12:49:22 +00001154/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1155/// turned into an explicit branch.
1156static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1157 // FIXME: This should use the same heuristics as IfConversion to determine
1158 // whether a select is better represented as a branch. This requires that
1159 // branch probability metadata is preserved for the select, which is not the
1160 // case currently.
1161
1162 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1163
1164 // If the branch is predicted right, an out of order CPU can avoid blocking on
1165 // the compare. Emit cmovs on compares with a memory operand as branches to
1166 // avoid stalls on the load from memory. If the compare has more than one use
1167 // there's probably another cmov or setcc around so it's not worth emitting a
1168 // branch.
1169 if (!Cmp)
1170 return false;
1171
1172 Value *CmpOp0 = Cmp->getOperand(0);
1173 Value *CmpOp1 = Cmp->getOperand(1);
1174
1175 // We check that the memory operand has one use to avoid uses of the loaded
1176 // value directly after the compare, making branches unprofitable.
1177 return Cmp->hasOneUse() &&
1178 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1179 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1180}
1181
1182
1183bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1184 // If we have a SelectInst that will likely profit from branch prediction,
1185 // turn it into a branch.
Benjamin Kramer6c505512012-06-29 19:58:21 +00001186 if (DisableSelectToBranch || OptSize || !TLI ||
1187 !TLI->isPredictableSelectExpensive())
Benjamin Kramer59957502012-05-05 12:49:22 +00001188 return false;
1189
1190 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1191 !isFormingBranchFromSelectProfitable(SI))
1192 return false;
1193
1194 ModifiedDT = true;
1195
1196 // First, we split the block containing the select into 2 blocks.
1197 BasicBlock *StartBlock = SI->getParent();
1198 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1199 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1200
1201 // Create a new block serving as the landing pad for the branch.
1202 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1203 NextBlock->getParent(), NextBlock);
1204
1205 // Move the unconditional branch from the block with the select in it into our
1206 // landing pad block.
1207 StartBlock->getTerminator()->eraseFromParent();
1208 BranchInst::Create(NextBlock, SmallBlock);
1209
1210 // Insert the real conditional branch based on the original condition.
1211 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1212
1213 // The select itself is replaced with a PHI Node.
1214 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1215 PN->takeName(SI);
1216 PN->addIncoming(SI->getTrueValue(), StartBlock);
1217 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1218 SI->replaceAllUsesWith(PN);
1219 SI->eraseFromParent();
1220
1221 // Instruct OptimizeBlock to skip to the next block.
1222 CurInstIterator = StartBlock->end();
1223 ++NumSelectsExpanded;
1224 return true;
1225}
1226
Cameron Zwarichc0611012011-01-06 02:37:26 +00001227bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001228 if (PHINode *P = dyn_cast<PHINode>(I)) {
1229 // It is possible for very late stage optimizations (such as SimplifyCFG)
1230 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1231 // trivial PHI, go ahead and zap it here.
1232 if (Value *V = SimplifyInstruction(P)) {
1233 P->replaceAllUsesWith(V);
1234 P->eraseFromParent();
1235 ++NumPHIsElim;
Chris Lattner1a8943a2011-01-15 07:29:01 +00001236 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001237 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001238 return false;
1239 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001240
Chris Lattner1a8943a2011-01-15 07:29:01 +00001241 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001242 // If the source of the cast is a constant, then this should have
1243 // already been constant folded. The only reason NOT to constant fold
1244 // it is if something (e.g. LSR) was careful to place the constant
1245 // evaluation in a block other than then one that uses it (e.g. to hoist
1246 // the address of globals out of a loop). If this is the case, we don't
1247 // want to forward-subst the cast.
1248 if (isa<Constant>(CI->getOperand(0)))
1249 return false;
1250
Chris Lattner1a8943a2011-01-15 07:29:01 +00001251 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1252 return true;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001253
Chris Lattner1a8943a2011-01-15 07:29:01 +00001254 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1255 bool MadeChange = MoveExtToFormExtLoad(I);
1256 return MadeChange | OptimizeExtUses(I);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001257 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001258 return false;
1259 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001260
Chris Lattner1a8943a2011-01-15 07:29:01 +00001261 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1262 return OptimizeCmpExpression(CI);
Nadav Rotema94d6e82012-07-24 10:51:42 +00001263
Chris Lattner1a8943a2011-01-15 07:29:01 +00001264 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001265 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001266 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1267 return false;
1268 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001269
Chris Lattner1a8943a2011-01-15 07:29:01 +00001270 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarichc0611012011-01-06 02:37:26 +00001271 if (TLI)
Chris Lattner1a8943a2011-01-15 07:29:01 +00001272 return OptimizeMemoryInst(I, SI->getOperand(1),
1273 SI->getOperand(0)->getType());
1274 return false;
1275 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001276
Chris Lattner1a8943a2011-01-15 07:29:01 +00001277 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001278 if (GEPI->hasAllZeroIndices()) {
1279 /// The GEP operand must be a pointer, so must its result -> BitCast
1280 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1281 GEPI->getName(), GEPI);
1282 GEPI->replaceAllUsesWith(NC);
1283 GEPI->eraseFromParent();
1284 ++NumGEPsElim;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001285 OptimizeInst(NC);
Chris Lattner1a8943a2011-01-15 07:29:01 +00001286 return true;
Cameron Zwarich865ae1a2011-01-06 02:44:52 +00001287 }
Chris Lattner1a8943a2011-01-15 07:29:01 +00001288 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001289 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001290
Chris Lattner1a8943a2011-01-15 07:29:01 +00001291 if (CallInst *CI = dyn_cast<CallInst>(I))
1292 return OptimizeCallInst(CI);
Cameron Zwarichc0611012011-01-06 02:37:26 +00001293
Evan Cheng485fafc2011-03-21 01:19:09 +00001294 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1295 return DupRetToEnableTailCallOpts(RI);
1296
Benjamin Kramer59957502012-05-05 12:49:22 +00001297 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1298 return OptimizeSelectInst(SI);
1299
Chris Lattner1a8943a2011-01-15 07:29:01 +00001300 return false;
Cameron Zwarichc0611012011-01-06 02:37:26 +00001301}
1302
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001303// In this pass we look for GEP and cast instructions that are used
1304// across basic blocks and rewrite them to improve basic-block-at-a-time
1305// selection.
1306bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarich8c3527e2011-01-06 00:42:50 +00001307 SunkAddrs.clear();
Cameron Zwarich56e37932011-03-02 03:31:46 +00001308 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +00001309
Chris Lattner75796092011-01-15 07:14:54 +00001310 CurInstIterator = BB.begin();
Chris Lattner94e8e0c2011-01-15 07:25:29 +00001311 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1312 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopher692bf6b2008-09-24 05:32:41 +00001313
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001314 return MadeChange;
1315}
Devang Patelf56ea612011-08-18 00:50:51 +00001316
1317// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotema94d6e82012-07-24 10:51:42 +00001318// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patelf56ea612011-08-18 00:50:51 +00001319// find a node corresponding to the value.
1320bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1321 bool MadeChange = false;
1322 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1323 Instruction *PrevNonDbgInst = NULL;
1324 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1325 Instruction *Insn = BI; ++BI;
1326 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1327 if (!DVI) {
1328 PrevNonDbgInst = Insn;
1329 continue;
1330 }
1331
1332 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1333 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1334 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1335 DVI->removeFromParent();
1336 if (isa<PHINode>(VI))
1337 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1338 else
1339 DVI->insertAfter(VI);
1340 MadeChange = true;
1341 ++NumDbgValueMoved;
1342 }
1343 }
1344 }
1345 return MadeChange;
1346}