1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "codegenprepare"
17 #include "llvm/Transforms/Scalar.h"
18 #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"
26 #include "llvm/Constants.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Function.h"
30 #include "llvm/IRBuilder.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/IntrinsicInst.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/PatternMatch.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #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"
47 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
48 #include "llvm/Transforms/Utils/Local.h"
50 using namespace llvm::PatternMatch;
52 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
53 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
55 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
61 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
64 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
65 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
67 static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
71 static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
76 class CodeGenPrepare : public FunctionPass {
77 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
80 const TargetLibraryInfo *TLInfo;
84 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
87 BasicBlock::iterator CurInstIterator;
89 /// 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.
92 DenseMap<Value*, Value*> SunkAddrs;
94 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
98 /// OptSize - True if optimizing for size.
102 static char ID; // Pass identification, replacement for typeid
103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
107 bool runOnFunction(Function &F);
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addPreserved<DominatorTree>();
111 AU.addPreserved<ProfileInfo>();
112 AU.addRequired<TargetLibraryInfo>();
116 bool EliminateFallThrough(Function &F);
117 bool EliminateMostlyEmptyBlocks(Function &F);
118 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
119 void EliminateMostlyEmptyBlock(BasicBlock *BB);
120 bool OptimizeBlock(BasicBlock &BB);
121 bool OptimizeInst(Instruction *I);
122 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
123 bool OptimizeInlineAsmInst(CallInst *CS);
124 bool OptimizeCallInst(CallInst *CI);
125 bool MoveExtToFormExtLoad(Instruction *I);
126 bool OptimizeExtUses(Instruction *I);
127 bool OptimizeSelectInst(SelectInst *SI);
128 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
129 bool PlaceDbgValues(Function &F);
133 char CodeGenPrepare::ID = 0;
134 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
135 "Optimize for code generation", false, false)
136 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
137 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
138 "Optimize for code generation", false, false)
140 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
141 return new CodeGenPrepare(TLI);
144 bool CodeGenPrepare::runOnFunction(Function &F) {
145 bool EverMadeChange = false;
148 TLInfo = &getAnalysis<TargetLibraryInfo>();
149 DT = getAnalysisIfAvailable<DominatorTree>();
150 PFI = getAnalysisIfAvailable<ProfileInfo>();
151 OptSize = F.getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
153 /// This optimization identifies DIV instructions that can be
154 /// profitably bypassed and carried out with a shorter, faster divide.
155 if (TLI && TLI->isSlowDivBypassed()) {
156 const DenseMap<unsigned int, unsigned int> &BypassWidths =
157 TLI->getBypassSlowDivWidths();
158 for (Function::iterator I = F.begin(); I != F.end(); I++)
159 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
162 // Eliminate blocks that contain only PHI nodes and an
163 // unconditional branch.
164 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
166 // llvm.dbg.value is far away from the value then iSel may not be able
167 // handle it properly. iSel will drop llvm.dbg.value if it can not
168 // find a node corresponding to the value.
169 EverMadeChange |= PlaceDbgValues(F);
171 bool MadeChange = true;
174 for (Function::iterator I = F.begin(); I != F.end(); ) {
175 BasicBlock *BB = I++;
176 MadeChange |= OptimizeBlock(*BB);
178 EverMadeChange |= MadeChange;
183 if (!DisableBranchOpts) {
185 SmallPtrSet<BasicBlock*, 8> WorkList;
186 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
187 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
188 MadeChange |= ConstantFoldTerminator(BB, true);
189 if (!MadeChange) continue;
191 for (SmallVectorImpl<BasicBlock*>::iterator
192 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
193 if (pred_begin(*II) == pred_end(*II))
194 WorkList.insert(*II);
197 // Delete the dead blocks and any of their dead successors.
198 MadeChange |= !WorkList.empty();
199 while (!WorkList.empty()) {
200 BasicBlock *BB = *WorkList.begin();
202 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
206 for (SmallVectorImpl<BasicBlock*>::iterator
207 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
208 if (pred_begin(*II) == pred_end(*II))
209 WorkList.insert(*II);
212 // Merge pairs of basic blocks with unconditional branches, connected by
214 if (EverMadeChange || MadeChange)
215 MadeChange |= EliminateFallThrough(F);
219 EverMadeChange |= MadeChange;
222 if (ModifiedDT && DT)
223 DT->DT->recalculate(F);
225 return EverMadeChange;
228 /// EliminateFallThrough - Merge basic blocks which are connected
229 /// by a single edge, where one of the basic blocks has a single successor
230 /// pointing to the other basic block, which has a single predecessor.
231 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
232 bool Changed = false;
233 // Scan all of the blocks in the function, except for the entry block.
234 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
235 BasicBlock *BB = I++;
236 // If the destination block has a single pred, then this is a trivial
237 // edge, just collapse it.
238 BasicBlock *SinglePred = BB->getSinglePredecessor();
240 // Don't merge if BB's address is taken.
241 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
243 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
244 if (Term && !Term->isConditional()) {
246 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
247 // Remember if SinglePred was the entry block of the function.
248 // If so, we will need to move BB back to the entry position.
249 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
250 MergeBasicBlockIntoOnlyPred(BB, this);
252 if (isEntry && BB != &BB->getParent()->getEntryBlock())
253 BB->moveBefore(&BB->getParent()->getEntryBlock());
255 // We have erased a block. Update the iterator.
262 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
263 /// debug info directives, and an unconditional branch. Passes before isel
264 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
265 /// isel. Start by eliminating these blocks so we can split them the way we
267 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
268 bool MadeChange = false;
269 // Note that this intentionally skips the entry block.
270 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
271 BasicBlock *BB = I++;
273 // If this block doesn't end with an uncond branch, ignore it.
274 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
275 if (!BI || !BI->isUnconditional())
278 // If the instruction before the branch (skipping debug info) isn't a phi
279 // node, then other stuff is happening here.
280 BasicBlock::iterator BBI = BI;
281 if (BBI != BB->begin()) {
283 while (isa<DbgInfoIntrinsic>(BBI)) {
284 if (BBI == BB->begin())
288 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
292 // Do not break infinite loops.
293 BasicBlock *DestBB = BI->getSuccessor(0);
297 if (!CanMergeBlocks(BB, DestBB))
300 EliminateMostlyEmptyBlock(BB);
306 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
307 /// single uncond branch between them, and BB contains no other non-phi
309 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
310 const BasicBlock *DestBB) const {
311 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
312 // the successor. If there are more complex condition (e.g. preheaders),
313 // don't mess around with them.
314 BasicBlock::const_iterator BBI = BB->begin();
315 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
316 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
318 const Instruction *User = cast<Instruction>(*UI);
319 if (User->getParent() != DestBB || !isa<PHINode>(User))
321 // If User is inside DestBB block and it is a PHINode then check
322 // incoming value. If incoming value is not from BB then this is
323 // a complex condition (e.g. preheaders) we want to avoid here.
324 if (User->getParent() == DestBB) {
325 if (const PHINode *UPN = dyn_cast<PHINode>(User))
326 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
327 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
328 if (Insn && Insn->getParent() == BB &&
329 Insn->getParent() != UPN->getIncomingBlock(I))
336 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
337 // and DestBB may have conflicting incoming values for the block. If so, we
338 // can't merge the block.
339 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
340 if (!DestBBPN) return true; // no conflict.
342 // Collect the preds of BB.
343 SmallPtrSet<const BasicBlock*, 16> BBPreds;
344 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
345 // It is faster to get preds from a PHI than with pred_iterator.
346 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
347 BBPreds.insert(BBPN->getIncomingBlock(i));
349 BBPreds.insert(pred_begin(BB), pred_end(BB));
352 // Walk the preds of DestBB.
353 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
354 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
355 if (BBPreds.count(Pred)) { // Common predecessor?
356 BBI = DestBB->begin();
357 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
358 const Value *V1 = PN->getIncomingValueForBlock(Pred);
359 const Value *V2 = PN->getIncomingValueForBlock(BB);
361 // If V2 is a phi node in BB, look up what the mapped value will be.
362 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
363 if (V2PN->getParent() == BB)
364 V2 = V2PN->getIncomingValueForBlock(Pred);
366 // If there is a conflict, bail out.
367 if (V1 != V2) return false;
376 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
377 /// an unconditional branch in it.
378 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
379 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
380 BasicBlock *DestBB = BI->getSuccessor(0);
382 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
384 // If the destination block has a single pred, then this is a trivial edge,
386 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
387 if (SinglePred != DestBB) {
388 // Remember if SinglePred was the entry block of the function. If so, we
389 // will need to move BB back to the entry position.
390 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
391 MergeBasicBlockIntoOnlyPred(DestBB, this);
393 if (isEntry && BB != &BB->getParent()->getEntryBlock())
394 BB->moveBefore(&BB->getParent()->getEntryBlock());
396 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
401 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
402 // to handle the new incoming edges it is about to have.
404 for (BasicBlock::iterator BBI = DestBB->begin();
405 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
406 // Remove the incoming value for BB, and remember it.
407 Value *InVal = PN->removeIncomingValue(BB, false);
409 // Two options: either the InVal is a phi node defined in BB or it is some
410 // value that dominates BB.
411 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
412 if (InValPhi && InValPhi->getParent() == BB) {
413 // Add all of the input values of the input PHI as inputs of this phi.
414 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
415 PN->addIncoming(InValPhi->getIncomingValue(i),
416 InValPhi->getIncomingBlock(i));
418 // Otherwise, add one instance of the dominating value for each edge that
419 // we will be adding.
420 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
421 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
422 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
424 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
425 PN->addIncoming(InVal, *PI);
430 // The PHIs are now updated, change everything that refers to BB to use
431 // DestBB and remove BB.
432 BB->replaceAllUsesWith(DestBB);
433 if (DT && !ModifiedDT) {
434 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
435 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
436 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
437 DT->changeImmediateDominator(DestBB, NewIDom);
441 PFI->replaceAllUses(BB, DestBB);
442 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
444 BB->eraseFromParent();
447 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
450 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
451 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
452 /// sink it into user blocks to reduce the number of virtual
453 /// registers that must be created and coalesced.
455 /// Return true if any changes are made.
457 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
458 // If this is a noop copy,
459 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
460 EVT DstVT = TLI.getValueType(CI->getType());
462 // This is an fp<->int conversion?
463 if (SrcVT.isInteger() != DstVT.isInteger())
466 // If this is an extension, it will be a zero or sign extension, which
468 if (SrcVT.bitsLT(DstVT)) return false;
470 // If these values will be promoted, find out what they will be promoted
471 // to. This helps us consider truncates on PPC as noop copies when they
473 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
474 TargetLowering::TypePromoteInteger)
475 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
476 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
477 TargetLowering::TypePromoteInteger)
478 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
480 // If, after promotion, these are the same types, this is a noop copy.
484 BasicBlock *DefBB = CI->getParent();
486 /// InsertedCasts - Only insert a cast in each block once.
487 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
489 bool MadeChange = false;
490 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
492 Use &TheUse = UI.getUse();
493 Instruction *User = cast<Instruction>(*UI);
495 // Figure out which BB this cast is used in. For PHI's this is the
496 // appropriate predecessor block.
497 BasicBlock *UserBB = User->getParent();
498 if (PHINode *PN = dyn_cast<PHINode>(User)) {
499 UserBB = PN->getIncomingBlock(UI);
502 // Preincrement use iterator so we don't invalidate it.
505 // If this user is in the same block as the cast, don't change the cast.
506 if (UserBB == DefBB) continue;
508 // If we have already inserted a cast into this block, use it.
509 CastInst *&InsertedCast = InsertedCasts[UserBB];
512 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
514 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
519 // Replace a use of the cast with a use of the new cast.
520 TheUse = InsertedCast;
524 // If we removed all uses, nuke the cast.
525 if (CI->use_empty()) {
526 CI->eraseFromParent();
533 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
534 /// the number of virtual registers that must be created and coalesced. This is
535 /// a clear win except on targets with multiple condition code registers
536 /// (PowerPC), where it might lose; some adjustment may be wanted there.
538 /// Return true if any changes are made.
539 static bool OptimizeCmpExpression(CmpInst *CI) {
540 BasicBlock *DefBB = CI->getParent();
542 /// InsertedCmp - Only insert a cmp in each block once.
543 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
545 bool MadeChange = false;
546 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
548 Use &TheUse = UI.getUse();
549 Instruction *User = cast<Instruction>(*UI);
551 // Preincrement use iterator so we don't invalidate it.
554 // Don't bother for PHI nodes.
555 if (isa<PHINode>(User))
558 // Figure out which BB this cmp is used in.
559 BasicBlock *UserBB = User->getParent();
561 // If this user is in the same block as the cmp, don't change the cmp.
562 if (UserBB == DefBB) continue;
564 // If we have already inserted a cmp into this block, use it.
565 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
568 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
570 CmpInst::Create(CI->getOpcode(),
571 CI->getPredicate(), CI->getOperand(0),
572 CI->getOperand(1), "", InsertPt);
576 // Replace a use of the cmp with a use of the new cmp.
577 TheUse = InsertedCmp;
581 // If we removed all uses, nuke the cmp.
583 CI->eraseFromParent();
589 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
591 void replaceCall(Value *With) {
592 CI->replaceAllUsesWith(With);
593 CI->eraseFromParent();
595 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
596 if (ConstantInt *SizeCI =
597 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
598 return SizeCI->isAllOnesValue();
602 } // end anonymous namespace
604 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
605 BasicBlock *BB = CI->getParent();
607 // Lower inline assembly if we can.
608 // If we found an inline asm expession, and if the target knows how to
609 // lower it to normal LLVM code, do so now.
610 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
611 if (TLI->ExpandInlineAsm(CI)) {
612 // Avoid invalidating the iterator.
613 CurInstIterator = BB->begin();
614 // Avoid processing instructions out of order, which could cause
615 // reuse before a value is defined.
619 // Sink address computing for memory operands into the block.
620 if (OptimizeInlineAsmInst(CI))
624 // Lower all uses of llvm.objectsize.*
625 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
626 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
627 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
628 Type *ReturnTy = CI->getType();
629 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
631 // Substituting this can cause recursive simplifications, which can
632 // invalidate our iterator. Use a WeakVH to hold onto it in case this
634 WeakVH IterHandle(CurInstIterator);
636 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
637 TLInfo, ModifiedDT ? 0 : DT);
639 // If the iterator instruction was recursively deleted, start over at the
640 // start of the block.
641 if (IterHandle != CurInstIterator) {
642 CurInstIterator = BB->begin();
649 SmallVector<Value*, 2> PtrOps;
651 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
652 while (!PtrOps.empty())
653 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
657 // From here on out we're working with named functions.
658 if (CI->getCalledFunction() == 0) return false;
660 // We'll need DataLayout from here on out.
661 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
662 if (!TD) return false;
664 // Lower all default uses of _chk calls. This is very similar
665 // to what InstCombineCalls does, but here we are only lowering calls
666 // that have the default "don't know" as the objectsize. Anything else
667 // should be left alone.
668 CodeGenPrepareFortifiedLibCalls Simplifier;
669 return Simplifier.fold(CI, TD, TLInfo);
672 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
673 /// instructions to the predecessor to enable tail call optimizations. The
674 /// case it is currently looking for is:
677 /// %tmp0 = tail call i32 @f0()
680 /// %tmp1 = tail call i32 @f1()
683 /// %tmp2 = tail call i32 @f2()
686 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
694 /// %tmp0 = tail call i32 @f0()
697 /// %tmp1 = tail call i32 @f1()
700 /// %tmp2 = tail call i32 @f2()
703 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
707 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
712 BitCastInst *BCI = 0;
713 Value *V = RI->getReturnValue();
715 BCI = dyn_cast<BitCastInst>(V);
717 V = BCI->getOperand(0);
719 PN = dyn_cast<PHINode>(V);
724 if (PN && PN->getParent() != BB)
727 // It's not safe to eliminate the sign / zero extension of the return value.
728 // See llvm::isInTailCallPosition().
729 const Function *F = BB->getParent();
730 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
731 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
732 CallerRetAttr.hasAttribute(Attributes::SExt))
735 // Make sure there are no instructions between the PHI and return, or that the
736 // return is the first instruction in the block.
738 BasicBlock::iterator BI = BB->begin();
739 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
741 // Also skip over the bitcast.
746 BasicBlock::iterator BI = BB->begin();
747 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
752 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
754 SmallVector<CallInst*, 4> TailCalls;
756 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
757 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
758 // Make sure the phi value is indeed produced by the tail call.
759 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
760 TLI->mayBeEmittedAsTailCall(CI))
761 TailCalls.push_back(CI);
764 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
765 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
766 if (!VisitedBBs.insert(*PI))
769 BasicBlock::InstListType &InstList = (*PI)->getInstList();
770 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
771 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
772 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
776 CallInst *CI = dyn_cast<CallInst>(&*RI);
777 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
778 TailCalls.push_back(CI);
782 bool Changed = false;
783 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
784 CallInst *CI = TailCalls[i];
787 // Conservatively require the attributes of the call to match those of the
788 // return. Ignore noalias because it doesn't affect the call sequence.
789 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
790 if (AttrBuilder(CalleeRetAttr).
791 removeAttribute(Attributes::NoAlias) !=
792 AttrBuilder(CallerRetAttr).
793 removeAttribute(Attributes::NoAlias))
796 // Make sure the call instruction is followed by an unconditional branch to
798 BasicBlock *CallBB = CI->getParent();
799 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
800 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
803 // Duplicate the return into CallBB.
804 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
805 ModifiedDT = Changed = true;
809 // If we eliminated all predecessors of the block, delete the block now.
810 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
811 BB->eraseFromParent();
816 //===----------------------------------------------------------------------===//
817 // Memory Optimization
818 //===----------------------------------------------------------------------===//
820 /// IsNonLocalValue - Return true if the specified values are defined in a
821 /// different basic block than BB.
822 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
823 if (Instruction *I = dyn_cast<Instruction>(V))
824 return I->getParent() != BB;
828 /// OptimizeMemoryInst - Load and Store Instructions often have
829 /// addressing modes that can do significant amounts of computation. As such,
830 /// instruction selection will try to get the load or store to do as much
831 /// computation as possible for the program. The problem is that isel can only
832 /// see within a single block. As such, we sink as much legal addressing mode
833 /// stuff into the block as possible.
835 /// This method is used to optimize both load/store and inline asms with memory
837 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
841 // Try to collapse single-value PHI nodes. This is necessary to undo
842 // unprofitable PRE transformations.
843 SmallVector<Value*, 8> worklist;
844 SmallPtrSet<Value*, 16> Visited;
845 worklist.push_back(Addr);
847 // Use a worklist to iteratively look through PHI nodes, and ensure that
848 // the addressing mode obtained from the non-PHI roots of the graph
850 Value *Consensus = 0;
851 unsigned NumUsesConsensus = 0;
852 bool IsNumUsesConsensusValid = false;
853 SmallVector<Instruction*, 16> AddrModeInsts;
854 ExtAddrMode AddrMode;
855 while (!worklist.empty()) {
856 Value *V = worklist.back();
859 // Break use-def graph loops.
860 if (!Visited.insert(V)) {
865 // For a PHI node, push all of its incoming values.
866 if (PHINode *P = dyn_cast<PHINode>(V)) {
867 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
868 worklist.push_back(P->getIncomingValue(i));
872 // For non-PHIs, determine the addressing mode being computed.
873 SmallVector<Instruction*, 16> NewAddrModeInsts;
874 ExtAddrMode NewAddrMode =
875 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
876 NewAddrModeInsts, *TLI);
878 // This check is broken into two cases with very similar code to avoid using
879 // getNumUses() as much as possible. Some values have a lot of uses, so
880 // calling getNumUses() unconditionally caused a significant compile-time
884 AddrMode = NewAddrMode;
885 AddrModeInsts = NewAddrModeInsts;
887 } else if (NewAddrMode == AddrMode) {
888 if (!IsNumUsesConsensusValid) {
889 NumUsesConsensus = Consensus->getNumUses();
890 IsNumUsesConsensusValid = true;
893 // Ensure that the obtained addressing mode is equivalent to that obtained
894 // for all other roots of the PHI traversal. Also, when choosing one
895 // such root as representative, select the one with the most uses in order
896 // to keep the cost modeling heuristics in AddressingModeMatcher
898 unsigned NumUses = V->getNumUses();
899 if (NumUses > NumUsesConsensus) {
901 NumUsesConsensus = NumUses;
902 AddrModeInsts = NewAddrModeInsts;
911 // If the addressing mode couldn't be determined, or if multiple different
912 // ones were determined, bail out now.
913 if (!Consensus) return false;
915 // Check to see if any of the instructions supersumed by this addr mode are
916 // non-local to I's BB.
917 bool AnyNonLocal = false;
918 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
919 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
925 // If all the instructions matched are already in this BB, don't do anything.
927 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
931 // Insert this computation right after this user. Since our caller is
932 // scanning from the top of the BB to the bottom, reuse of the expr are
933 // guaranteed to happen later.
934 IRBuilder<> Builder(MemoryInst);
936 // Now that we determined the addressing expression we want to use and know
937 // that we have to sink it into this block. Check to see if we have already
938 // done this for some other load/store instr in this block. If so, reuse the
940 Value *&SunkAddr = SunkAddrs[Addr];
942 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
944 if (SunkAddr->getType() != Addr->getType())
945 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
947 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
950 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
954 // Start with the base register. Do this first so that subsequent address
955 // matching finds it last, which will prevent it from trying to match it
956 // as the scaled value in case it happens to be a mul. That would be
957 // problematic if we've sunk a different mul for the scale, because then
958 // we'd end up sinking both muls.
959 if (AddrMode.BaseReg) {
960 Value *V = AddrMode.BaseReg;
961 if (V->getType()->isPointerTy())
962 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
963 if (V->getType() != IntPtrTy)
964 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
968 // Add the scale value.
969 if (AddrMode.Scale) {
970 Value *V = AddrMode.ScaledReg;
971 if (V->getType() == IntPtrTy) {
973 } else if (V->getType()->isPointerTy()) {
974 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
975 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
976 cast<IntegerType>(V->getType())->getBitWidth()) {
977 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
979 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
981 if (AddrMode.Scale != 1)
982 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
985 Result = Builder.CreateAdd(Result, V, "sunkaddr");
990 // Add in the BaseGV if present.
991 if (AddrMode.BaseGV) {
992 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
994 Result = Builder.CreateAdd(Result, V, "sunkaddr");
999 // Add in the Base Offset if present.
1000 if (AddrMode.BaseOffs) {
1001 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1003 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1009 SunkAddr = Constant::getNullValue(Addr->getType());
1011 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1014 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1016 // If we have no uses, recursively delete the value and all dead instructions
1018 if (Repl->use_empty()) {
1019 // This can cause recursive deletion, which can invalidate our iterator.
1020 // Use a WeakVH to hold onto it in case this happens.
1021 WeakVH IterHandle(CurInstIterator);
1022 BasicBlock *BB = CurInstIterator->getParent();
1024 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1026 if (IterHandle != CurInstIterator) {
1027 // If the iterator instruction was recursively deleted, start over at the
1028 // start of the block.
1029 CurInstIterator = BB->begin();
1032 // This address is now available for reassignment, so erase the table
1033 // entry; we don't want to match some completely different instruction.
1034 SunkAddrs[Addr] = 0;
1041 /// OptimizeInlineAsmInst - If there are any memory operands, use
1042 /// OptimizeMemoryInst to sink their address computing into the block when
1043 /// possible / profitable.
1044 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1045 bool MadeChange = false;
1047 TargetLowering::AsmOperandInfoVector
1048 TargetConstraints = TLI->ParseConstraints(CS);
1050 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1051 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1053 // Compute the constraint code and ConstraintType to use.
1054 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1056 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1057 OpInfo.isIndirect) {
1058 Value *OpVal = CS->getArgOperand(ArgNo++);
1059 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1060 } else if (OpInfo.Type == InlineAsm::isInput)
1067 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1068 /// basic block as the load, unless conditions are unfavorable. This allows
1069 /// SelectionDAG to fold the extend into the load.
1071 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1072 // Look for a load being extended.
1073 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1074 if (!LI) return false;
1076 // If they're already in the same block, there's nothing to do.
1077 if (LI->getParent() == I->getParent())
1080 // If the load has other users and the truncate is not free, this probably
1081 // isn't worthwhile.
1082 if (!LI->hasOneUse() &&
1083 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1084 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1085 !TLI->isTruncateFree(I->getType(), LI->getType()))
1088 // Check whether the target supports casts folded into loads.
1090 if (isa<ZExtInst>(I))
1091 LType = ISD::ZEXTLOAD;
1093 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1094 LType = ISD::SEXTLOAD;
1096 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1099 // Move the extend into the same block as the load, so that SelectionDAG
1101 I->removeFromParent();
1107 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1108 BasicBlock *DefBB = I->getParent();
1110 // If the result of a {s|z}ext and its source are both live out, rewrite all
1111 // other uses of the source with result of extension.
1112 Value *Src = I->getOperand(0);
1113 if (Src->hasOneUse())
1116 // Only do this xform if truncating is free.
1117 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1120 // Only safe to perform the optimization if the source is also defined in
1122 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1125 bool DefIsLiveOut = false;
1126 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1128 Instruction *User = cast<Instruction>(*UI);
1130 // Figure out which BB this ext is used in.
1131 BasicBlock *UserBB = User->getParent();
1132 if (UserBB == DefBB) continue;
1133 DefIsLiveOut = true;
1139 // Make sure non of the uses are PHI nodes.
1140 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1142 Instruction *User = cast<Instruction>(*UI);
1143 BasicBlock *UserBB = User->getParent();
1144 if (UserBB == DefBB) continue;
1145 // Be conservative. We don't want this xform to end up introducing
1146 // reloads just before load / store instructions.
1147 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1151 // InsertedTruncs - Only insert one trunc in each block once.
1152 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1154 bool MadeChange = false;
1155 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1157 Use &TheUse = UI.getUse();
1158 Instruction *User = cast<Instruction>(*UI);
1160 // Figure out which BB this ext is used in.
1161 BasicBlock *UserBB = User->getParent();
1162 if (UserBB == DefBB) continue;
1164 // Both src and def are live in this block. Rewrite the use.
1165 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1167 if (!InsertedTrunc) {
1168 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1169 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1172 // Replace a use of the {s|z}ext source with a use of the result.
1173 TheUse = InsertedTrunc;
1181 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1182 /// turned into an explicit branch.
1183 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1184 // FIXME: This should use the same heuristics as IfConversion to determine
1185 // whether a select is better represented as a branch. This requires that
1186 // branch probability metadata is preserved for the select, which is not the
1189 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1191 // If the branch is predicted right, an out of order CPU can avoid blocking on
1192 // the compare. Emit cmovs on compares with a memory operand as branches to
1193 // avoid stalls on the load from memory. If the compare has more than one use
1194 // there's probably another cmov or setcc around so it's not worth emitting a
1199 Value *CmpOp0 = Cmp->getOperand(0);
1200 Value *CmpOp1 = Cmp->getOperand(1);
1202 // We check that the memory operand has one use to avoid uses of the loaded
1203 // value directly after the compare, making branches unprofitable.
1204 return Cmp->hasOneUse() &&
1205 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1206 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1210 /// If we have a SelectInst that will likely profit from branch prediction,
1211 /// turn it into a branch.
1212 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1213 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1215 // Can we convert the 'select' to CF ?
1216 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1219 TargetLowering::SelectSupportKind SelectKind;
1221 SelectKind = TargetLowering::VectorMaskSelect;
1222 else if (SI->getType()->isVectorTy())
1223 SelectKind = TargetLowering::ScalarCondVectorVal;
1225 SelectKind = TargetLowering::ScalarValSelect;
1227 // Do we have efficient codegen support for this kind of 'selects' ?
1228 if (TLI->isSelectSupported(SelectKind)) {
1229 // We have efficient codegen support for the select instruction.
1230 // Check if it is profitable to keep this 'select'.
1231 if (!TLI->isPredictableSelectExpensive() ||
1232 !isFormingBranchFromSelectProfitable(SI))
1238 // First, we split the block containing the select into 2 blocks.
1239 BasicBlock *StartBlock = SI->getParent();
1240 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1241 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1243 // Create a new block serving as the landing pad for the branch.
1244 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1245 NextBlock->getParent(), NextBlock);
1247 // Move the unconditional branch from the block with the select in it into our
1248 // landing pad block.
1249 StartBlock->getTerminator()->eraseFromParent();
1250 BranchInst::Create(NextBlock, SmallBlock);
1252 // Insert the real conditional branch based on the original condition.
1253 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1255 // The select itself is replaced with a PHI Node.
1256 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1258 PN->addIncoming(SI->getTrueValue(), StartBlock);
1259 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1260 SI->replaceAllUsesWith(PN);
1261 SI->eraseFromParent();
1263 // Instruct OptimizeBlock to skip to the next block.
1264 CurInstIterator = StartBlock->end();
1265 ++NumSelectsExpanded;
1269 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1270 if (PHINode *P = dyn_cast<PHINode>(I)) {
1271 // It is possible for very late stage optimizations (such as SimplifyCFG)
1272 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1273 // trivial PHI, go ahead and zap it here.
1274 if (Value *V = SimplifyInstruction(P)) {
1275 P->replaceAllUsesWith(V);
1276 P->eraseFromParent();
1283 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1284 // If the source of the cast is a constant, then this should have
1285 // already been constant folded. The only reason NOT to constant fold
1286 // it is if something (e.g. LSR) was careful to place the constant
1287 // evaluation in a block other than then one that uses it (e.g. to hoist
1288 // the address of globals out of a loop). If this is the case, we don't
1289 // want to forward-subst the cast.
1290 if (isa<Constant>(CI->getOperand(0)))
1293 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1296 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1297 bool MadeChange = MoveExtToFormExtLoad(I);
1298 return MadeChange | OptimizeExtUses(I);
1303 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1304 return OptimizeCmpExpression(CI);
1306 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1308 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1312 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1314 return OptimizeMemoryInst(I, SI->getOperand(1),
1315 SI->getOperand(0)->getType());
1319 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1320 if (GEPI->hasAllZeroIndices()) {
1321 /// The GEP operand must be a pointer, so must its result -> BitCast
1322 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1323 GEPI->getName(), GEPI);
1324 GEPI->replaceAllUsesWith(NC);
1325 GEPI->eraseFromParent();
1333 if (CallInst *CI = dyn_cast<CallInst>(I))
1334 return OptimizeCallInst(CI);
1336 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1337 return OptimizeSelectInst(SI);
1342 // In this pass we look for GEP and cast instructions that are used
1343 // across basic blocks and rewrite them to improve basic-block-at-a-time
1345 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1347 bool MadeChange = false;
1349 CurInstIterator = BB.begin();
1350 while (CurInstIterator != BB.end())
1351 MadeChange |= OptimizeInst(CurInstIterator++);
1353 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1358 // llvm.dbg.value is far away from the value then iSel may not be able
1359 // handle it properly. iSel will drop llvm.dbg.value if it can not
1360 // find a node corresponding to the value.
1361 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1362 bool MadeChange = false;
1363 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1364 Instruction *PrevNonDbgInst = NULL;
1365 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1366 Instruction *Insn = BI; ++BI;
1367 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1369 PrevNonDbgInst = Insn;
1373 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1374 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1375 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1376 DVI->removeFromParent();
1377 if (isa<PHINode>(VI))
1378 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1380 DVI->insertAfter(VI);