1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "codegenprepare"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/ProfileInfo.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/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 TargetLowering *TLI;
78 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 DenseMap<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 TargetLowering *tli = 0)
102 : FunctionPass(ID), TLI(tli) {
103 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
105 bool runOnFunction(Function &F);
107 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.addPreserved<DominatorTree>();
109 AU.addPreserved<ProfileInfo>();
110 AU.addRequired<TargetLibraryInfo>();
114 bool EliminateFallThrough(Function &F);
115 bool EliminateMostlyEmptyBlocks(Function &F);
116 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
117 void EliminateMostlyEmptyBlock(BasicBlock *BB);
118 bool OptimizeBlock(BasicBlock &BB);
119 bool OptimizeInst(Instruction *I);
120 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
121 bool OptimizeInlineAsmInst(CallInst *CS);
122 bool OptimizeCallInst(CallInst *CI);
123 bool MoveExtToFormExtLoad(Instruction *I);
124 bool OptimizeExtUses(Instruction *I);
125 bool OptimizeSelectInst(SelectInst *SI);
126 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
127 bool PlaceDbgValues(Function &F);
131 char CodeGenPrepare::ID = 0;
132 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
133 "Optimize for code generation", false, false)
134 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
135 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
136 "Optimize for code generation", false, false)
138 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
139 return new CodeGenPrepare(TLI);
142 bool CodeGenPrepare::runOnFunction(Function &F) {
143 bool EverMadeChange = false;
146 TLInfo = &getAnalysis<TargetLibraryInfo>();
147 DT = getAnalysisIfAvailable<DominatorTree>();
148 PFI = getAnalysisIfAvailable<ProfileInfo>();
149 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
151 // First pass, eliminate blocks that contain only PHI nodes and an
152 // unconditional branch.
153 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
155 // llvm.dbg.value is far away from the value then iSel may not be able
156 // handle it properly. iSel will drop llvm.dbg.value if it can not
157 // find a node corresponding to the value.
158 EverMadeChange |= PlaceDbgValues(F);
160 bool MadeChange = true;
163 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
164 BasicBlock *BB = I++;
165 MadeChange |= OptimizeBlock(*BB);
167 EverMadeChange |= MadeChange;
172 if (!DisableBranchOpts) {
174 SmallPtrSet<BasicBlock*, 8> WorkList;
175 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
176 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
177 MadeChange |= ConstantFoldTerminator(BB, true);
178 if (!MadeChange) continue;
180 for (SmallVectorImpl<BasicBlock*>::iterator
181 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
182 if (pred_begin(*II) == pred_end(*II))
183 WorkList.insert(*II);
186 for (SmallPtrSet<BasicBlock*, 8>::iterator
187 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
190 // Merge pairs of basic blocks with unconditional branches, connected by
192 if (EverMadeChange || MadeChange)
193 MadeChange |= EliminateFallThrough(F);
197 EverMadeChange |= MadeChange;
200 if (ModifiedDT && DT)
201 DT->DT->recalculate(F);
203 return EverMadeChange;
206 /// EliminateFallThrough - Merge basic blocks which are connected
207 /// by a single edge, where one of the basic blocks has a single successor
208 /// pointing to the other basic block, which has a single predecessor.
209 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
210 bool Changed = false;
211 // Scan all of the blocks in the function, except for the entry block.
212 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
213 BasicBlock *BB = I++;
214 // If the destination block has a single pred, then this is a trivial
215 // edge, just collapse it.
216 BasicBlock *SinglePred = BB->getSinglePredecessor();
218 if (!SinglePred || SinglePred == BB) continue;
220 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
221 if (Term && !Term->isConditional()) {
223 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
224 // Remember if SinglePred was the entry block of the function.
225 // If so, we will need to move BB back to the entry position.
226 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
227 MergeBasicBlockIntoOnlyPred(BB, this);
229 if (isEntry && BB != &BB->getParent()->getEntryBlock())
230 BB->moveBefore(&BB->getParent()->getEntryBlock());
232 // We have erased a block. Update the iterator.
239 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
240 /// debug info directives, and an unconditional branch. Passes before isel
241 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
242 /// isel. Start by eliminating these blocks so we can split them the way we
244 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
245 bool MadeChange = false;
246 // Note that this intentionally skips the entry block.
247 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
248 BasicBlock *BB = I++;
250 // If this block doesn't end with an uncond branch, ignore it.
251 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
252 if (!BI || !BI->isUnconditional())
255 // If the instruction before the branch (skipping debug info) isn't a phi
256 // node, then other stuff is happening here.
257 BasicBlock::iterator BBI = BI;
258 if (BBI != BB->begin()) {
260 while (isa<DbgInfoIntrinsic>(BBI)) {
261 if (BBI == BB->begin())
265 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
269 // Do not break infinite loops.
270 BasicBlock *DestBB = BI->getSuccessor(0);
274 if (!CanMergeBlocks(BB, DestBB))
277 EliminateMostlyEmptyBlock(BB);
283 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
284 /// single uncond branch between them, and BB contains no other non-phi
286 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
287 const BasicBlock *DestBB) const {
288 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
289 // the successor. If there are more complex condition (e.g. preheaders),
290 // don't mess around with them.
291 BasicBlock::const_iterator BBI = BB->begin();
292 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
293 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
295 const Instruction *User = cast<Instruction>(*UI);
296 if (User->getParent() != DestBB || !isa<PHINode>(User))
298 // If User is inside DestBB block and it is a PHINode then check
299 // incoming value. If incoming value is not from BB then this is
300 // a complex condition (e.g. preheaders) we want to avoid here.
301 if (User->getParent() == DestBB) {
302 if (const PHINode *UPN = dyn_cast<PHINode>(User))
303 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
304 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
305 if (Insn && Insn->getParent() == BB &&
306 Insn->getParent() != UPN->getIncomingBlock(I))
313 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
314 // and DestBB may have conflicting incoming values for the block. If so, we
315 // can't merge the block.
316 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
317 if (!DestBBPN) return true; // no conflict.
319 // Collect the preds of BB.
320 SmallPtrSet<const BasicBlock*, 16> BBPreds;
321 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
322 // It is faster to get preds from a PHI than with pred_iterator.
323 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
324 BBPreds.insert(BBPN->getIncomingBlock(i));
326 BBPreds.insert(pred_begin(BB), pred_end(BB));
329 // Walk the preds of DestBB.
330 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
331 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
332 if (BBPreds.count(Pred)) { // Common predecessor?
333 BBI = DestBB->begin();
334 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
335 const Value *V1 = PN->getIncomingValueForBlock(Pred);
336 const Value *V2 = PN->getIncomingValueForBlock(BB);
338 // If V2 is a phi node in BB, look up what the mapped value will be.
339 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
340 if (V2PN->getParent() == BB)
341 V2 = V2PN->getIncomingValueForBlock(Pred);
343 // If there is a conflict, bail out.
344 if (V1 != V2) return false;
353 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
354 /// an unconditional branch in it.
355 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
356 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
357 BasicBlock *DestBB = BI->getSuccessor(0);
359 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
361 // If the destination block has a single pred, then this is a trivial edge,
363 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
364 if (SinglePred != DestBB) {
365 // Remember if SinglePred was the entry block of the function. If so, we
366 // will need to move BB back to the entry position.
367 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
368 MergeBasicBlockIntoOnlyPred(DestBB, this);
370 if (isEntry && BB != &BB->getParent()->getEntryBlock())
371 BB->moveBefore(&BB->getParent()->getEntryBlock());
373 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
378 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
379 // to handle the new incoming edges it is about to have.
381 for (BasicBlock::iterator BBI = DestBB->begin();
382 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
383 // Remove the incoming value for BB, and remember it.
384 Value *InVal = PN->removeIncomingValue(BB, false);
386 // Two options: either the InVal is a phi node defined in BB or it is some
387 // value that dominates BB.
388 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
389 if (InValPhi && InValPhi->getParent() == BB) {
390 // Add all of the input values of the input PHI as inputs of this phi.
391 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
392 PN->addIncoming(InValPhi->getIncomingValue(i),
393 InValPhi->getIncomingBlock(i));
395 // Otherwise, add one instance of the dominating value for each edge that
396 // we will be adding.
397 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
398 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
399 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
401 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
402 PN->addIncoming(InVal, *PI);
407 // The PHIs are now updated, change everything that refers to BB to use
408 // DestBB and remove BB.
409 BB->replaceAllUsesWith(DestBB);
410 if (DT && !ModifiedDT) {
411 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
412 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
413 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
414 DT->changeImmediateDominator(DestBB, NewIDom);
418 PFI->replaceAllUses(BB, DestBB);
419 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
421 BB->eraseFromParent();
424 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
427 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
428 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
429 /// sink it into user blocks to reduce the number of virtual
430 /// registers that must be created and coalesced.
432 /// Return true if any changes are made.
434 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
435 // If this is a noop copy,
436 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
437 EVT DstVT = TLI.getValueType(CI->getType());
439 // This is an fp<->int conversion?
440 if (SrcVT.isInteger() != DstVT.isInteger())
443 // If this is an extension, it will be a zero or sign extension, which
445 if (SrcVT.bitsLT(DstVT)) return false;
447 // If these values will be promoted, find out what they will be promoted
448 // to. This helps us consider truncates on PPC as noop copies when they
450 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
451 TargetLowering::TypePromoteInteger)
452 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
453 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
454 TargetLowering::TypePromoteInteger)
455 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
457 // If, after promotion, these are the same types, this is a noop copy.
461 BasicBlock *DefBB = CI->getParent();
463 /// InsertedCasts - Only insert a cast in each block once.
464 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
466 bool MadeChange = false;
467 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
469 Use &TheUse = UI.getUse();
470 Instruction *User = cast<Instruction>(*UI);
472 // Figure out which BB this cast is used in. For PHI's this is the
473 // appropriate predecessor block.
474 BasicBlock *UserBB = User->getParent();
475 if (PHINode *PN = dyn_cast<PHINode>(User)) {
476 UserBB = PN->getIncomingBlock(UI);
479 // Preincrement use iterator so we don't invalidate it.
482 // If this user is in the same block as the cast, don't change the cast.
483 if (UserBB == DefBB) continue;
485 // If we have already inserted a cast into this block, use it.
486 CastInst *&InsertedCast = InsertedCasts[UserBB];
489 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
491 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
496 // Replace a use of the cast with a use of the new cast.
497 TheUse = InsertedCast;
501 // If we removed all uses, nuke the cast.
502 if (CI->use_empty()) {
503 CI->eraseFromParent();
510 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
511 /// the number of virtual registers that must be created and coalesced. This is
512 /// a clear win except on targets with multiple condition code registers
513 /// (PowerPC), where it might lose; some adjustment may be wanted there.
515 /// Return true if any changes are made.
516 static bool OptimizeCmpExpression(CmpInst *CI) {
517 BasicBlock *DefBB = CI->getParent();
519 /// InsertedCmp - Only insert a cmp in each block once.
520 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
522 bool MadeChange = false;
523 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
525 Use &TheUse = UI.getUse();
526 Instruction *User = cast<Instruction>(*UI);
528 // Preincrement use iterator so we don't invalidate it.
531 // Don't bother for PHI nodes.
532 if (isa<PHINode>(User))
535 // Figure out which BB this cmp is used in.
536 BasicBlock *UserBB = User->getParent();
538 // If this user is in the same block as the cmp, don't change the cmp.
539 if (UserBB == DefBB) continue;
541 // If we have already inserted a cmp into this block, use it.
542 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
545 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
547 CmpInst::Create(CI->getOpcode(),
548 CI->getPredicate(), CI->getOperand(0),
549 CI->getOperand(1), "", InsertPt);
553 // Replace a use of the cmp with a use of the new cmp.
554 TheUse = InsertedCmp;
558 // If we removed all uses, nuke the cmp.
560 CI->eraseFromParent();
566 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
568 void replaceCall(Value *With) {
569 CI->replaceAllUsesWith(With);
570 CI->eraseFromParent();
572 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
573 if (ConstantInt *SizeCI =
574 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
575 return SizeCI->isAllOnesValue();
579 } // end anonymous namespace
581 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
582 BasicBlock *BB = CI->getParent();
584 // Lower inline assembly if we can.
585 // If we found an inline asm expession, and if the target knows how to
586 // lower it to normal LLVM code, do so now.
587 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
588 if (TLI->ExpandInlineAsm(CI)) {
589 // Avoid invalidating the iterator.
590 CurInstIterator = BB->begin();
591 // Avoid processing instructions out of order, which could cause
592 // reuse before a value is defined.
596 // Sink address computing for memory operands into the block.
597 if (OptimizeInlineAsmInst(CI))
601 // Lower all uses of llvm.objectsize.*
602 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
603 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
604 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
605 Type *ReturnTy = CI->getType();
606 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
608 // Substituting this can cause recursive simplifications, which can
609 // invalidate our iterator. Use a WeakVH to hold onto it in case this
611 WeakVH IterHandle(CurInstIterator);
613 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
614 TLInfo, ModifiedDT ? 0 : DT);
616 // If the iterator instruction was recursively deleted, start over at the
617 // start of the block.
618 if (IterHandle != CurInstIterator) {
619 CurInstIterator = BB->begin();
626 SmallVector<Value*, 2> PtrOps;
628 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
629 while (!PtrOps.empty())
630 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
634 // From here on out we're working with named functions.
635 if (CI->getCalledFunction() == 0) return false;
637 // We'll need TargetData from here on out.
638 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
639 if (!TD) return false;
641 // Lower all default uses of _chk calls. This is very similar
642 // to what InstCombineCalls does, but here we are only lowering calls
643 // that have the default "don't know" as the objectsize. Anything else
644 // should be left alone.
645 CodeGenPrepareFortifiedLibCalls Simplifier;
646 return Simplifier.fold(CI, TD, TLInfo);
649 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
650 /// instructions to the predecessor to enable tail call optimizations. The
651 /// case it is currently looking for is:
653 /// %tmp0 = tail call i32 @f0()
656 /// %tmp1 = tail call i32 @f1()
659 /// %tmp2 = tail call i32 @f2()
662 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
668 /// %tmp0 = tail call i32 @f0()
671 /// %tmp1 = tail call i32 @f1()
674 /// %tmp2 = tail call i32 @f2()
677 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
682 BitCastInst *BCI = 0;
683 Value *V = RI->getReturnValue();
685 BCI = dyn_cast<BitCastInst>(V);
687 V = BCI->getOperand(0);
689 PN = dyn_cast<PHINode>(V);
694 BasicBlock *BB = RI->getParent();
695 if (PN && PN->getParent() != BB)
698 // It's not safe to eliminate the sign / zero extension of the return value.
699 // See llvm::isInTailCallPosition().
700 const Function *F = BB->getParent();
701 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
702 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
705 // Make sure there are no instructions between the PHI and return, or that the
706 // return is the first instruction in the block.
708 BasicBlock::iterator BI = BB->begin();
709 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
711 // Also skip over the bitcast.
716 BasicBlock::iterator BI = BB->begin();
717 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
722 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
724 SmallVector<CallInst*, 4> TailCalls;
726 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
727 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
728 // Make sure the phi value is indeed produced by the tail call.
729 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
730 TLI->mayBeEmittedAsTailCall(CI))
731 TailCalls.push_back(CI);
734 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
735 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
736 if (!VisitedBBs.insert(*PI))
739 BasicBlock::InstListType &InstList = (*PI)->getInstList();
740 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
741 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
742 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
746 CallInst *CI = dyn_cast<CallInst>(&*RI);
747 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
748 TailCalls.push_back(CI);
752 bool Changed = false;
753 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
754 CallInst *CI = TailCalls[i];
757 // Conservatively require the attributes of the call to match those of the
758 // return. Ignore noalias because it doesn't affect the call sequence.
759 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
760 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
763 // Make sure the call instruction is followed by an unconditional branch to
765 BasicBlock *CallBB = CI->getParent();
766 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
767 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
770 // Duplicate the return into CallBB.
771 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
772 ModifiedDT = Changed = true;
776 // If we eliminated all predecessors of the block, delete the block now.
777 if (Changed && pred_begin(BB) == pred_end(BB))
778 BB->eraseFromParent();
783 //===----------------------------------------------------------------------===//
784 // Memory Optimization
785 //===----------------------------------------------------------------------===//
787 /// IsNonLocalValue - Return true if the specified values are defined in a
788 /// different basic block than BB.
789 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
790 if (Instruction *I = dyn_cast<Instruction>(V))
791 return I->getParent() != BB;
795 /// OptimizeMemoryInst - Load and Store Instructions often have
796 /// addressing modes that can do significant amounts of computation. As such,
797 /// instruction selection will try to get the load or store to do as much
798 /// computation as possible for the program. The problem is that isel can only
799 /// see within a single block. As such, we sink as much legal addressing mode
800 /// stuff into the block as possible.
802 /// This method is used to optimize both load/store and inline asms with memory
804 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
808 // Try to collapse single-value PHI nodes. This is necessary to undo
809 // unprofitable PRE transformations.
810 SmallVector<Value*, 8> worklist;
811 SmallPtrSet<Value*, 16> Visited;
812 worklist.push_back(Addr);
814 // Use a worklist to iteratively look through PHI nodes, and ensure that
815 // the addressing mode obtained from the non-PHI roots of the graph
817 Value *Consensus = 0;
818 unsigned NumUsesConsensus = 0;
819 bool IsNumUsesConsensusValid = false;
820 SmallVector<Instruction*, 16> AddrModeInsts;
821 ExtAddrMode AddrMode;
822 while (!worklist.empty()) {
823 Value *V = worklist.back();
826 // Break use-def graph loops.
827 if (!Visited.insert(V)) {
832 // For a PHI node, push all of its incoming values.
833 if (PHINode *P = dyn_cast<PHINode>(V)) {
834 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
835 worklist.push_back(P->getIncomingValue(i));
839 // For non-PHIs, determine the addressing mode being computed.
840 SmallVector<Instruction*, 16> NewAddrModeInsts;
841 ExtAddrMode NewAddrMode =
842 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
843 NewAddrModeInsts, *TLI);
845 // This check is broken into two cases with very similar code to avoid using
846 // getNumUses() as much as possible. Some values have a lot of uses, so
847 // calling getNumUses() unconditionally caused a significant compile-time
851 AddrMode = NewAddrMode;
852 AddrModeInsts = NewAddrModeInsts;
854 } else if (NewAddrMode == AddrMode) {
855 if (!IsNumUsesConsensusValid) {
856 NumUsesConsensus = Consensus->getNumUses();
857 IsNumUsesConsensusValid = true;
860 // Ensure that the obtained addressing mode is equivalent to that obtained
861 // for all other roots of the PHI traversal. Also, when choosing one
862 // such root as representative, select the one with the most uses in order
863 // to keep the cost modeling heuristics in AddressingModeMatcher
865 unsigned NumUses = V->getNumUses();
866 if (NumUses > NumUsesConsensus) {
868 NumUsesConsensus = NumUses;
869 AddrModeInsts = NewAddrModeInsts;
878 // If the addressing mode couldn't be determined, or if multiple different
879 // ones were determined, bail out now.
880 if (!Consensus) return false;
882 // Check to see if any of the instructions supersumed by this addr mode are
883 // non-local to I's BB.
884 bool AnyNonLocal = false;
885 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
886 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
892 // If all the instructions matched are already in this BB, don't do anything.
894 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
898 // Insert this computation right after this user. Since our caller is
899 // scanning from the top of the BB to the bottom, reuse of the expr are
900 // guaranteed to happen later.
901 IRBuilder<> Builder(MemoryInst);
903 // Now that we determined the addressing expression we want to use and know
904 // that we have to sink it into this block. Check to see if we have already
905 // done this for some other load/store instr in this block. If so, reuse the
907 Value *&SunkAddr = SunkAddrs[Addr];
909 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
911 if (SunkAddr->getType() != Addr->getType())
912 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
914 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
917 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
921 // Start with the base register. Do this first so that subsequent address
922 // matching finds it last, which will prevent it from trying to match it
923 // as the scaled value in case it happens to be a mul. That would be
924 // problematic if we've sunk a different mul for the scale, because then
925 // we'd end up sinking both muls.
926 if (AddrMode.BaseReg) {
927 Value *V = AddrMode.BaseReg;
928 if (V->getType()->isPointerTy())
929 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
930 if (V->getType() != IntPtrTy)
931 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
935 // Add the scale value.
936 if (AddrMode.Scale) {
937 Value *V = AddrMode.ScaledReg;
938 if (V->getType() == IntPtrTy) {
940 } else if (V->getType()->isPointerTy()) {
941 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
942 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
943 cast<IntegerType>(V->getType())->getBitWidth()) {
944 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
946 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
948 if (AddrMode.Scale != 1)
949 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
952 Result = Builder.CreateAdd(Result, V, "sunkaddr");
957 // Add in the BaseGV if present.
958 if (AddrMode.BaseGV) {
959 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
961 Result = Builder.CreateAdd(Result, V, "sunkaddr");
966 // Add in the Base Offset if present.
967 if (AddrMode.BaseOffs) {
968 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
970 Result = Builder.CreateAdd(Result, V, "sunkaddr");
976 SunkAddr = Constant::getNullValue(Addr->getType());
978 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
981 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
983 // If we have no uses, recursively delete the value and all dead instructions
985 if (Repl->use_empty()) {
986 // This can cause recursive deletion, which can invalidate our iterator.
987 // Use a WeakVH to hold onto it in case this happens.
988 WeakVH IterHandle(CurInstIterator);
989 BasicBlock *BB = CurInstIterator->getParent();
991 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
993 if (IterHandle != CurInstIterator) {
994 // If the iterator instruction was recursively deleted, start over at the
995 // start of the block.
996 CurInstIterator = BB->begin();
999 // This address is now available for reassignment, so erase the table
1000 // entry; we don't want to match some completely different instruction.
1001 SunkAddrs[Addr] = 0;
1008 /// OptimizeInlineAsmInst - If there are any memory operands, use
1009 /// OptimizeMemoryInst to sink their address computing into the block when
1010 /// possible / profitable.
1011 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1012 bool MadeChange = false;
1014 TargetLowering::AsmOperandInfoVector
1015 TargetConstraints = TLI->ParseConstraints(CS);
1017 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1018 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1020 // Compute the constraint code and ConstraintType to use.
1021 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1023 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1024 OpInfo.isIndirect) {
1025 Value *OpVal = CS->getArgOperand(ArgNo++);
1026 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1027 } else if (OpInfo.Type == InlineAsm::isInput)
1034 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1035 /// basic block as the load, unless conditions are unfavorable. This allows
1036 /// SelectionDAG to fold the extend into the load.
1038 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1039 // Look for a load being extended.
1040 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1041 if (!LI) return false;
1043 // If they're already in the same block, there's nothing to do.
1044 if (LI->getParent() == I->getParent())
1047 // If the load has other users and the truncate is not free, this probably
1048 // isn't worthwhile.
1049 if (!LI->hasOneUse() &&
1050 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1051 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1052 !TLI->isTruncateFree(I->getType(), LI->getType()))
1055 // Check whether the target supports casts folded into loads.
1057 if (isa<ZExtInst>(I))
1058 LType = ISD::ZEXTLOAD;
1060 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1061 LType = ISD::SEXTLOAD;
1063 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1066 // Move the extend into the same block as the load, so that SelectionDAG
1068 I->removeFromParent();
1074 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1075 BasicBlock *DefBB = I->getParent();
1077 // If the result of a {s|z}ext and its source are both live out, rewrite all
1078 // other uses of the source with result of extension.
1079 Value *Src = I->getOperand(0);
1080 if (Src->hasOneUse())
1083 // Only do this xform if truncating is free.
1084 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1087 // Only safe to perform the optimization if the source is also defined in
1089 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1092 bool DefIsLiveOut = false;
1093 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1095 Instruction *User = cast<Instruction>(*UI);
1097 // Figure out which BB this ext is used in.
1098 BasicBlock *UserBB = User->getParent();
1099 if (UserBB == DefBB) continue;
1100 DefIsLiveOut = true;
1106 // Make sure non of the uses are PHI nodes.
1107 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1109 Instruction *User = cast<Instruction>(*UI);
1110 BasicBlock *UserBB = User->getParent();
1111 if (UserBB == DefBB) continue;
1112 // Be conservative. We don't want this xform to end up introducing
1113 // reloads just before load / store instructions.
1114 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1118 // InsertedTruncs - Only insert one trunc in each block once.
1119 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1121 bool MadeChange = false;
1122 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1124 Use &TheUse = UI.getUse();
1125 Instruction *User = cast<Instruction>(*UI);
1127 // Figure out which BB this ext is used in.
1128 BasicBlock *UserBB = User->getParent();
1129 if (UserBB == DefBB) continue;
1131 // Both src and def are live in this block. Rewrite the use.
1132 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1134 if (!InsertedTrunc) {
1135 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1136 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1139 // Replace a use of the {s|z}ext source with a use of the result.
1140 TheUse = InsertedTrunc;
1148 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1149 /// turned into an explicit branch.
1150 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1151 // FIXME: This should use the same heuristics as IfConversion to determine
1152 // whether a select is better represented as a branch. This requires that
1153 // branch probability metadata is preserved for the select, which is not the
1156 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1158 // If the branch is predicted right, an out of order CPU can avoid blocking on
1159 // the compare. Emit cmovs on compares with a memory operand as branches to
1160 // avoid stalls on the load from memory. If the compare has more than one use
1161 // there's probably another cmov or setcc around so it's not worth emitting a
1166 Value *CmpOp0 = Cmp->getOperand(0);
1167 Value *CmpOp1 = Cmp->getOperand(1);
1169 // We check that the memory operand has one use to avoid uses of the loaded
1170 // value directly after the compare, making branches unprofitable.
1171 return Cmp->hasOneUse() &&
1172 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1173 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1177 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1178 // If we have a SelectInst that will likely profit from branch prediction,
1179 // turn it into a branch.
1180 if (DisableSelectToBranch || OptSize || !TLI ||
1181 !TLI->isPredictableSelectExpensive())
1184 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1185 !isFormingBranchFromSelectProfitable(SI))
1190 // First, we split the block containing the select into 2 blocks.
1191 BasicBlock *StartBlock = SI->getParent();
1192 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1193 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1195 // Create a new block serving as the landing pad for the branch.
1196 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1197 NextBlock->getParent(), NextBlock);
1199 // Move the unconditional branch from the block with the select in it into our
1200 // landing pad block.
1201 StartBlock->getTerminator()->eraseFromParent();
1202 BranchInst::Create(NextBlock, SmallBlock);
1204 // Insert the real conditional branch based on the original condition.
1205 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1207 // The select itself is replaced with a PHI Node.
1208 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1210 PN->addIncoming(SI->getTrueValue(), StartBlock);
1211 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1212 SI->replaceAllUsesWith(PN);
1213 SI->eraseFromParent();
1215 // Instruct OptimizeBlock to skip to the next block.
1216 CurInstIterator = StartBlock->end();
1217 ++NumSelectsExpanded;
1221 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1222 if (PHINode *P = dyn_cast<PHINode>(I)) {
1223 // It is possible for very late stage optimizations (such as SimplifyCFG)
1224 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1225 // trivial PHI, go ahead and zap it here.
1226 if (Value *V = SimplifyInstruction(P)) {
1227 P->replaceAllUsesWith(V);
1228 P->eraseFromParent();
1235 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1236 // If the source of the cast is a constant, then this should have
1237 // already been constant folded. The only reason NOT to constant fold
1238 // it is if something (e.g. LSR) was careful to place the constant
1239 // evaluation in a block other than then one that uses it (e.g. to hoist
1240 // the address of globals out of a loop). If this is the case, we don't
1241 // want to forward-subst the cast.
1242 if (isa<Constant>(CI->getOperand(0)))
1245 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1248 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1249 bool MadeChange = MoveExtToFormExtLoad(I);
1250 return MadeChange | OptimizeExtUses(I);
1255 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1256 return OptimizeCmpExpression(CI);
1258 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1260 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1264 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1266 return OptimizeMemoryInst(I, SI->getOperand(1),
1267 SI->getOperand(0)->getType());
1271 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1272 if (GEPI->hasAllZeroIndices()) {
1273 /// The GEP operand must be a pointer, so must its result -> BitCast
1274 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1275 GEPI->getName(), GEPI);
1276 GEPI->replaceAllUsesWith(NC);
1277 GEPI->eraseFromParent();
1285 if (CallInst *CI = dyn_cast<CallInst>(I))
1286 return OptimizeCallInst(CI);
1288 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1289 return DupRetToEnableTailCallOpts(RI);
1291 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1292 return OptimizeSelectInst(SI);
1297 // In this pass we look for GEP and cast instructions that are used
1298 // across basic blocks and rewrite them to improve basic-block-at-a-time
1300 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1302 bool MadeChange = false;
1304 CurInstIterator = BB.begin();
1305 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1306 MadeChange |= OptimizeInst(CurInstIterator++);
1311 // llvm.dbg.value is far away from the value then iSel may not be able
1312 // handle it properly. iSel will drop llvm.dbg.value if it can not
1313 // find a node corresponding to the value.
1314 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1315 bool MadeChange = false;
1316 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1317 Instruction *PrevNonDbgInst = NULL;
1318 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1319 Instruction *Insn = BI; ++BI;
1320 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1322 PrevNonDbgInst = Insn;
1326 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1327 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1328 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1329 DVI->removeFromParent();
1330 if (isa<PHINode>(VI))
1331 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1333 DVI->insertAfter(VI);