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/ADT/ValueMap.h"
22 #include "llvm/Analysis/DominatorInternals.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Support/PatternMatch.h"
39 #include "llvm/Support/ValueHandle.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/BuildLibCalls.h"
45 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
46 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm::PatternMatch;
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
59 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
65 static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69 static cl::opt<bool> DisableSelectToBranch(
70 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71 cl::desc("Disable select to branch conversion."));
74 class CodeGenPrepare : public FunctionPass {
75 /// TLI - Keep a pointer of a TargetLowering to consult for determining
76 /// transformation profitability.
77 const TargetMachine *TM;
78 const TargetLowering *TLI;
79 const TargetLibraryInfo *TLInfo;
82 /// CurInstIterator - As we scan instructions optimizing them, this is the
83 /// next instruction to optimize. Xforms that can invalidate this should
85 BasicBlock::iterator CurInstIterator;
87 /// Keeps track of non-local addresses that have been sunk into a block.
88 /// This allows us to avoid inserting duplicate code for blocks with
89 /// multiple load/stores of the same address.
90 ValueMap<Value*, Value*> SunkAddrs;
92 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
96 /// OptSize - True if optimizing for size.
100 static char ID; // Pass identification, replacement for typeid
101 explicit CodeGenPrepare(const TargetMachine *TM = 0)
102 : FunctionPass(ID), TM(TM), TLI(0) {
103 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
105 bool runOnFunction(Function &F);
107 const char *getPassName() const { return "CodeGen Prepare"; }
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addPreserved<DominatorTree>();
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(BasicBlock *BB);
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 TargetMachine *TM) {
140 return new CodeGenPrepare(TM);
143 bool CodeGenPrepare::runOnFunction(Function &F) {
144 bool EverMadeChange = false;
147 if (TM) TLI = TM->getTargetLowering();
148 TLInfo = &getAnalysis<TargetLibraryInfo>();
149 DT = getAnalysisIfAvailable<DominatorTree>();
150 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
151 Attribute::OptimizeForSize);
153 /// This optimization identifies DIV instructions that can be
154 /// profitably bypassed and carried out with a shorter, faster divide.
155 if (!OptSize && 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);
440 BB->eraseFromParent();
443 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
446 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
447 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
448 /// sink it into user blocks to reduce the number of virtual
449 /// registers that must be created and coalesced.
451 /// Return true if any changes are made.
453 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
454 // If this is a noop copy,
455 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
456 EVT DstVT = TLI.getValueType(CI->getType());
458 // This is an fp<->int conversion?
459 if (SrcVT.isInteger() != DstVT.isInteger())
462 // If this is an extension, it will be a zero or sign extension, which
464 if (SrcVT.bitsLT(DstVT)) return false;
466 // If these values will be promoted, find out what they will be promoted
467 // to. This helps us consider truncates on PPC as noop copies when they
469 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
470 TargetLowering::TypePromoteInteger)
471 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
472 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
473 TargetLowering::TypePromoteInteger)
474 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
476 // If, after promotion, these are the same types, this is a noop copy.
480 BasicBlock *DefBB = CI->getParent();
482 /// InsertedCasts - Only insert a cast in each block once.
483 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
485 bool MadeChange = false;
486 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
488 Use &TheUse = UI.getUse();
489 Instruction *User = cast<Instruction>(*UI);
491 // Figure out which BB this cast is used in. For PHI's this is the
492 // appropriate predecessor block.
493 BasicBlock *UserBB = User->getParent();
494 if (PHINode *PN = dyn_cast<PHINode>(User)) {
495 UserBB = PN->getIncomingBlock(UI);
498 // Preincrement use iterator so we don't invalidate it.
501 // If this user is in the same block as the cast, don't change the cast.
502 if (UserBB == DefBB) continue;
504 // If we have already inserted a cast into this block, use it.
505 CastInst *&InsertedCast = InsertedCasts[UserBB];
508 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
510 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
515 // Replace a use of the cast with a use of the new cast.
516 TheUse = InsertedCast;
520 // If we removed all uses, nuke the cast.
521 if (CI->use_empty()) {
522 CI->eraseFromParent();
529 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
530 /// the number of virtual registers that must be created and coalesced. This is
531 /// a clear win except on targets with multiple condition code registers
532 /// (PowerPC), where it might lose; some adjustment may be wanted there.
534 /// Return true if any changes are made.
535 static bool OptimizeCmpExpression(CmpInst *CI) {
536 BasicBlock *DefBB = CI->getParent();
538 /// InsertedCmp - Only insert a cmp in each block once.
539 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
541 bool MadeChange = false;
542 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
544 Use &TheUse = UI.getUse();
545 Instruction *User = cast<Instruction>(*UI);
547 // Preincrement use iterator so we don't invalidate it.
550 // Don't bother for PHI nodes.
551 if (isa<PHINode>(User))
554 // Figure out which BB this cmp is used in.
555 BasicBlock *UserBB = User->getParent();
557 // If this user is in the same block as the cmp, don't change the cmp.
558 if (UserBB == DefBB) continue;
560 // If we have already inserted a cmp into this block, use it.
561 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
564 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
566 CmpInst::Create(CI->getOpcode(),
567 CI->getPredicate(), CI->getOperand(0),
568 CI->getOperand(1), "", InsertPt);
572 // Replace a use of the cmp with a use of the new cmp.
573 TheUse = InsertedCmp;
577 // If we removed all uses, nuke the cmp.
579 CI->eraseFromParent();
585 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
587 void replaceCall(Value *With) {
588 CI->replaceAllUsesWith(With);
589 CI->eraseFromParent();
591 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
592 if (ConstantInt *SizeCI =
593 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
594 return SizeCI->isAllOnesValue();
598 } // end anonymous namespace
600 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
601 BasicBlock *BB = CI->getParent();
603 // Lower inline assembly if we can.
604 // If we found an inline asm expession, and if the target knows how to
605 // lower it to normal LLVM code, do so now.
606 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
607 if (TLI->ExpandInlineAsm(CI)) {
608 // Avoid invalidating the iterator.
609 CurInstIterator = BB->begin();
610 // Avoid processing instructions out of order, which could cause
611 // reuse before a value is defined.
615 // Sink address computing for memory operands into the block.
616 if (OptimizeInlineAsmInst(CI))
620 // Lower all uses of llvm.objectsize.*
621 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
622 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
623 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
624 Type *ReturnTy = CI->getType();
625 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
627 // Substituting this can cause recursive simplifications, which can
628 // invalidate our iterator. Use a WeakVH to hold onto it in case this
630 WeakVH IterHandle(CurInstIterator);
632 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
633 TLInfo, ModifiedDT ? 0 : DT);
635 // If the iterator instruction was recursively deleted, start over at the
636 // start of the block.
637 if (IterHandle != CurInstIterator) {
638 CurInstIterator = BB->begin();
645 SmallVector<Value*, 2> PtrOps;
647 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
648 while (!PtrOps.empty())
649 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
653 // From here on out we're working with named functions.
654 if (CI->getCalledFunction() == 0) return false;
656 // We'll need DataLayout from here on out.
657 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
658 if (!TD) return false;
660 // Lower all default uses of _chk calls. This is very similar
661 // to what InstCombineCalls does, but here we are only lowering calls
662 // that have the default "don't know" as the objectsize. Anything else
663 // should be left alone.
664 CodeGenPrepareFortifiedLibCalls Simplifier;
665 return Simplifier.fold(CI, TD, TLInfo);
668 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
669 /// instructions to the predecessor to enable tail call optimizations. The
670 /// case it is currently looking for is:
673 /// %tmp0 = tail call i32 @f0()
676 /// %tmp1 = tail call i32 @f1()
679 /// %tmp2 = tail call i32 @f2()
682 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
690 /// %tmp0 = tail call i32 @f0()
693 /// %tmp1 = tail call i32 @f1()
696 /// %tmp2 = tail call i32 @f2()
699 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
703 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
708 BitCastInst *BCI = 0;
709 Value *V = RI->getReturnValue();
711 BCI = dyn_cast<BitCastInst>(V);
713 V = BCI->getOperand(0);
715 PN = dyn_cast<PHINode>(V);
720 if (PN && PN->getParent() != BB)
723 // It's not safe to eliminate the sign / zero extension of the return value.
724 // See llvm::isInTailCallPosition().
725 const Function *F = BB->getParent();
726 AttributeSet CallerAttrs = F->getAttributes();
727 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
728 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
731 // Make sure there are no instructions between the PHI and return, or that the
732 // return is the first instruction in the block.
734 BasicBlock::iterator BI = BB->begin();
735 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
737 // Also skip over the bitcast.
742 BasicBlock::iterator BI = BB->begin();
743 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
748 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
750 SmallVector<CallInst*, 4> TailCalls;
752 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
753 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
754 // Make sure the phi value is indeed produced by the tail call.
755 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
756 TLI->mayBeEmittedAsTailCall(CI))
757 TailCalls.push_back(CI);
760 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
761 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
762 if (!VisitedBBs.insert(*PI))
765 BasicBlock::InstListType &InstList = (*PI)->getInstList();
766 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
767 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
768 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
772 CallInst *CI = dyn_cast<CallInst>(&*RI);
773 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
774 TailCalls.push_back(CI);
778 bool Changed = false;
779 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
780 CallInst *CI = TailCalls[i];
783 // Conservatively require the attributes of the call to match those of the
784 // return. Ignore noalias because it doesn't affect the call sequence.
785 AttributeSet CalleeAttrs = CS.getAttributes();
786 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
787 removeAttribute(Attribute::NoAlias) !=
788 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
789 removeAttribute(Attribute::NoAlias))
792 // Make sure the call instruction is followed by an unconditional branch to
794 BasicBlock *CallBB = CI->getParent();
795 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
796 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
799 // Duplicate the return into CallBB.
800 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
801 ModifiedDT = Changed = true;
805 // If we eliminated all predecessors of the block, delete the block now.
806 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
807 BB->eraseFromParent();
812 //===----------------------------------------------------------------------===//
813 // Memory Optimization
814 //===----------------------------------------------------------------------===//
818 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
819 /// which holds actual Value*'s for register values.
820 struct ExtAddrMode : public TargetLowering::AddrMode {
823 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
824 void print(raw_ostream &OS) const;
827 bool operator==(const ExtAddrMode& O) const {
828 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
829 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
830 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
835 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
841 void ExtAddrMode::print(raw_ostream &OS) const {
842 bool NeedPlus = false;
845 OS << (NeedPlus ? " + " : "")
847 BaseGV->printAsOperand(OS, /*PrintType=*/false);
852 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
855 OS << (NeedPlus ? " + " : "")
857 BaseReg->printAsOperand(OS, /*PrintType=*/false);
861 OS << (NeedPlus ? " + " : "")
863 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
869 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
870 void ExtAddrMode::dump() const {
877 /// \brief A helper class for matching addressing modes.
879 /// This encapsulates the logic for matching the target-legal addressing modes.
880 class AddressingModeMatcher {
881 SmallVectorImpl<Instruction*> &AddrModeInsts;
882 const TargetLowering &TLI;
884 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
885 /// the memory instruction that we're computing this address for.
887 Instruction *MemoryInst;
889 /// AddrMode - This is the addressing mode that we're building up. This is
890 /// part of the return value of this addressing mode matching stuff.
891 ExtAddrMode &AddrMode;
893 /// IgnoreProfitability - This is set to true when we should not do
894 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
895 /// always returns true.
896 bool IgnoreProfitability;
898 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
899 const TargetLowering &T, Type *AT,
900 Instruction *MI, ExtAddrMode &AM)
901 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
902 IgnoreProfitability = false;
906 /// Match - Find the maximal addressing mode that a load/store of V can fold,
907 /// give an access type of AccessTy. This returns a list of involved
908 /// instructions in AddrModeInsts.
909 static ExtAddrMode Match(Value *V, Type *AccessTy,
910 Instruction *MemoryInst,
911 SmallVectorImpl<Instruction*> &AddrModeInsts,
912 const TargetLowering &TLI) {
916 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
917 MemoryInst, Result).MatchAddr(V, 0);
918 (void)Success; assert(Success && "Couldn't select *anything*?");
922 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
923 bool MatchAddr(Value *V, unsigned Depth);
924 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
925 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
926 ExtAddrMode &AMBefore,
927 ExtAddrMode &AMAfter);
928 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
931 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
932 /// Return true and update AddrMode if this addr mode is legal for the target,
934 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
936 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
937 // mode. Just process that directly.
939 return MatchAddr(ScaleReg, Depth);
941 // If the scale is 0, it takes nothing to add this.
945 // If we already have a scale of this value, we can add to it, otherwise, we
946 // need an available scale field.
947 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
950 ExtAddrMode TestAddrMode = AddrMode;
952 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
953 // [A+B + A*7] -> [B+A*8].
954 TestAddrMode.Scale += Scale;
955 TestAddrMode.ScaledReg = ScaleReg;
957 // If the new address isn't legal, bail out.
958 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
961 // It was legal, so commit it.
962 AddrMode = TestAddrMode;
964 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
965 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
966 // X*Scale + C*Scale to addr mode.
967 ConstantInt *CI = 0; Value *AddLHS = 0;
968 if (isa<Instruction>(ScaleReg) && // not a constant expr.
969 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
970 TestAddrMode.ScaledReg = AddLHS;
971 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
973 // If this addressing mode is legal, commit it and remember that we folded
975 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
976 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
977 AddrMode = TestAddrMode;
982 // Otherwise, not (x+c)*scale, just return what we have.
986 /// MightBeFoldableInst - This is a little filter, which returns true if an
987 /// addressing computation involving I might be folded into a load/store
988 /// accessing it. This doesn't need to be perfect, but needs to accept at least
989 /// the set of instructions that MatchOperationAddr can.
990 static bool MightBeFoldableInst(Instruction *I) {
991 switch (I->getOpcode()) {
992 case Instruction::BitCast:
993 // Don't touch identity bitcasts.
994 if (I->getType() == I->getOperand(0)->getType())
996 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
997 case Instruction::PtrToInt:
998 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1000 case Instruction::IntToPtr:
1001 // We know the input is intptr_t, so this is foldable.
1003 case Instruction::Add:
1005 case Instruction::Mul:
1006 case Instruction::Shl:
1007 // Can only handle X*C and X << C.
1008 return isa<ConstantInt>(I->getOperand(1));
1009 case Instruction::GetElementPtr:
1016 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1017 /// fold the operation into the addressing mode. If so, update the addressing
1018 /// mode and return true, otherwise return false without modifying AddrMode.
1019 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1021 // Avoid exponential behavior on extremely deep expression trees.
1022 if (Depth >= 5) return false;
1025 case Instruction::PtrToInt:
1026 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1027 return MatchAddr(AddrInst->getOperand(0), Depth);
1028 case Instruction::IntToPtr:
1029 // This inttoptr is a no-op if the integer type is pointer sized.
1030 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1031 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1032 return MatchAddr(AddrInst->getOperand(0), Depth);
1034 case Instruction::BitCast:
1035 // BitCast is always a noop, and we can handle it as long as it is
1036 // int->int or pointer->pointer (we don't want int<->fp or something).
1037 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1038 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1039 // Don't touch identity bitcasts. These were probably put here by LSR,
1040 // and we don't want to mess around with them. Assume it knows what it
1042 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1043 return MatchAddr(AddrInst->getOperand(0), Depth);
1045 case Instruction::Add: {
1046 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1047 ExtAddrMode BackupAddrMode = AddrMode;
1048 unsigned OldSize = AddrModeInsts.size();
1049 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1050 MatchAddr(AddrInst->getOperand(0), Depth+1))
1053 // Restore the old addr mode info.
1054 AddrMode = BackupAddrMode;
1055 AddrModeInsts.resize(OldSize);
1057 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1058 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1059 MatchAddr(AddrInst->getOperand(1), Depth+1))
1062 // Otherwise we definitely can't merge the ADD in.
1063 AddrMode = BackupAddrMode;
1064 AddrModeInsts.resize(OldSize);
1067 //case Instruction::Or:
1068 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1070 case Instruction::Mul:
1071 case Instruction::Shl: {
1072 // Can only handle X*C and X << C.
1073 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1074 if (!RHS) return false;
1075 int64_t Scale = RHS->getSExtValue();
1076 if (Opcode == Instruction::Shl)
1077 Scale = 1LL << Scale;
1079 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1081 case Instruction::GetElementPtr: {
1082 // Scan the GEP. We check it if it contains constant offsets and at most
1083 // one variable offset.
1084 int VariableOperand = -1;
1085 unsigned VariableScale = 0;
1087 int64_t ConstantOffset = 0;
1088 const DataLayout *TD = TLI.getDataLayout();
1089 gep_type_iterator GTI = gep_type_begin(AddrInst);
1090 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1091 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1092 const StructLayout *SL = TD->getStructLayout(STy);
1094 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1095 ConstantOffset += SL->getElementOffset(Idx);
1097 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1098 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1099 ConstantOffset += CI->getSExtValue()*TypeSize;
1100 } else if (TypeSize) { // Scales of zero don't do anything.
1101 // We only allow one variable index at the moment.
1102 if (VariableOperand != -1)
1105 // Remember the variable index.
1106 VariableOperand = i;
1107 VariableScale = TypeSize;
1112 // A common case is for the GEP to only do a constant offset. In this case,
1113 // just add it to the disp field and check validity.
1114 if (VariableOperand == -1) {
1115 AddrMode.BaseOffs += ConstantOffset;
1116 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1117 // Check to see if we can fold the base pointer in too.
1118 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1121 AddrMode.BaseOffs -= ConstantOffset;
1125 // Save the valid addressing mode in case we can't match.
1126 ExtAddrMode BackupAddrMode = AddrMode;
1127 unsigned OldSize = AddrModeInsts.size();
1129 // See if the scale and offset amount is valid for this target.
1130 AddrMode.BaseOffs += ConstantOffset;
1132 // Match the base operand of the GEP.
1133 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1134 // If it couldn't be matched, just stuff the value in a register.
1135 if (AddrMode.HasBaseReg) {
1136 AddrMode = BackupAddrMode;
1137 AddrModeInsts.resize(OldSize);
1140 AddrMode.HasBaseReg = true;
1141 AddrMode.BaseReg = AddrInst->getOperand(0);
1144 // Match the remaining variable portion of the GEP.
1145 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1147 // If it couldn't be matched, try stuffing the base into a register
1148 // instead of matching it, and retrying the match of the scale.
1149 AddrMode = BackupAddrMode;
1150 AddrModeInsts.resize(OldSize);
1151 if (AddrMode.HasBaseReg)
1153 AddrMode.HasBaseReg = true;
1154 AddrMode.BaseReg = AddrInst->getOperand(0);
1155 AddrMode.BaseOffs += ConstantOffset;
1156 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1157 VariableScale, Depth)) {
1158 // If even that didn't work, bail.
1159 AddrMode = BackupAddrMode;
1160 AddrModeInsts.resize(OldSize);
1171 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
1172 /// addressing mode. If Addr can't be added to AddrMode this returns false and
1173 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
1174 /// or intptr_t for the target.
1176 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
1177 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1178 // Fold in immediates if legal for the target.
1179 AddrMode.BaseOffs += CI->getSExtValue();
1180 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1182 AddrMode.BaseOffs -= CI->getSExtValue();
1183 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
1184 // If this is a global variable, try to fold it into the addressing mode.
1185 if (AddrMode.BaseGV == 0) {
1186 AddrMode.BaseGV = GV;
1187 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1189 AddrMode.BaseGV = 0;
1191 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
1192 ExtAddrMode BackupAddrMode = AddrMode;
1193 unsigned OldSize = AddrModeInsts.size();
1195 // Check to see if it is possible to fold this operation.
1196 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
1197 // Okay, it's possible to fold this. Check to see if it is actually
1198 // *profitable* to do so. We use a simple cost model to avoid increasing
1199 // register pressure too much.
1200 if (I->hasOneUse() ||
1201 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
1202 AddrModeInsts.push_back(I);
1206 // It isn't profitable to do this, roll back.
1207 //cerr << "NOT FOLDING: " << *I;
1208 AddrMode = BackupAddrMode;
1209 AddrModeInsts.resize(OldSize);
1211 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1212 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
1214 } else if (isa<ConstantPointerNull>(Addr)) {
1215 // Null pointer gets folded without affecting the addressing mode.
1219 // Worse case, the target should support [reg] addressing modes. :)
1220 if (!AddrMode.HasBaseReg) {
1221 AddrMode.HasBaseReg = true;
1222 AddrMode.BaseReg = Addr;
1223 // Still check for legality in case the target supports [imm] but not [i+r].
1224 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1226 AddrMode.HasBaseReg = false;
1227 AddrMode.BaseReg = 0;
1230 // If the base register is already taken, see if we can do [r+r].
1231 if (AddrMode.Scale == 0) {
1233 AddrMode.ScaledReg = Addr;
1234 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1237 AddrMode.ScaledReg = 0;
1243 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
1244 /// inline asm call are due to memory operands. If so, return true, otherwise
1246 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
1247 const TargetLowering &TLI) {
1248 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
1249 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1250 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1252 // Compute the constraint code and ConstraintType to use.
1253 TLI.ComputeConstraintToUse(OpInfo, SDValue());
1255 // If this asm operand is our Value*, and if it isn't an indirect memory
1256 // operand, we can't fold it!
1257 if (OpInfo.CallOperandVal == OpVal &&
1258 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1259 !OpInfo.isIndirect))
1266 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1267 /// memory use. If we find an obviously non-foldable instruction, return true.
1268 /// Add the ultimately found memory instructions to MemoryUses.
1269 static bool FindAllMemoryUses(Instruction *I,
1270 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
1271 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1272 const TargetLowering &TLI) {
1273 // If we already considered this instruction, we're done.
1274 if (!ConsideredInsts.insert(I))
1277 // If this is an obviously unfoldable instruction, bail out.
1278 if (!MightBeFoldableInst(I))
1281 // Loop over all the uses, recursively processing them.
1282 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1286 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1287 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1291 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1292 unsigned opNo = UI.getOperandNo();
1293 if (opNo == 0) return true; // Storing addr, not into addr.
1294 MemoryUses.push_back(std::make_pair(SI, opNo));
1298 if (CallInst *CI = dyn_cast<CallInst>(U)) {
1299 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1300 if (!IA) return true;
1302 // If this is a memory operand, we're cool, otherwise bail out.
1303 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1308 if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
1316 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1317 /// the use site that we're folding it into. If so, there is no cost to
1318 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
1319 /// that we know are live at the instruction already.
1320 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1321 Value *KnownLive2) {
1322 // If Val is either of the known-live values, we know it is live!
1323 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1326 // All values other than instructions and arguments (e.g. constants) are live.
1327 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
1329 // If Val is a constant sized alloca in the entry block, it is live, this is
1330 // true because it is just a reference to the stack/frame pointer, which is
1331 // live for the whole function.
1332 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1333 if (AI->isStaticAlloca())
1336 // Check to see if this value is already used in the memory instruction's
1337 // block. If so, it's already live into the block at the very least, so we
1338 // can reasonably fold it.
1339 return Val->isUsedInBasicBlock(MemoryInst->getParent());
1342 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1343 /// mode of the machine to fold the specified instruction into a load or store
1344 /// that ultimately uses it. However, the specified instruction has multiple
1345 /// uses. Given this, it may actually increase register pressure to fold it
1346 /// into the load. For example, consider this code:
1350 /// use(Y) -> nonload/store
1354 /// In this case, Y has multiple uses, and can be folded into the load of Z
1355 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1356 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1357 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1358 /// number of computations either.
1360 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1361 /// X was live across 'load Z' for other reasons, we actually *would* want to
1362 /// fold the addressing mode in the Z case. This would make Y die earlier.
1363 bool AddressingModeMatcher::
1364 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1365 ExtAddrMode &AMAfter) {
1366 if (IgnoreProfitability) return true;
1368 // AMBefore is the addressing mode before this instruction was folded into it,
1369 // and AMAfter is the addressing mode after the instruction was folded. Get
1370 // the set of registers referenced by AMAfter and subtract out those
1371 // referenced by AMBefore: this is the set of values which folding in this
1372 // address extends the lifetime of.
1374 // Note that there are only two potential values being referenced here,
1375 // BaseReg and ScaleReg (global addresses are always available, as are any
1376 // folded immediates).
1377 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1379 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1380 // lifetime wasn't extended by adding this instruction.
1381 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1383 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1386 // If folding this instruction (and it's subexprs) didn't extend any live
1387 // ranges, we're ok with it.
1388 if (BaseReg == 0 && ScaledReg == 0)
1391 // If all uses of this instruction are ultimately load/store/inlineasm's,
1392 // check to see if their addressing modes will include this instruction. If
1393 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1395 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1396 SmallPtrSet<Instruction*, 16> ConsideredInsts;
1397 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1398 return false; // Has a non-memory, non-foldable use!
1400 // Now that we know that all uses of this instruction are part of a chain of
1401 // computation involving only operations that could theoretically be folded
1402 // into a memory use, loop over each of these uses and see if they could
1403 // *actually* fold the instruction.
1404 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1405 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1406 Instruction *User = MemoryUses[i].first;
1407 unsigned OpNo = MemoryUses[i].second;
1409 // Get the access type of this use. If the use isn't a pointer, we don't
1410 // know what it accesses.
1411 Value *Address = User->getOperand(OpNo);
1412 if (!Address->getType()->isPointerTy())
1414 Type *AddressAccessTy = Address->getType()->getPointerElementType();
1416 // Do a match against the root of this address, ignoring profitability. This
1417 // will tell us if the addressing mode for the memory operation will
1418 // *actually* cover the shared instruction.
1420 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1421 MemoryInst, Result);
1422 Matcher.IgnoreProfitability = true;
1423 bool Success = Matcher.MatchAddr(Address, 0);
1424 (void)Success; assert(Success && "Couldn't select *anything*?");
1426 // If the match didn't cover I, then it won't be shared by it.
1427 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1428 I) == MatchedAddrModeInsts.end())
1431 MatchedAddrModeInsts.clear();
1437 } // end anonymous namespace
1439 /// IsNonLocalValue - Return true if the specified values are defined in a
1440 /// different basic block than BB.
1441 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1442 if (Instruction *I = dyn_cast<Instruction>(V))
1443 return I->getParent() != BB;
1447 /// OptimizeMemoryInst - Load and Store Instructions often have
1448 /// addressing modes that can do significant amounts of computation. As such,
1449 /// instruction selection will try to get the load or store to do as much
1450 /// computation as possible for the program. The problem is that isel can only
1451 /// see within a single block. As such, we sink as much legal addressing mode
1452 /// stuff into the block as possible.
1454 /// This method is used to optimize both load/store and inline asms with memory
1456 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
1460 // Try to collapse single-value PHI nodes. This is necessary to undo
1461 // unprofitable PRE transformations.
1462 SmallVector<Value*, 8> worklist;
1463 SmallPtrSet<Value*, 16> Visited;
1464 worklist.push_back(Addr);
1466 // Use a worklist to iteratively look through PHI nodes, and ensure that
1467 // the addressing mode obtained from the non-PHI roots of the graph
1469 Value *Consensus = 0;
1470 unsigned NumUsesConsensus = 0;
1471 bool IsNumUsesConsensusValid = false;
1472 SmallVector<Instruction*, 16> AddrModeInsts;
1473 ExtAddrMode AddrMode;
1474 while (!worklist.empty()) {
1475 Value *V = worklist.back();
1476 worklist.pop_back();
1478 // Break use-def graph loops.
1479 if (!Visited.insert(V)) {
1484 // For a PHI node, push all of its incoming values.
1485 if (PHINode *P = dyn_cast<PHINode>(V)) {
1486 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
1487 worklist.push_back(P->getIncomingValue(i));
1491 // For non-PHIs, determine the addressing mode being computed.
1492 SmallVector<Instruction*, 16> NewAddrModeInsts;
1493 ExtAddrMode NewAddrMode =
1494 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
1495 NewAddrModeInsts, *TLI);
1497 // This check is broken into two cases with very similar code to avoid using
1498 // getNumUses() as much as possible. Some values have a lot of uses, so
1499 // calling getNumUses() unconditionally caused a significant compile-time
1503 AddrMode = NewAddrMode;
1504 AddrModeInsts = NewAddrModeInsts;
1506 } else if (NewAddrMode == AddrMode) {
1507 if (!IsNumUsesConsensusValid) {
1508 NumUsesConsensus = Consensus->getNumUses();
1509 IsNumUsesConsensusValid = true;
1512 // Ensure that the obtained addressing mode is equivalent to that obtained
1513 // for all other roots of the PHI traversal. Also, when choosing one
1514 // such root as representative, select the one with the most uses in order
1515 // to keep the cost modeling heuristics in AddressingModeMatcher
1517 unsigned NumUses = V->getNumUses();
1518 if (NumUses > NumUsesConsensus) {
1520 NumUsesConsensus = NumUses;
1521 AddrModeInsts = NewAddrModeInsts;
1530 // If the addressing mode couldn't be determined, or if multiple different
1531 // ones were determined, bail out now.
1532 if (!Consensus) return false;
1534 // Check to see if any of the instructions supersumed by this addr mode are
1535 // non-local to I's BB.
1536 bool AnyNonLocal = false;
1537 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
1538 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
1544 // If all the instructions matched are already in this BB, don't do anything.
1546 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
1550 // Insert this computation right after this user. Since our caller is
1551 // scanning from the top of the BB to the bottom, reuse of the expr are
1552 // guaranteed to happen later.
1553 IRBuilder<> Builder(MemoryInst);
1555 // Now that we determined the addressing expression we want to use and know
1556 // that we have to sink it into this block. Check to see if we have already
1557 // done this for some other load/store instr in this block. If so, reuse the
1559 Value *&SunkAddr = SunkAddrs[Addr];
1561 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
1563 if (SunkAddr->getType() != Addr->getType())
1564 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
1566 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
1568 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
1571 // Start with the base register. Do this first so that subsequent address
1572 // matching finds it last, which will prevent it from trying to match it
1573 // as the scaled value in case it happens to be a mul. That would be
1574 // problematic if we've sunk a different mul for the scale, because then
1575 // we'd end up sinking both muls.
1576 if (AddrMode.BaseReg) {
1577 Value *V = AddrMode.BaseReg;
1578 if (V->getType()->isPointerTy())
1579 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1580 if (V->getType() != IntPtrTy)
1581 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
1585 // Add the scale value.
1586 if (AddrMode.Scale) {
1587 Value *V = AddrMode.ScaledReg;
1588 if (V->getType() == IntPtrTy) {
1590 } else if (V->getType()->isPointerTy()) {
1591 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1592 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1593 cast<IntegerType>(V->getType())->getBitWidth()) {
1594 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
1596 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
1598 if (AddrMode.Scale != 1)
1599 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
1602 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1607 // Add in the BaseGV if present.
1608 if (AddrMode.BaseGV) {
1609 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
1611 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1616 // Add in the Base Offset if present.
1617 if (AddrMode.BaseOffs) {
1618 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1620 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1626 SunkAddr = Constant::getNullValue(Addr->getType());
1628 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1631 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1633 // If we have no uses, recursively delete the value and all dead instructions
1635 if (Repl->use_empty()) {
1636 // This can cause recursive deletion, which can invalidate our iterator.
1637 // Use a WeakVH to hold onto it in case this happens.
1638 WeakVH IterHandle(CurInstIterator);
1639 BasicBlock *BB = CurInstIterator->getParent();
1641 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1643 if (IterHandle != CurInstIterator) {
1644 // If the iterator instruction was recursively deleted, start over at the
1645 // start of the block.
1646 CurInstIterator = BB->begin();
1654 /// OptimizeInlineAsmInst - If there are any memory operands, use
1655 /// OptimizeMemoryInst to sink their address computing into the block when
1656 /// possible / profitable.
1657 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1658 bool MadeChange = false;
1660 TargetLowering::AsmOperandInfoVector
1661 TargetConstraints = TLI->ParseConstraints(CS);
1663 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1664 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1666 // Compute the constraint code and ConstraintType to use.
1667 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1669 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1670 OpInfo.isIndirect) {
1671 Value *OpVal = CS->getArgOperand(ArgNo++);
1672 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1673 } else if (OpInfo.Type == InlineAsm::isInput)
1680 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1681 /// basic block as the load, unless conditions are unfavorable. This allows
1682 /// SelectionDAG to fold the extend into the load.
1684 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1685 // Look for a load being extended.
1686 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1687 if (!LI) return false;
1689 // If they're already in the same block, there's nothing to do.
1690 if (LI->getParent() == I->getParent())
1693 // If the load has other users and the truncate is not free, this probably
1694 // isn't worthwhile.
1695 if (!LI->hasOneUse() &&
1696 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1697 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1698 !TLI->isTruncateFree(I->getType(), LI->getType()))
1701 // Check whether the target supports casts folded into loads.
1703 if (isa<ZExtInst>(I))
1704 LType = ISD::ZEXTLOAD;
1706 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1707 LType = ISD::SEXTLOAD;
1709 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1712 // Move the extend into the same block as the load, so that SelectionDAG
1714 I->removeFromParent();
1720 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1721 BasicBlock *DefBB = I->getParent();
1723 // If the result of a {s|z}ext and its source are both live out, rewrite all
1724 // other uses of the source with result of extension.
1725 Value *Src = I->getOperand(0);
1726 if (Src->hasOneUse())
1729 // Only do this xform if truncating is free.
1730 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1733 // Only safe to perform the optimization if the source is also defined in
1735 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1738 bool DefIsLiveOut = false;
1739 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1741 Instruction *User = cast<Instruction>(*UI);
1743 // Figure out which BB this ext is used in.
1744 BasicBlock *UserBB = User->getParent();
1745 if (UserBB == DefBB) continue;
1746 DefIsLiveOut = true;
1752 // Make sure none of the uses are PHI nodes.
1753 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1755 Instruction *User = cast<Instruction>(*UI);
1756 BasicBlock *UserBB = User->getParent();
1757 if (UserBB == DefBB) continue;
1758 // Be conservative. We don't want this xform to end up introducing
1759 // reloads just before load / store instructions.
1760 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1764 // InsertedTruncs - Only insert one trunc in each block once.
1765 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1767 bool MadeChange = false;
1768 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1770 Use &TheUse = UI.getUse();
1771 Instruction *User = cast<Instruction>(*UI);
1773 // Figure out which BB this ext is used in.
1774 BasicBlock *UserBB = User->getParent();
1775 if (UserBB == DefBB) continue;
1777 // Both src and def are live in this block. Rewrite the use.
1778 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1780 if (!InsertedTrunc) {
1781 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1782 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1785 // Replace a use of the {s|z}ext source with a use of the result.
1786 TheUse = InsertedTrunc;
1794 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1795 /// turned into an explicit branch.
1796 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1797 // FIXME: This should use the same heuristics as IfConversion to determine
1798 // whether a select is better represented as a branch. This requires that
1799 // branch probability metadata is preserved for the select, which is not the
1802 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1804 // If the branch is predicted right, an out of order CPU can avoid blocking on
1805 // the compare. Emit cmovs on compares with a memory operand as branches to
1806 // avoid stalls on the load from memory. If the compare has more than one use
1807 // there's probably another cmov or setcc around so it's not worth emitting a
1812 Value *CmpOp0 = Cmp->getOperand(0);
1813 Value *CmpOp1 = Cmp->getOperand(1);
1815 // We check that the memory operand has one use to avoid uses of the loaded
1816 // value directly after the compare, making branches unprofitable.
1817 return Cmp->hasOneUse() &&
1818 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1819 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1823 /// If we have a SelectInst that will likely profit from branch prediction,
1824 /// turn it into a branch.
1825 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1826 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1828 // Can we convert the 'select' to CF ?
1829 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1832 TargetLowering::SelectSupportKind SelectKind;
1834 SelectKind = TargetLowering::VectorMaskSelect;
1835 else if (SI->getType()->isVectorTy())
1836 SelectKind = TargetLowering::ScalarCondVectorVal;
1838 SelectKind = TargetLowering::ScalarValSelect;
1840 // Do we have efficient codegen support for this kind of 'selects' ?
1841 if (TLI->isSelectSupported(SelectKind)) {
1842 // We have efficient codegen support for the select instruction.
1843 // Check if it is profitable to keep this 'select'.
1844 if (!TLI->isPredictableSelectExpensive() ||
1845 !isFormingBranchFromSelectProfitable(SI))
1851 // First, we split the block containing the select into 2 blocks.
1852 BasicBlock *StartBlock = SI->getParent();
1853 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1854 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1856 // Create a new block serving as the landing pad for the branch.
1857 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1858 NextBlock->getParent(), NextBlock);
1860 // Move the unconditional branch from the block with the select in it into our
1861 // landing pad block.
1862 StartBlock->getTerminator()->eraseFromParent();
1863 BranchInst::Create(NextBlock, SmallBlock);
1865 // Insert the real conditional branch based on the original condition.
1866 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1868 // The select itself is replaced with a PHI Node.
1869 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1871 PN->addIncoming(SI->getTrueValue(), StartBlock);
1872 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1873 SI->replaceAllUsesWith(PN);
1874 SI->eraseFromParent();
1876 // Instruct OptimizeBlock to skip to the next block.
1877 CurInstIterator = StartBlock->end();
1878 ++NumSelectsExpanded;
1882 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1883 if (PHINode *P = dyn_cast<PHINode>(I)) {
1884 // It is possible for very late stage optimizations (such as SimplifyCFG)
1885 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1886 // trivial PHI, go ahead and zap it here.
1887 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
1889 P->replaceAllUsesWith(V);
1890 P->eraseFromParent();
1897 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1898 // If the source of the cast is a constant, then this should have
1899 // already been constant folded. The only reason NOT to constant fold
1900 // it is if something (e.g. LSR) was careful to place the constant
1901 // evaluation in a block other than then one that uses it (e.g. to hoist
1902 // the address of globals out of a loop). If this is the case, we don't
1903 // want to forward-subst the cast.
1904 if (isa<Constant>(CI->getOperand(0)))
1907 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1910 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1911 bool MadeChange = MoveExtToFormExtLoad(I);
1912 return MadeChange | OptimizeExtUses(I);
1917 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1918 if (!TLI || !TLI->hasMultipleConditionRegisters())
1919 return OptimizeCmpExpression(CI);
1921 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1923 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1927 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1929 return OptimizeMemoryInst(I, SI->getOperand(1),
1930 SI->getOperand(0)->getType());
1934 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1935 if (GEPI->hasAllZeroIndices()) {
1936 /// The GEP operand must be a pointer, so must its result -> BitCast
1937 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1938 GEPI->getName(), GEPI);
1939 GEPI->replaceAllUsesWith(NC);
1940 GEPI->eraseFromParent();
1948 if (CallInst *CI = dyn_cast<CallInst>(I))
1949 return OptimizeCallInst(CI);
1951 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1952 return OptimizeSelectInst(SI);
1957 // In this pass we look for GEP and cast instructions that are used
1958 // across basic blocks and rewrite them to improve basic-block-at-a-time
1960 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1962 bool MadeChange = false;
1964 CurInstIterator = BB.begin();
1965 while (CurInstIterator != BB.end())
1966 MadeChange |= OptimizeInst(CurInstIterator++);
1968 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1973 // llvm.dbg.value is far away from the value then iSel may not be able
1974 // handle it properly. iSel will drop llvm.dbg.value if it can not
1975 // find a node corresponding to the value.
1976 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1977 bool MadeChange = false;
1978 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1979 Instruction *PrevNonDbgInst = NULL;
1980 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1981 Instruction *Insn = BI; ++BI;
1982 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1984 PrevNonDbgInst = Insn;
1988 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1989 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1990 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1991 DVI->removeFromParent();
1992 if (isa<PHINode>(VI))
1993 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1995 DVI->insertAfter(VI);