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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/ProfileInfo.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #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/BypassSlowDivision.h"
47 #include "llvm/Transforms/Utils/Local.h"
49 using namespace llvm::PatternMatch;
51 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
52 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
53 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
54 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59 "computations were sunk");
60 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
61 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
63 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
64 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
66 static cl::opt<bool> DisableBranchOpts(
67 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
68 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70 static cl::opt<bool> DisableSelectToBranch(
71 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
72 cl::desc("Disable select to branch conversion."));
75 class CodeGenPrepare : public FunctionPass {
76 /// TLI - Keep a pointer of a TargetLowering to consult for determining
77 /// transformation profitability.
78 const TargetLowering *TLI;
79 const TargetLibraryInfo *TLInfo;
83 /// CurInstIterator - As we scan instructions optimizing them, this is the
84 /// next instruction to optimize. Xforms that can invalidate this should
86 BasicBlock::iterator CurInstIterator;
88 /// Keeps track of non-local addresses that have been sunk into a block.
89 /// This allows us to avoid inserting duplicate code for blocks with
90 /// multiple load/stores of the same address.
91 DenseMap<Value*, Value*> SunkAddrs;
93 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
97 /// OptSize - True if optimizing for size.
101 static char ID; // Pass identification, replacement for typeid
102 explicit CodeGenPrepare(const TargetLowering *tli = 0)
103 : FunctionPass(ID), TLI(tli) {
104 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
106 bool runOnFunction(Function &F);
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addPreserved<DominatorTree>();
110 AU.addPreserved<ProfileInfo>();
111 AU.addRequired<TargetLibraryInfo>();
115 bool EliminateFallThrough(Function &F);
116 bool EliminateMostlyEmptyBlocks(Function &F);
117 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
118 void EliminateMostlyEmptyBlock(BasicBlock *BB);
119 bool OptimizeBlock(BasicBlock &BB);
120 bool OptimizeInst(Instruction *I);
121 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
122 bool OptimizeInlineAsmInst(CallInst *CS);
123 bool OptimizeCallInst(CallInst *CI);
124 bool MoveExtToFormExtLoad(Instruction *I);
125 bool OptimizeExtUses(Instruction *I);
126 bool OptimizeSelectInst(SelectInst *SI);
127 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
128 bool PlaceDbgValues(Function &F);
132 char CodeGenPrepare::ID = 0;
133 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
134 "Optimize for code generation", false, false)
135 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
136 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
139 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
140 return new CodeGenPrepare(TLI);
143 bool CodeGenPrepare::runOnFunction(Function &F) {
144 bool EverMadeChange = false;
147 TLInfo = &getAnalysis<TargetLibraryInfo>();
148 DT = getAnalysisIfAvailable<DominatorTree>();
149 PFI = getAnalysisIfAvailable<ProfileInfo>();
150 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
152 /// This optimization identifies DIV instructions that can be
153 /// profitably bypassed and carried out with a shorter, faster divide.
154 if (TLI && TLI->isSlowDivBypassed()) {
155 const DenseMap<Type*, Type*> &BypassTypeMap = TLI->getBypassSlowDivTypes();
156 for (Function::iterator I = F.begin(); I != F.end(); I++)
157 EverMadeChange |= bypassSlowDivision(F, I, BypassTypeMap);
160 // Eliminate blocks that contain only PHI nodes and an
161 // unconditional branch.
162 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
164 // llvm.dbg.value is far away from the value then iSel may not be able
165 // handle it properly. iSel will drop llvm.dbg.value if it can not
166 // find a node corresponding to the value.
167 EverMadeChange |= PlaceDbgValues(F);
169 bool MadeChange = true;
172 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
173 BasicBlock *BB = I++;
174 MadeChange |= OptimizeBlock(*BB);
176 EverMadeChange |= MadeChange;
181 if (!DisableBranchOpts) {
183 SmallPtrSet<BasicBlock*, 8> WorkList;
184 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
185 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
186 MadeChange |= ConstantFoldTerminator(BB, true);
187 if (!MadeChange) continue;
189 for (SmallVectorImpl<BasicBlock*>::iterator
190 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
191 if (pred_begin(*II) == pred_end(*II))
192 WorkList.insert(*II);
195 for (SmallPtrSet<BasicBlock*, 8>::iterator
196 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
199 // Merge pairs of basic blocks with unconditional branches, connected by
201 if (EverMadeChange || MadeChange)
202 MadeChange |= EliminateFallThrough(F);
206 EverMadeChange |= MadeChange;
209 if (ModifiedDT && DT)
210 DT->DT->recalculate(F);
212 return EverMadeChange;
215 /// EliminateFallThrough - Merge basic blocks which are connected
216 /// by a single edge, where one of the basic blocks has a single successor
217 /// pointing to the other basic block, which has a single predecessor.
218 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
219 bool Changed = false;
220 // Scan all of the blocks in the function, except for the entry block.
221 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
222 BasicBlock *BB = I++;
223 // If the destination block has a single pred, then this is a trivial
224 // edge, just collapse it.
225 BasicBlock *SinglePred = BB->getSinglePredecessor();
227 if (!SinglePred || SinglePred == BB) continue;
229 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
230 if (Term && !Term->isConditional()) {
232 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
233 // Remember if SinglePred was the entry block of the function.
234 // If so, we will need to move BB back to the entry position.
235 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
236 MergeBasicBlockIntoOnlyPred(BB, this);
238 if (isEntry && BB != &BB->getParent()->getEntryBlock())
239 BB->moveBefore(&BB->getParent()->getEntryBlock());
241 // We have erased a block. Update the iterator.
248 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
249 /// debug info directives, and an unconditional branch. Passes before isel
250 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
251 /// isel. Start by eliminating these blocks so we can split them the way we
253 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
254 bool MadeChange = false;
255 // Note that this intentionally skips the entry block.
256 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
257 BasicBlock *BB = I++;
259 // If this block doesn't end with an uncond branch, ignore it.
260 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
261 if (!BI || !BI->isUnconditional())
264 // If the instruction before the branch (skipping debug info) isn't a phi
265 // node, then other stuff is happening here.
266 BasicBlock::iterator BBI = BI;
267 if (BBI != BB->begin()) {
269 while (isa<DbgInfoIntrinsic>(BBI)) {
270 if (BBI == BB->begin())
274 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
278 // Do not break infinite loops.
279 BasicBlock *DestBB = BI->getSuccessor(0);
283 if (!CanMergeBlocks(BB, DestBB))
286 EliminateMostlyEmptyBlock(BB);
292 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
293 /// single uncond branch between them, and BB contains no other non-phi
295 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
296 const BasicBlock *DestBB) const {
297 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
298 // the successor. If there are more complex condition (e.g. preheaders),
299 // don't mess around with them.
300 BasicBlock::const_iterator BBI = BB->begin();
301 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
302 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
304 const Instruction *User = cast<Instruction>(*UI);
305 if (User->getParent() != DestBB || !isa<PHINode>(User))
307 // If User is inside DestBB block and it is a PHINode then check
308 // incoming value. If incoming value is not from BB then this is
309 // a complex condition (e.g. preheaders) we want to avoid here.
310 if (User->getParent() == DestBB) {
311 if (const PHINode *UPN = dyn_cast<PHINode>(User))
312 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
313 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
314 if (Insn && Insn->getParent() == BB &&
315 Insn->getParent() != UPN->getIncomingBlock(I))
322 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
323 // and DestBB may have conflicting incoming values for the block. If so, we
324 // can't merge the block.
325 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
326 if (!DestBBPN) return true; // no conflict.
328 // Collect the preds of BB.
329 SmallPtrSet<const BasicBlock*, 16> BBPreds;
330 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
331 // It is faster to get preds from a PHI than with pred_iterator.
332 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
333 BBPreds.insert(BBPN->getIncomingBlock(i));
335 BBPreds.insert(pred_begin(BB), pred_end(BB));
338 // Walk the preds of DestBB.
339 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
340 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
341 if (BBPreds.count(Pred)) { // Common predecessor?
342 BBI = DestBB->begin();
343 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
344 const Value *V1 = PN->getIncomingValueForBlock(Pred);
345 const Value *V2 = PN->getIncomingValueForBlock(BB);
347 // If V2 is a phi node in BB, look up what the mapped value will be.
348 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
349 if (V2PN->getParent() == BB)
350 V2 = V2PN->getIncomingValueForBlock(Pred);
352 // If there is a conflict, bail out.
353 if (V1 != V2) return false;
362 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
363 /// an unconditional branch in it.
364 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
365 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
366 BasicBlock *DestBB = BI->getSuccessor(0);
368 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
370 // If the destination block has a single pred, then this is a trivial edge,
372 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
373 if (SinglePred != DestBB) {
374 // Remember if SinglePred was the entry block of the function. If so, we
375 // will need to move BB back to the entry position.
376 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
377 MergeBasicBlockIntoOnlyPred(DestBB, this);
379 if (isEntry && BB != &BB->getParent()->getEntryBlock())
380 BB->moveBefore(&BB->getParent()->getEntryBlock());
382 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
387 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
388 // to handle the new incoming edges it is about to have.
390 for (BasicBlock::iterator BBI = DestBB->begin();
391 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
392 // Remove the incoming value for BB, and remember it.
393 Value *InVal = PN->removeIncomingValue(BB, false);
395 // Two options: either the InVal is a phi node defined in BB or it is some
396 // value that dominates BB.
397 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
398 if (InValPhi && InValPhi->getParent() == BB) {
399 // Add all of the input values of the input PHI as inputs of this phi.
400 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
401 PN->addIncoming(InValPhi->getIncomingValue(i),
402 InValPhi->getIncomingBlock(i));
404 // Otherwise, add one instance of the dominating value for each edge that
405 // we will be adding.
406 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
407 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
408 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
410 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
411 PN->addIncoming(InVal, *PI);
416 // The PHIs are now updated, change everything that refers to BB to use
417 // DestBB and remove BB.
418 BB->replaceAllUsesWith(DestBB);
419 if (DT && !ModifiedDT) {
420 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
421 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
422 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
423 DT->changeImmediateDominator(DestBB, NewIDom);
427 PFI->replaceAllUses(BB, DestBB);
428 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
430 BB->eraseFromParent();
433 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
436 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
437 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
438 /// sink it into user blocks to reduce the number of virtual
439 /// registers that must be created and coalesced.
441 /// Return true if any changes are made.
443 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
444 // If this is a noop copy,
445 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
446 EVT DstVT = TLI.getValueType(CI->getType());
448 // This is an fp<->int conversion?
449 if (SrcVT.isInteger() != DstVT.isInteger())
452 // If this is an extension, it will be a zero or sign extension, which
454 if (SrcVT.bitsLT(DstVT)) return false;
456 // If these values will be promoted, find out what they will be promoted
457 // to. This helps us consider truncates on PPC as noop copies when they
459 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
460 TargetLowering::TypePromoteInteger)
461 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
462 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
463 TargetLowering::TypePromoteInteger)
464 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
466 // If, after promotion, these are the same types, this is a noop copy.
470 BasicBlock *DefBB = CI->getParent();
472 /// InsertedCasts - Only insert a cast in each block once.
473 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
475 bool MadeChange = false;
476 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
478 Use &TheUse = UI.getUse();
479 Instruction *User = cast<Instruction>(*UI);
481 // Figure out which BB this cast is used in. For PHI's this is the
482 // appropriate predecessor block.
483 BasicBlock *UserBB = User->getParent();
484 if (PHINode *PN = dyn_cast<PHINode>(User)) {
485 UserBB = PN->getIncomingBlock(UI);
488 // Preincrement use iterator so we don't invalidate it.
491 // If this user is in the same block as the cast, don't change the cast.
492 if (UserBB == DefBB) continue;
494 // If we have already inserted a cast into this block, use it.
495 CastInst *&InsertedCast = InsertedCasts[UserBB];
498 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
500 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
505 // Replace a use of the cast with a use of the new cast.
506 TheUse = InsertedCast;
510 // If we removed all uses, nuke the cast.
511 if (CI->use_empty()) {
512 CI->eraseFromParent();
519 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
520 /// the number of virtual registers that must be created and coalesced. This is
521 /// a clear win except on targets with multiple condition code registers
522 /// (PowerPC), where it might lose; some adjustment may be wanted there.
524 /// Return true if any changes are made.
525 static bool OptimizeCmpExpression(CmpInst *CI) {
526 BasicBlock *DefBB = CI->getParent();
528 /// InsertedCmp - Only insert a cmp in each block once.
529 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
531 bool MadeChange = false;
532 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
534 Use &TheUse = UI.getUse();
535 Instruction *User = cast<Instruction>(*UI);
537 // Preincrement use iterator so we don't invalidate it.
540 // Don't bother for PHI nodes.
541 if (isa<PHINode>(User))
544 // Figure out which BB this cmp is used in.
545 BasicBlock *UserBB = User->getParent();
547 // If this user is in the same block as the cmp, don't change the cmp.
548 if (UserBB == DefBB) continue;
550 // If we have already inserted a cmp into this block, use it.
551 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
554 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
556 CmpInst::Create(CI->getOpcode(),
557 CI->getPredicate(), CI->getOperand(0),
558 CI->getOperand(1), "", InsertPt);
562 // Replace a use of the cmp with a use of the new cmp.
563 TheUse = InsertedCmp;
567 // If we removed all uses, nuke the cmp.
569 CI->eraseFromParent();
575 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
577 void replaceCall(Value *With) {
578 CI->replaceAllUsesWith(With);
579 CI->eraseFromParent();
581 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
582 if (ConstantInt *SizeCI =
583 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
584 return SizeCI->isAllOnesValue();
588 } // end anonymous namespace
590 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
591 BasicBlock *BB = CI->getParent();
593 // Lower inline assembly if we can.
594 // If we found an inline asm expession, and if the target knows how to
595 // lower it to normal LLVM code, do so now.
596 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
597 if (TLI->ExpandInlineAsm(CI)) {
598 // Avoid invalidating the iterator.
599 CurInstIterator = BB->begin();
600 // Avoid processing instructions out of order, which could cause
601 // reuse before a value is defined.
605 // Sink address computing for memory operands into the block.
606 if (OptimizeInlineAsmInst(CI))
610 // Lower all uses of llvm.objectsize.*
611 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
612 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
613 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
614 Type *ReturnTy = CI->getType();
615 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
617 // Substituting this can cause recursive simplifications, which can
618 // invalidate our iterator. Use a WeakVH to hold onto it in case this
620 WeakVH IterHandle(CurInstIterator);
622 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
623 TLInfo, ModifiedDT ? 0 : DT);
625 // If the iterator instruction was recursively deleted, start over at the
626 // start of the block.
627 if (IterHandle != CurInstIterator) {
628 CurInstIterator = BB->begin();
635 SmallVector<Value*, 2> PtrOps;
637 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
638 while (!PtrOps.empty())
639 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
643 // From here on out we're working with named functions.
644 if (CI->getCalledFunction() == 0) return false;
646 // We'll need TargetData from here on out.
647 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
648 if (!TD) return false;
650 // Lower all default uses of _chk calls. This is very similar
651 // to what InstCombineCalls does, but here we are only lowering calls
652 // that have the default "don't know" as the objectsize. Anything else
653 // should be left alone.
654 CodeGenPrepareFortifiedLibCalls Simplifier;
655 return Simplifier.fold(CI, TD, TLInfo);
658 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
659 /// instructions to the predecessor to enable tail call optimizations. The
660 /// case it is currently looking for is:
663 /// %tmp0 = tail call i32 @f0()
666 /// %tmp1 = tail call i32 @f1()
669 /// %tmp2 = tail call i32 @f2()
672 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
680 /// %tmp0 = tail call i32 @f0()
683 /// %tmp1 = tail call i32 @f1()
686 /// %tmp2 = tail call i32 @f2()
689 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
694 BitCastInst *BCI = 0;
695 Value *V = RI->getReturnValue();
697 BCI = dyn_cast<BitCastInst>(V);
699 V = BCI->getOperand(0);
701 PN = dyn_cast<PHINode>(V);
706 BasicBlock *BB = RI->getParent();
707 if (PN && PN->getParent() != BB)
710 // It's not safe to eliminate the sign / zero extension of the return value.
711 // See llvm::isInTailCallPosition().
712 const Function *F = BB->getParent();
713 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
714 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
717 // Make sure there are no instructions between the PHI and return, or that the
718 // return is the first instruction in the block.
720 BasicBlock::iterator BI = BB->begin();
721 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
723 // Also skip over the bitcast.
728 BasicBlock::iterator BI = BB->begin();
729 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
734 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
736 SmallVector<CallInst*, 4> TailCalls;
738 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
739 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
740 // Make sure the phi value is indeed produced by the tail call.
741 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
742 TLI->mayBeEmittedAsTailCall(CI))
743 TailCalls.push_back(CI);
746 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
747 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
748 if (!VisitedBBs.insert(*PI))
751 BasicBlock::InstListType &InstList = (*PI)->getInstList();
752 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
753 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
754 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
758 CallInst *CI = dyn_cast<CallInst>(&*RI);
759 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
760 TailCalls.push_back(CI);
764 bool Changed = false;
765 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
766 CallInst *CI = TailCalls[i];
769 // Conservatively require the attributes of the call to match those of the
770 // return. Ignore noalias because it doesn't affect the call sequence.
771 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
772 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
775 // Make sure the call instruction is followed by an unconditional branch to
777 BasicBlock *CallBB = CI->getParent();
778 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
779 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
782 // Duplicate the return into CallBB.
783 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
784 ModifiedDT = Changed = true;
788 // If we eliminated all predecessors of the block, delete the block now.
789 if (Changed && pred_begin(BB) == pred_end(BB))
790 BB->eraseFromParent();
795 //===----------------------------------------------------------------------===//
796 // Memory Optimization
797 //===----------------------------------------------------------------------===//
799 /// IsNonLocalValue - Return true if the specified values are defined in a
800 /// different basic block than BB.
801 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
802 if (Instruction *I = dyn_cast<Instruction>(V))
803 return I->getParent() != BB;
807 /// OptimizeMemoryInst - Load and Store Instructions often have
808 /// addressing modes that can do significant amounts of computation. As such,
809 /// instruction selection will try to get the load or store to do as much
810 /// computation as possible for the program. The problem is that isel can only
811 /// see within a single block. As such, we sink as much legal addressing mode
812 /// stuff into the block as possible.
814 /// This method is used to optimize both load/store and inline asms with memory
816 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
820 // Try to collapse single-value PHI nodes. This is necessary to undo
821 // unprofitable PRE transformations.
822 SmallVector<Value*, 8> worklist;
823 SmallPtrSet<Value*, 16> Visited;
824 worklist.push_back(Addr);
826 // Use a worklist to iteratively look through PHI nodes, and ensure that
827 // the addressing mode obtained from the non-PHI roots of the graph
829 Value *Consensus = 0;
830 unsigned NumUsesConsensus = 0;
831 bool IsNumUsesConsensusValid = false;
832 SmallVector<Instruction*, 16> AddrModeInsts;
833 ExtAddrMode AddrMode;
834 while (!worklist.empty()) {
835 Value *V = worklist.back();
838 // Break use-def graph loops.
839 if (!Visited.insert(V)) {
844 // For a PHI node, push all of its incoming values.
845 if (PHINode *P = dyn_cast<PHINode>(V)) {
846 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
847 worklist.push_back(P->getIncomingValue(i));
851 // For non-PHIs, determine the addressing mode being computed.
852 SmallVector<Instruction*, 16> NewAddrModeInsts;
853 ExtAddrMode NewAddrMode =
854 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
855 NewAddrModeInsts, *TLI);
857 // This check is broken into two cases with very similar code to avoid using
858 // getNumUses() as much as possible. Some values have a lot of uses, so
859 // calling getNumUses() unconditionally caused a significant compile-time
863 AddrMode = NewAddrMode;
864 AddrModeInsts = NewAddrModeInsts;
866 } else if (NewAddrMode == AddrMode) {
867 if (!IsNumUsesConsensusValid) {
868 NumUsesConsensus = Consensus->getNumUses();
869 IsNumUsesConsensusValid = true;
872 // Ensure that the obtained addressing mode is equivalent to that obtained
873 // for all other roots of the PHI traversal. Also, when choosing one
874 // such root as representative, select the one with the most uses in order
875 // to keep the cost modeling heuristics in AddressingModeMatcher
877 unsigned NumUses = V->getNumUses();
878 if (NumUses > NumUsesConsensus) {
880 NumUsesConsensus = NumUses;
881 AddrModeInsts = NewAddrModeInsts;
890 // If the addressing mode couldn't be determined, or if multiple different
891 // ones were determined, bail out now.
892 if (!Consensus) return false;
894 // Check to see if any of the instructions supersumed by this addr mode are
895 // non-local to I's BB.
896 bool AnyNonLocal = false;
897 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
898 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
904 // If all the instructions matched are already in this BB, don't do anything.
906 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
910 // Insert this computation right after this user. Since our caller is
911 // scanning from the top of the BB to the bottom, reuse of the expr are
912 // guaranteed to happen later.
913 IRBuilder<> Builder(MemoryInst);
915 // Now that we determined the addressing expression we want to use and know
916 // that we have to sink it into this block. Check to see if we have already
917 // done this for some other load/store instr in this block. If so, reuse the
919 Value *&SunkAddr = SunkAddrs[Addr];
921 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
923 if (SunkAddr->getType() != Addr->getType())
924 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
926 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
929 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
933 // Start with the base register. Do this first so that subsequent address
934 // matching finds it last, which will prevent it from trying to match it
935 // as the scaled value in case it happens to be a mul. That would be
936 // problematic if we've sunk a different mul for the scale, because then
937 // we'd end up sinking both muls.
938 if (AddrMode.BaseReg) {
939 Value *V = AddrMode.BaseReg;
940 if (V->getType()->isPointerTy())
941 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
942 if (V->getType() != IntPtrTy)
943 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
947 // Add the scale value.
948 if (AddrMode.Scale) {
949 Value *V = AddrMode.ScaledReg;
950 if (V->getType() == IntPtrTy) {
952 } else if (V->getType()->isPointerTy()) {
953 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
954 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
955 cast<IntegerType>(V->getType())->getBitWidth()) {
956 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
958 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
960 if (AddrMode.Scale != 1)
961 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
964 Result = Builder.CreateAdd(Result, V, "sunkaddr");
969 // Add in the BaseGV if present.
970 if (AddrMode.BaseGV) {
971 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
973 Result = Builder.CreateAdd(Result, V, "sunkaddr");
978 // Add in the Base Offset if present.
979 if (AddrMode.BaseOffs) {
980 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
982 Result = Builder.CreateAdd(Result, V, "sunkaddr");
988 SunkAddr = Constant::getNullValue(Addr->getType());
990 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
993 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
995 // If we have no uses, recursively delete the value and all dead instructions
997 if (Repl->use_empty()) {
998 // This can cause recursive deletion, which can invalidate our iterator.
999 // Use a WeakVH to hold onto it in case this happens.
1000 WeakVH IterHandle(CurInstIterator);
1001 BasicBlock *BB = CurInstIterator->getParent();
1003 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1005 if (IterHandle != CurInstIterator) {
1006 // If the iterator instruction was recursively deleted, start over at the
1007 // start of the block.
1008 CurInstIterator = BB->begin();
1011 // This address is now available for reassignment, so erase the table
1012 // entry; we don't want to match some completely different instruction.
1013 SunkAddrs[Addr] = 0;
1020 /// OptimizeInlineAsmInst - If there are any memory operands, use
1021 /// OptimizeMemoryInst to sink their address computing into the block when
1022 /// possible / profitable.
1023 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1024 bool MadeChange = false;
1026 TargetLowering::AsmOperandInfoVector
1027 TargetConstraints = TLI->ParseConstraints(CS);
1029 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1030 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1032 // Compute the constraint code and ConstraintType to use.
1033 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1035 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1036 OpInfo.isIndirect) {
1037 Value *OpVal = CS->getArgOperand(ArgNo++);
1038 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1039 } else if (OpInfo.Type == InlineAsm::isInput)
1046 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1047 /// basic block as the load, unless conditions are unfavorable. This allows
1048 /// SelectionDAG to fold the extend into the load.
1050 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1051 // Look for a load being extended.
1052 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1053 if (!LI) return false;
1055 // If they're already in the same block, there's nothing to do.
1056 if (LI->getParent() == I->getParent())
1059 // If the load has other users and the truncate is not free, this probably
1060 // isn't worthwhile.
1061 if (!LI->hasOneUse() &&
1062 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1063 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1064 !TLI->isTruncateFree(I->getType(), LI->getType()))
1067 // Check whether the target supports casts folded into loads.
1069 if (isa<ZExtInst>(I))
1070 LType = ISD::ZEXTLOAD;
1072 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1073 LType = ISD::SEXTLOAD;
1075 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1078 // Move the extend into the same block as the load, so that SelectionDAG
1080 I->removeFromParent();
1086 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1087 BasicBlock *DefBB = I->getParent();
1089 // If the result of a {s|z}ext and its source are both live out, rewrite all
1090 // other uses of the source with result of extension.
1091 Value *Src = I->getOperand(0);
1092 if (Src->hasOneUse())
1095 // Only do this xform if truncating is free.
1096 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1099 // Only safe to perform the optimization if the source is also defined in
1101 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1104 bool DefIsLiveOut = false;
1105 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1107 Instruction *User = cast<Instruction>(*UI);
1109 // Figure out which BB this ext is used in.
1110 BasicBlock *UserBB = User->getParent();
1111 if (UserBB == DefBB) continue;
1112 DefIsLiveOut = true;
1118 // Make sure non of the uses are PHI nodes.
1119 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1121 Instruction *User = cast<Instruction>(*UI);
1122 BasicBlock *UserBB = User->getParent();
1123 if (UserBB == DefBB) continue;
1124 // Be conservative. We don't want this xform to end up introducing
1125 // reloads just before load / store instructions.
1126 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1130 // InsertedTruncs - Only insert one trunc in each block once.
1131 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1133 bool MadeChange = false;
1134 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1136 Use &TheUse = UI.getUse();
1137 Instruction *User = cast<Instruction>(*UI);
1139 // Figure out which BB this ext is used in.
1140 BasicBlock *UserBB = User->getParent();
1141 if (UserBB == DefBB) continue;
1143 // Both src and def are live in this block. Rewrite the use.
1144 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1146 if (!InsertedTrunc) {
1147 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1148 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1151 // Replace a use of the {s|z}ext source with a use of the result.
1152 TheUse = InsertedTrunc;
1160 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1161 /// turned into an explicit branch.
1162 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1163 // FIXME: This should use the same heuristics as IfConversion to determine
1164 // whether a select is better represented as a branch. This requires that
1165 // branch probability metadata is preserved for the select, which is not the
1168 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1170 // If the branch is predicted right, an out of order CPU can avoid blocking on
1171 // the compare. Emit cmovs on compares with a memory operand as branches to
1172 // avoid stalls on the load from memory. If the compare has more than one use
1173 // there's probably another cmov or setcc around so it's not worth emitting a
1178 Value *CmpOp0 = Cmp->getOperand(0);
1179 Value *CmpOp1 = Cmp->getOperand(1);
1181 // We check that the memory operand has one use to avoid uses of the loaded
1182 // value directly after the compare, making branches unprofitable.
1183 return Cmp->hasOneUse() &&
1184 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1185 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1189 /// If we have a SelectInst that will likely profit from branch prediction,
1190 /// turn it into a branch.
1191 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1192 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1194 // Can we convert the 'select' to CF ?
1195 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1198 TargetLowering::SelectSupportKind SelectKind;
1200 SelectKind = TargetLowering::VectorMaskSelect;
1201 else if (SI->getType()->isVectorTy())
1202 SelectKind = TargetLowering::ScalarCondVectorVal;
1204 SelectKind = TargetLowering::ScalarValSelect;
1206 // Do we have efficient codegen support for this kind of 'selects' ?
1207 if (TLI->isSelectSupported(SelectKind)) {
1208 // We have efficient codegen support for the select instruction.
1209 // Check if it is profitable to keep this 'select'.
1210 if (!TLI->isPredictableSelectExpensive() ||
1211 !isFormingBranchFromSelectProfitable(SI))
1217 // First, we split the block containing the select into 2 blocks.
1218 BasicBlock *StartBlock = SI->getParent();
1219 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1220 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1222 // Create a new block serving as the landing pad for the branch.
1223 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1224 NextBlock->getParent(), NextBlock);
1226 // Move the unconditional branch from the block with the select in it into our
1227 // landing pad block.
1228 StartBlock->getTerminator()->eraseFromParent();
1229 BranchInst::Create(NextBlock, SmallBlock);
1231 // Insert the real conditional branch based on the original condition.
1232 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1234 // The select itself is replaced with a PHI Node.
1235 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1237 PN->addIncoming(SI->getTrueValue(), StartBlock);
1238 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1239 SI->replaceAllUsesWith(PN);
1240 SI->eraseFromParent();
1242 // Instruct OptimizeBlock to skip to the next block.
1243 CurInstIterator = StartBlock->end();
1244 ++NumSelectsExpanded;
1248 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1249 if (PHINode *P = dyn_cast<PHINode>(I)) {
1250 // It is possible for very late stage optimizations (such as SimplifyCFG)
1251 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1252 // trivial PHI, go ahead and zap it here.
1253 if (Value *V = SimplifyInstruction(P)) {
1254 P->replaceAllUsesWith(V);
1255 P->eraseFromParent();
1262 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1263 // If the source of the cast is a constant, then this should have
1264 // already been constant folded. The only reason NOT to constant fold
1265 // it is if something (e.g. LSR) was careful to place the constant
1266 // evaluation in a block other than then one that uses it (e.g. to hoist
1267 // the address of globals out of a loop). If this is the case, we don't
1268 // want to forward-subst the cast.
1269 if (isa<Constant>(CI->getOperand(0)))
1272 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1275 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1276 bool MadeChange = MoveExtToFormExtLoad(I);
1277 return MadeChange | OptimizeExtUses(I);
1282 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1283 return OptimizeCmpExpression(CI);
1285 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1287 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1291 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1293 return OptimizeMemoryInst(I, SI->getOperand(1),
1294 SI->getOperand(0)->getType());
1298 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1299 if (GEPI->hasAllZeroIndices()) {
1300 /// The GEP operand must be a pointer, so must its result -> BitCast
1301 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1302 GEPI->getName(), GEPI);
1303 GEPI->replaceAllUsesWith(NC);
1304 GEPI->eraseFromParent();
1312 if (CallInst *CI = dyn_cast<CallInst>(I))
1313 return OptimizeCallInst(CI);
1315 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1316 return DupRetToEnableTailCallOpts(RI);
1318 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1319 return OptimizeSelectInst(SI);
1324 // In this pass we look for GEP and cast instructions that are used
1325 // across basic blocks and rewrite them to improve basic-block-at-a-time
1327 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1329 bool MadeChange = false;
1331 CurInstIterator = BB.begin();
1332 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1333 MadeChange |= OptimizeInst(CurInstIterator++);
1338 // llvm.dbg.value is far away from the value then iSel may not be able
1339 // handle it properly. iSel will drop llvm.dbg.value if it can not
1340 // find a node corresponding to the value.
1341 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1342 bool MadeChange = false;
1343 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1344 Instruction *PrevNonDbgInst = NULL;
1345 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1346 Instruction *Insn = BI; ++BI;
1347 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1349 PrevNonDbgInst = Insn;
1353 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1354 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1355 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1356 DVI->removeFromParent();
1357 if (isa<PHINode>(VI))
1358 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1360 DVI->insertAfter(VI);