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 const char *getPassName() const { return "CodeGen Prepare"; }
111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.addPreserved<DominatorTree>();
113 AU.addPreserved<ProfileInfo>();
114 AU.addRequired<TargetLibraryInfo>();
118 bool EliminateFallThrough(Function &F);
119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
122 bool OptimizeBlock(BasicBlock &BB);
123 bool OptimizeInst(Instruction *I);
124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
125 bool OptimizeInlineAsmInst(CallInst *CS);
126 bool OptimizeCallInst(CallInst *CI);
127 bool MoveExtToFormExtLoad(Instruction *I);
128 bool OptimizeExtUses(Instruction *I);
129 bool OptimizeSelectInst(SelectInst *SI);
130 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
131 bool PlaceDbgValues(Function &F);
135 char CodeGenPrepare::ID = 0;
136 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
140 "Optimize for code generation", false, false)
142 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
146 bool CodeGenPrepare::runOnFunction(Function &F) {
147 bool EverMadeChange = false;
150 TLInfo = &getAnalysis<TargetLibraryInfo>();
151 DT = getAnalysisIfAvailable<DominatorTree>();
152 PFI = getAnalysisIfAvailable<ProfileInfo>();
153 OptSize = F.getFnAttributes().hasAttribute(Attribute::OptimizeForSize);
155 /// This optimization identifies DIV instructions that can be
156 /// profitably bypassed and carried out with a shorter, faster divide.
157 if (TLI && TLI->isSlowDivBypassed()) {
158 const DenseMap<unsigned int, unsigned int> &BypassWidths =
159 TLI->getBypassSlowDivWidths();
160 for (Function::iterator I = F.begin(); I != F.end(); I++)
161 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
164 // Eliminate blocks that contain only PHI nodes and an
165 // unconditional branch.
166 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
168 // llvm.dbg.value is far away from the value then iSel may not be able
169 // handle it properly. iSel will drop llvm.dbg.value if it can not
170 // find a node corresponding to the value.
171 EverMadeChange |= PlaceDbgValues(F);
173 bool MadeChange = true;
176 for (Function::iterator I = F.begin(); I != F.end(); ) {
177 BasicBlock *BB = I++;
178 MadeChange |= OptimizeBlock(*BB);
180 EverMadeChange |= MadeChange;
185 if (!DisableBranchOpts) {
187 SmallPtrSet<BasicBlock*, 8> WorkList;
188 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
189 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
190 MadeChange |= ConstantFoldTerminator(BB, true);
191 if (!MadeChange) continue;
193 for (SmallVectorImpl<BasicBlock*>::iterator
194 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
195 if (pred_begin(*II) == pred_end(*II))
196 WorkList.insert(*II);
199 // Delete the dead blocks and any of their dead successors.
200 MadeChange |= !WorkList.empty();
201 while (!WorkList.empty()) {
202 BasicBlock *BB = *WorkList.begin();
204 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
208 for (SmallVectorImpl<BasicBlock*>::iterator
209 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
210 if (pred_begin(*II) == pred_end(*II))
211 WorkList.insert(*II);
214 // Merge pairs of basic blocks with unconditional branches, connected by
216 if (EverMadeChange || MadeChange)
217 MadeChange |= EliminateFallThrough(F);
221 EverMadeChange |= MadeChange;
224 if (ModifiedDT && DT)
225 DT->DT->recalculate(F);
227 return EverMadeChange;
230 /// EliminateFallThrough - Merge basic blocks which are connected
231 /// by a single edge, where one of the basic blocks has a single successor
232 /// pointing to the other basic block, which has a single predecessor.
233 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
234 bool Changed = false;
235 // Scan all of the blocks in the function, except for the entry block.
236 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
237 BasicBlock *BB = I++;
238 // If the destination block has a single pred, then this is a trivial
239 // edge, just collapse it.
240 BasicBlock *SinglePred = BB->getSinglePredecessor();
242 // Don't merge if BB's address is taken.
243 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
245 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
246 if (Term && !Term->isConditional()) {
248 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
249 // Remember if SinglePred was the entry block of the function.
250 // If so, we will need to move BB back to the entry position.
251 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
252 MergeBasicBlockIntoOnlyPred(BB, this);
254 if (isEntry && BB != &BB->getParent()->getEntryBlock())
255 BB->moveBefore(&BB->getParent()->getEntryBlock());
257 // We have erased a block. Update the iterator.
264 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
265 /// debug info directives, and an unconditional branch. Passes before isel
266 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
267 /// isel. Start by eliminating these blocks so we can split them the way we
269 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
270 bool MadeChange = false;
271 // Note that this intentionally skips the entry block.
272 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
273 BasicBlock *BB = I++;
275 // If this block doesn't end with an uncond branch, ignore it.
276 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
277 if (!BI || !BI->isUnconditional())
280 // If the instruction before the branch (skipping debug info) isn't a phi
281 // node, then other stuff is happening here.
282 BasicBlock::iterator BBI = BI;
283 if (BBI != BB->begin()) {
285 while (isa<DbgInfoIntrinsic>(BBI)) {
286 if (BBI == BB->begin())
290 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
294 // Do not break infinite loops.
295 BasicBlock *DestBB = BI->getSuccessor(0);
299 if (!CanMergeBlocks(BB, DestBB))
302 EliminateMostlyEmptyBlock(BB);
308 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
309 /// single uncond branch between them, and BB contains no other non-phi
311 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
312 const BasicBlock *DestBB) const {
313 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
314 // the successor. If there are more complex condition (e.g. preheaders),
315 // don't mess around with them.
316 BasicBlock::const_iterator BBI = BB->begin();
317 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
318 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
320 const Instruction *User = cast<Instruction>(*UI);
321 if (User->getParent() != DestBB || !isa<PHINode>(User))
323 // If User is inside DestBB block and it is a PHINode then check
324 // incoming value. If incoming value is not from BB then this is
325 // a complex condition (e.g. preheaders) we want to avoid here.
326 if (User->getParent() == DestBB) {
327 if (const PHINode *UPN = dyn_cast<PHINode>(User))
328 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
329 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
330 if (Insn && Insn->getParent() == BB &&
331 Insn->getParent() != UPN->getIncomingBlock(I))
338 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
339 // and DestBB may have conflicting incoming values for the block. If so, we
340 // can't merge the block.
341 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
342 if (!DestBBPN) return true; // no conflict.
344 // Collect the preds of BB.
345 SmallPtrSet<const BasicBlock*, 16> BBPreds;
346 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
347 // It is faster to get preds from a PHI than with pred_iterator.
348 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
349 BBPreds.insert(BBPN->getIncomingBlock(i));
351 BBPreds.insert(pred_begin(BB), pred_end(BB));
354 // Walk the preds of DestBB.
355 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
356 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
357 if (BBPreds.count(Pred)) { // Common predecessor?
358 BBI = DestBB->begin();
359 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
360 const Value *V1 = PN->getIncomingValueForBlock(Pred);
361 const Value *V2 = PN->getIncomingValueForBlock(BB);
363 // If V2 is a phi node in BB, look up what the mapped value will be.
364 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
365 if (V2PN->getParent() == BB)
366 V2 = V2PN->getIncomingValueForBlock(Pred);
368 // If there is a conflict, bail out.
369 if (V1 != V2) return false;
378 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
379 /// an unconditional branch in it.
380 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
381 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
382 BasicBlock *DestBB = BI->getSuccessor(0);
384 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
386 // If the destination block has a single pred, then this is a trivial edge,
388 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
389 if (SinglePred != DestBB) {
390 // Remember if SinglePred was the entry block of the function. If so, we
391 // will need to move BB back to the entry position.
392 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
393 MergeBasicBlockIntoOnlyPred(DestBB, this);
395 if (isEntry && BB != &BB->getParent()->getEntryBlock())
396 BB->moveBefore(&BB->getParent()->getEntryBlock());
398 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
403 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
404 // to handle the new incoming edges it is about to have.
406 for (BasicBlock::iterator BBI = DestBB->begin();
407 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
408 // Remove the incoming value for BB, and remember it.
409 Value *InVal = PN->removeIncomingValue(BB, false);
411 // Two options: either the InVal is a phi node defined in BB or it is some
412 // value that dominates BB.
413 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
414 if (InValPhi && InValPhi->getParent() == BB) {
415 // Add all of the input values of the input PHI as inputs of this phi.
416 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
417 PN->addIncoming(InValPhi->getIncomingValue(i),
418 InValPhi->getIncomingBlock(i));
420 // Otherwise, add one instance of the dominating value for each edge that
421 // we will be adding.
422 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
423 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
424 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
426 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
427 PN->addIncoming(InVal, *PI);
432 // The PHIs are now updated, change everything that refers to BB to use
433 // DestBB and remove BB.
434 BB->replaceAllUsesWith(DestBB);
435 if (DT && !ModifiedDT) {
436 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
437 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
438 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
439 DT->changeImmediateDominator(DestBB, NewIDom);
443 PFI->replaceAllUses(BB, DestBB);
444 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
446 BB->eraseFromParent();
449 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
452 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
453 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
454 /// sink it into user blocks to reduce the number of virtual
455 /// registers that must be created and coalesced.
457 /// Return true if any changes are made.
459 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
460 // If this is a noop copy,
461 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
462 EVT DstVT = TLI.getValueType(CI->getType());
464 // This is an fp<->int conversion?
465 if (SrcVT.isInteger() != DstVT.isInteger())
468 // If this is an extension, it will be a zero or sign extension, which
470 if (SrcVT.bitsLT(DstVT)) return false;
472 // If these values will be promoted, find out what they will be promoted
473 // to. This helps us consider truncates on PPC as noop copies when they
475 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
476 TargetLowering::TypePromoteInteger)
477 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
478 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
479 TargetLowering::TypePromoteInteger)
480 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
482 // If, after promotion, these are the same types, this is a noop copy.
486 BasicBlock *DefBB = CI->getParent();
488 /// InsertedCasts - Only insert a cast in each block once.
489 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
491 bool MadeChange = false;
492 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
494 Use &TheUse = UI.getUse();
495 Instruction *User = cast<Instruction>(*UI);
497 // Figure out which BB this cast is used in. For PHI's this is the
498 // appropriate predecessor block.
499 BasicBlock *UserBB = User->getParent();
500 if (PHINode *PN = dyn_cast<PHINode>(User)) {
501 UserBB = PN->getIncomingBlock(UI);
504 // Preincrement use iterator so we don't invalidate it.
507 // If this user is in the same block as the cast, don't change the cast.
508 if (UserBB == DefBB) continue;
510 // If we have already inserted a cast into this block, use it.
511 CastInst *&InsertedCast = InsertedCasts[UserBB];
514 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
516 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
521 // Replace a use of the cast with a use of the new cast.
522 TheUse = InsertedCast;
526 // If we removed all uses, nuke the cast.
527 if (CI->use_empty()) {
528 CI->eraseFromParent();
535 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
536 /// the number of virtual registers that must be created and coalesced. This is
537 /// a clear win except on targets with multiple condition code registers
538 /// (PowerPC), where it might lose; some adjustment may be wanted there.
540 /// Return true if any changes are made.
541 static bool OptimizeCmpExpression(CmpInst *CI) {
542 BasicBlock *DefBB = CI->getParent();
544 /// InsertedCmp - Only insert a cmp in each block once.
545 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
547 bool MadeChange = false;
548 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
550 Use &TheUse = UI.getUse();
551 Instruction *User = cast<Instruction>(*UI);
553 // Preincrement use iterator so we don't invalidate it.
556 // Don't bother for PHI nodes.
557 if (isa<PHINode>(User))
560 // Figure out which BB this cmp is used in.
561 BasicBlock *UserBB = User->getParent();
563 // If this user is in the same block as the cmp, don't change the cmp.
564 if (UserBB == DefBB) continue;
566 // If we have already inserted a cmp into this block, use it.
567 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
570 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
572 CmpInst::Create(CI->getOpcode(),
573 CI->getPredicate(), CI->getOperand(0),
574 CI->getOperand(1), "", InsertPt);
578 // Replace a use of the cmp with a use of the new cmp.
579 TheUse = InsertedCmp;
583 // If we removed all uses, nuke the cmp.
585 CI->eraseFromParent();
591 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
593 void replaceCall(Value *With) {
594 CI->replaceAllUsesWith(With);
595 CI->eraseFromParent();
597 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
598 if (ConstantInt *SizeCI =
599 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
600 return SizeCI->isAllOnesValue();
604 } // end anonymous namespace
606 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
607 BasicBlock *BB = CI->getParent();
609 // Lower inline assembly if we can.
610 // If we found an inline asm expession, and if the target knows how to
611 // lower it to normal LLVM code, do so now.
612 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
613 if (TLI->ExpandInlineAsm(CI)) {
614 // Avoid invalidating the iterator.
615 CurInstIterator = BB->begin();
616 // Avoid processing instructions out of order, which could cause
617 // reuse before a value is defined.
621 // Sink address computing for memory operands into the block.
622 if (OptimizeInlineAsmInst(CI))
626 // Lower all uses of llvm.objectsize.*
627 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
628 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
629 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
630 Type *ReturnTy = CI->getType();
631 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
633 // Substituting this can cause recursive simplifications, which can
634 // invalidate our iterator. Use a WeakVH to hold onto it in case this
636 WeakVH IterHandle(CurInstIterator);
638 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
639 TLInfo, ModifiedDT ? 0 : DT);
641 // If the iterator instruction was recursively deleted, start over at the
642 // start of the block.
643 if (IterHandle != CurInstIterator) {
644 CurInstIterator = BB->begin();
651 SmallVector<Value*, 2> PtrOps;
653 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
654 while (!PtrOps.empty())
655 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
659 // From here on out we're working with named functions.
660 if (CI->getCalledFunction() == 0) return false;
662 // We'll need DataLayout from here on out.
663 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
664 if (!TD) return false;
666 // Lower all default uses of _chk calls. This is very similar
667 // to what InstCombineCalls does, but here we are only lowering calls
668 // that have the default "don't know" as the objectsize. Anything else
669 // should be left alone.
670 CodeGenPrepareFortifiedLibCalls Simplifier;
671 return Simplifier.fold(CI, TD, TLInfo);
674 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
675 /// instructions to the predecessor to enable tail call optimizations. The
676 /// case it is currently looking for is:
679 /// %tmp0 = tail call i32 @f0()
682 /// %tmp1 = tail call i32 @f1()
685 /// %tmp2 = tail call i32 @f2()
688 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
696 /// %tmp0 = tail call i32 @f0()
699 /// %tmp1 = tail call i32 @f1()
702 /// %tmp2 = tail call i32 @f2()
705 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
709 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
714 BitCastInst *BCI = 0;
715 Value *V = RI->getReturnValue();
717 BCI = dyn_cast<BitCastInst>(V);
719 V = BCI->getOperand(0);
721 PN = dyn_cast<PHINode>(V);
726 if (PN && PN->getParent() != BB)
729 // It's not safe to eliminate the sign / zero extension of the return value.
730 // See llvm::isInTailCallPosition().
731 const Function *F = BB->getParent();
732 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
733 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
734 CallerRetAttr.hasAttribute(Attribute::SExt))
737 // Make sure there are no instructions between the PHI and return, or that the
738 // return is the first instruction in the block.
740 BasicBlock::iterator BI = BB->begin();
741 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
743 // Also skip over the bitcast.
748 BasicBlock::iterator BI = BB->begin();
749 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
754 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
756 SmallVector<CallInst*, 4> TailCalls;
758 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
759 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
760 // Make sure the phi value is indeed produced by the tail call.
761 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
762 TLI->mayBeEmittedAsTailCall(CI))
763 TailCalls.push_back(CI);
766 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
767 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
768 if (!VisitedBBs.insert(*PI))
771 BasicBlock::InstListType &InstList = (*PI)->getInstList();
772 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
773 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
774 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
778 CallInst *CI = dyn_cast<CallInst>(&*RI);
779 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
780 TailCalls.push_back(CI);
784 bool Changed = false;
785 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
786 CallInst *CI = TailCalls[i];
789 // Conservatively require the attributes of the call to match those of the
790 // return. Ignore noalias because it doesn't affect the call sequence.
791 Attribute CalleeRetAttr = CS.getAttributes().getRetAttributes();
792 if (AttrBuilder(CalleeRetAttr).
793 removeAttribute(Attribute::NoAlias) !=
794 AttrBuilder(CallerRetAttr).
795 removeAttribute(Attribute::NoAlias))
798 // Make sure the call instruction is followed by an unconditional branch to
800 BasicBlock *CallBB = CI->getParent();
801 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
802 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
805 // Duplicate the return into CallBB.
806 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
807 ModifiedDT = Changed = true;
811 // If we eliminated all predecessors of the block, delete the block now.
812 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
813 BB->eraseFromParent();
818 //===----------------------------------------------------------------------===//
819 // Memory Optimization
820 //===----------------------------------------------------------------------===//
822 /// IsNonLocalValue - Return true if the specified values are defined in a
823 /// different basic block than BB.
824 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
825 if (Instruction *I = dyn_cast<Instruction>(V))
826 return I->getParent() != BB;
830 /// OptimizeMemoryInst - Load and Store Instructions often have
831 /// addressing modes that can do significant amounts of computation. As such,
832 /// instruction selection will try to get the load or store to do as much
833 /// computation as possible for the program. The problem is that isel can only
834 /// see within a single block. As such, we sink as much legal addressing mode
835 /// stuff into the block as possible.
837 /// This method is used to optimize both load/store and inline asms with memory
839 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
843 // Try to collapse single-value PHI nodes. This is necessary to undo
844 // unprofitable PRE transformations.
845 SmallVector<Value*, 8> worklist;
846 SmallPtrSet<Value*, 16> Visited;
847 worklist.push_back(Addr);
849 // Use a worklist to iteratively look through PHI nodes, and ensure that
850 // the addressing mode obtained from the non-PHI roots of the graph
852 Value *Consensus = 0;
853 unsigned NumUsesConsensus = 0;
854 bool IsNumUsesConsensusValid = false;
855 SmallVector<Instruction*, 16> AddrModeInsts;
856 ExtAddrMode AddrMode;
857 while (!worklist.empty()) {
858 Value *V = worklist.back();
861 // Break use-def graph loops.
862 if (!Visited.insert(V)) {
867 // For a PHI node, push all of its incoming values.
868 if (PHINode *P = dyn_cast<PHINode>(V)) {
869 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
870 worklist.push_back(P->getIncomingValue(i));
874 // For non-PHIs, determine the addressing mode being computed.
875 SmallVector<Instruction*, 16> NewAddrModeInsts;
876 ExtAddrMode NewAddrMode =
877 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
878 NewAddrModeInsts, *TLI);
880 // This check is broken into two cases with very similar code to avoid using
881 // getNumUses() as much as possible. Some values have a lot of uses, so
882 // calling getNumUses() unconditionally caused a significant compile-time
886 AddrMode = NewAddrMode;
887 AddrModeInsts = NewAddrModeInsts;
889 } else if (NewAddrMode == AddrMode) {
890 if (!IsNumUsesConsensusValid) {
891 NumUsesConsensus = Consensus->getNumUses();
892 IsNumUsesConsensusValid = true;
895 // Ensure that the obtained addressing mode is equivalent to that obtained
896 // for all other roots of the PHI traversal. Also, when choosing one
897 // such root as representative, select the one with the most uses in order
898 // to keep the cost modeling heuristics in AddressingModeMatcher
900 unsigned NumUses = V->getNumUses();
901 if (NumUses > NumUsesConsensus) {
903 NumUsesConsensus = NumUses;
904 AddrModeInsts = NewAddrModeInsts;
913 // If the addressing mode couldn't be determined, or if multiple different
914 // ones were determined, bail out now.
915 if (!Consensus) return false;
917 // Check to see if any of the instructions supersumed by this addr mode are
918 // non-local to I's BB.
919 bool AnyNonLocal = false;
920 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
921 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
927 // If all the instructions matched are already in this BB, don't do anything.
929 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
933 // Insert this computation right after this user. Since our caller is
934 // scanning from the top of the BB to the bottom, reuse of the expr are
935 // guaranteed to happen later.
936 IRBuilder<> Builder(MemoryInst);
938 // Now that we determined the addressing expression we want to use and know
939 // that we have to sink it into this block. Check to see if we have already
940 // done this for some other load/store instr in this block. If so, reuse the
942 Value *&SunkAddr = SunkAddrs[Addr];
944 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
946 if (SunkAddr->getType() != Addr->getType())
947 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
949 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
952 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
956 // Start with the base register. Do this first so that subsequent address
957 // matching finds it last, which will prevent it from trying to match it
958 // as the scaled value in case it happens to be a mul. That would be
959 // problematic if we've sunk a different mul for the scale, because then
960 // we'd end up sinking both muls.
961 if (AddrMode.BaseReg) {
962 Value *V = AddrMode.BaseReg;
963 if (V->getType()->isPointerTy())
964 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
965 if (V->getType() != IntPtrTy)
966 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
970 // Add the scale value.
971 if (AddrMode.Scale) {
972 Value *V = AddrMode.ScaledReg;
973 if (V->getType() == IntPtrTy) {
975 } else if (V->getType()->isPointerTy()) {
976 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
977 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
978 cast<IntegerType>(V->getType())->getBitWidth()) {
979 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
981 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
983 if (AddrMode.Scale != 1)
984 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
987 Result = Builder.CreateAdd(Result, V, "sunkaddr");
992 // Add in the BaseGV if present.
993 if (AddrMode.BaseGV) {
994 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
996 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1001 // Add in the Base Offset if present.
1002 if (AddrMode.BaseOffs) {
1003 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1005 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1011 SunkAddr = Constant::getNullValue(Addr->getType());
1013 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1016 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1018 // If we have no uses, recursively delete the value and all dead instructions
1020 if (Repl->use_empty()) {
1021 // This can cause recursive deletion, which can invalidate our iterator.
1022 // Use a WeakVH to hold onto it in case this happens.
1023 WeakVH IterHandle(CurInstIterator);
1024 BasicBlock *BB = CurInstIterator->getParent();
1026 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1028 if (IterHandle != CurInstIterator) {
1029 // If the iterator instruction was recursively deleted, start over at the
1030 // start of the block.
1031 CurInstIterator = BB->begin();
1034 // This address is now available for reassignment, so erase the table
1035 // entry; we don't want to match some completely different instruction.
1036 SunkAddrs[Addr] = 0;
1043 /// OptimizeInlineAsmInst - If there are any memory operands, use
1044 /// OptimizeMemoryInst to sink their address computing into the block when
1045 /// possible / profitable.
1046 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1047 bool MadeChange = false;
1049 TargetLowering::AsmOperandInfoVector
1050 TargetConstraints = TLI->ParseConstraints(CS);
1052 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1053 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1055 // Compute the constraint code and ConstraintType to use.
1056 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1058 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1059 OpInfo.isIndirect) {
1060 Value *OpVal = CS->getArgOperand(ArgNo++);
1061 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1062 } else if (OpInfo.Type == InlineAsm::isInput)
1069 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1070 /// basic block as the load, unless conditions are unfavorable. This allows
1071 /// SelectionDAG to fold the extend into the load.
1073 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1074 // Look for a load being extended.
1075 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1076 if (!LI) return false;
1078 // If they're already in the same block, there's nothing to do.
1079 if (LI->getParent() == I->getParent())
1082 // If the load has other users and the truncate is not free, this probably
1083 // isn't worthwhile.
1084 if (!LI->hasOneUse() &&
1085 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1086 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1087 !TLI->isTruncateFree(I->getType(), LI->getType()))
1090 // Check whether the target supports casts folded into loads.
1092 if (isa<ZExtInst>(I))
1093 LType = ISD::ZEXTLOAD;
1095 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1096 LType = ISD::SEXTLOAD;
1098 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1101 // Move the extend into the same block as the load, so that SelectionDAG
1103 I->removeFromParent();
1109 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1110 BasicBlock *DefBB = I->getParent();
1112 // If the result of a {s|z}ext and its source are both live out, rewrite all
1113 // other uses of the source with result of extension.
1114 Value *Src = I->getOperand(0);
1115 if (Src->hasOneUse())
1118 // Only do this xform if truncating is free.
1119 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1122 // Only safe to perform the optimization if the source is also defined in
1124 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1127 bool DefIsLiveOut = false;
1128 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1130 Instruction *User = cast<Instruction>(*UI);
1132 // Figure out which BB this ext is used in.
1133 BasicBlock *UserBB = User->getParent();
1134 if (UserBB == DefBB) continue;
1135 DefIsLiveOut = true;
1141 // Make sure non of the uses are PHI nodes.
1142 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1144 Instruction *User = cast<Instruction>(*UI);
1145 BasicBlock *UserBB = User->getParent();
1146 if (UserBB == DefBB) continue;
1147 // Be conservative. We don't want this xform to end up introducing
1148 // reloads just before load / store instructions.
1149 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1153 // InsertedTruncs - Only insert one trunc in each block once.
1154 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1156 bool MadeChange = false;
1157 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1159 Use &TheUse = UI.getUse();
1160 Instruction *User = cast<Instruction>(*UI);
1162 // Figure out which BB this ext is used in.
1163 BasicBlock *UserBB = User->getParent();
1164 if (UserBB == DefBB) continue;
1166 // Both src and def are live in this block. Rewrite the use.
1167 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1169 if (!InsertedTrunc) {
1170 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1171 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1174 // Replace a use of the {s|z}ext source with a use of the result.
1175 TheUse = InsertedTrunc;
1183 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1184 /// turned into an explicit branch.
1185 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1186 // FIXME: This should use the same heuristics as IfConversion to determine
1187 // whether a select is better represented as a branch. This requires that
1188 // branch probability metadata is preserved for the select, which is not the
1191 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1193 // If the branch is predicted right, an out of order CPU can avoid blocking on
1194 // the compare. Emit cmovs on compares with a memory operand as branches to
1195 // avoid stalls on the load from memory. If the compare has more than one use
1196 // there's probably another cmov or setcc around so it's not worth emitting a
1201 Value *CmpOp0 = Cmp->getOperand(0);
1202 Value *CmpOp1 = Cmp->getOperand(1);
1204 // We check that the memory operand has one use to avoid uses of the loaded
1205 // value directly after the compare, making branches unprofitable.
1206 return Cmp->hasOneUse() &&
1207 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1208 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1212 /// If we have a SelectInst that will likely profit from branch prediction,
1213 /// turn it into a branch.
1214 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1215 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1217 // Can we convert the 'select' to CF ?
1218 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1221 TargetLowering::SelectSupportKind SelectKind;
1223 SelectKind = TargetLowering::VectorMaskSelect;
1224 else if (SI->getType()->isVectorTy())
1225 SelectKind = TargetLowering::ScalarCondVectorVal;
1227 SelectKind = TargetLowering::ScalarValSelect;
1229 // Do we have efficient codegen support for this kind of 'selects' ?
1230 if (TLI->isSelectSupported(SelectKind)) {
1231 // We have efficient codegen support for the select instruction.
1232 // Check if it is profitable to keep this 'select'.
1233 if (!TLI->isPredictableSelectExpensive() ||
1234 !isFormingBranchFromSelectProfitable(SI))
1240 // First, we split the block containing the select into 2 blocks.
1241 BasicBlock *StartBlock = SI->getParent();
1242 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1243 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1245 // Create a new block serving as the landing pad for the branch.
1246 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1247 NextBlock->getParent(), NextBlock);
1249 // Move the unconditional branch from the block with the select in it into our
1250 // landing pad block.
1251 StartBlock->getTerminator()->eraseFromParent();
1252 BranchInst::Create(NextBlock, SmallBlock);
1254 // Insert the real conditional branch based on the original condition.
1255 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1257 // The select itself is replaced with a PHI Node.
1258 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1260 PN->addIncoming(SI->getTrueValue(), StartBlock);
1261 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1262 SI->replaceAllUsesWith(PN);
1263 SI->eraseFromParent();
1265 // Instruct OptimizeBlock to skip to the next block.
1266 CurInstIterator = StartBlock->end();
1267 ++NumSelectsExpanded;
1271 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1272 if (PHINode *P = dyn_cast<PHINode>(I)) {
1273 // It is possible for very late stage optimizations (such as SimplifyCFG)
1274 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1275 // trivial PHI, go ahead and zap it here.
1276 if (Value *V = SimplifyInstruction(P)) {
1277 P->replaceAllUsesWith(V);
1278 P->eraseFromParent();
1285 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1286 // If the source of the cast is a constant, then this should have
1287 // already been constant folded. The only reason NOT to constant fold
1288 // it is if something (e.g. LSR) was careful to place the constant
1289 // evaluation in a block other than then one that uses it (e.g. to hoist
1290 // the address of globals out of a loop). If this is the case, we don't
1291 // want to forward-subst the cast.
1292 if (isa<Constant>(CI->getOperand(0)))
1295 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1298 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1299 bool MadeChange = MoveExtToFormExtLoad(I);
1300 return MadeChange | OptimizeExtUses(I);
1305 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1306 return OptimizeCmpExpression(CI);
1308 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1310 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1314 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1316 return OptimizeMemoryInst(I, SI->getOperand(1),
1317 SI->getOperand(0)->getType());
1321 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1322 if (GEPI->hasAllZeroIndices()) {
1323 /// The GEP operand must be a pointer, so must its result -> BitCast
1324 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1325 GEPI->getName(), GEPI);
1326 GEPI->replaceAllUsesWith(NC);
1327 GEPI->eraseFromParent();
1335 if (CallInst *CI = dyn_cast<CallInst>(I))
1336 return OptimizeCallInst(CI);
1338 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1339 return OptimizeSelectInst(SI);
1344 // In this pass we look for GEP and cast instructions that are used
1345 // across basic blocks and rewrite them to improve basic-block-at-a-time
1347 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1349 bool MadeChange = false;
1351 CurInstIterator = BB.begin();
1352 while (CurInstIterator != BB.end())
1353 MadeChange |= OptimizeInst(CurInstIterator++);
1355 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1360 // llvm.dbg.value is far away from the value then iSel may not be able
1361 // handle it properly. iSel will drop llvm.dbg.value if it can not
1362 // find a node corresponding to the value.
1363 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1364 bool MadeChange = false;
1365 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1366 Instruction *PrevNonDbgInst = NULL;
1367 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1368 Instruction *Insn = BI; ++BI;
1369 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1371 PrevNonDbgInst = Insn;
1375 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1376 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1377 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1378 DVI->removeFromParent();
1379 if (isa<PHINode>(VI))
1380 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1382 DVI->insertAfter(VI);