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/GlobalVariable.h"
22 #include "llvm/IRBuilder.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Pass.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Analysis/InstructionSimplify.h"
32 #include "llvm/Analysis/ProfileInfo.h"
33 #include "llvm/Assembly/Writer.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/DataLayout.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/BuildLibCalls.h"
47 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
48 #include "llvm/Transforms/Utils/Local.h"
50 using namespace llvm::PatternMatch;
52 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
53 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
55 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
61 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
64 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
65 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
67 static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
71 static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
76 class CodeGenPrepare : public FunctionPass {
77 /// TLI - Keep a pointer of a TargetLowering to consult for determining
78 /// transformation profitability.
79 const TargetLowering *TLI;
80 const TargetLibraryInfo *TLInfo;
84 /// CurInstIterator - As we scan instructions optimizing them, this is the
85 /// next instruction to optimize. Xforms that can invalidate this should
87 BasicBlock::iterator CurInstIterator;
89 /// Keeps track of non-local addresses that have been sunk into a block.
90 /// This allows us to avoid inserting duplicate code for blocks with
91 /// multiple load/stores of the same address.
92 DenseMap<Value*, Value*> SunkAddrs;
94 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
98 /// OptSize - True if optimizing for size.
102 static char ID; // Pass identification, replacement for typeid
103 explicit CodeGenPrepare(const TargetLowering *tli = 0)
104 : FunctionPass(ID), TLI(tli) {
105 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
107 bool runOnFunction(Function &F);
109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addPreserved<DominatorTree>();
111 AU.addPreserved<ProfileInfo>();
112 AU.addRequired<TargetLibraryInfo>();
116 bool EliminateFallThrough(Function &F);
117 bool EliminateMostlyEmptyBlocks(Function &F);
118 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
119 void EliminateMostlyEmptyBlock(BasicBlock *BB);
120 bool OptimizeBlock(BasicBlock &BB);
121 bool OptimizeInst(Instruction *I);
122 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
123 bool OptimizeInlineAsmInst(CallInst *CS);
124 bool OptimizeCallInst(CallInst *CI);
125 bool MoveExtToFormExtLoad(Instruction *I);
126 bool OptimizeExtUses(Instruction *I);
127 bool OptimizeSelectInst(SelectInst *SI);
128 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
129 bool PlaceDbgValues(Function &F);
130 bool ConvertLoadToSwitch(LoadInst *LI);
134 char CodeGenPrepare::ID = 0;
135 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
136 "Optimize for code generation", false, false)
137 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
138 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
139 "Optimize for code generation", false, false)
141 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
142 return new CodeGenPrepare(TLI);
145 bool CodeGenPrepare::runOnFunction(Function &F) {
146 bool EverMadeChange = false;
149 TLInfo = &getAnalysis<TargetLibraryInfo>();
150 DT = getAnalysisIfAvailable<DominatorTree>();
151 PFI = getAnalysisIfAvailable<ProfileInfo>();
152 OptSize = F.getFnAttributes().hasAttribute(Attributes::OptimizeForSize);
154 /// This optimization identifies DIV instructions that can be
155 /// profitably bypassed and carried out with a shorter, faster divide.
156 if (TLI && TLI->isSlowDivBypassed()) {
157 const DenseMap<unsigned int, unsigned int> &BypassWidths =
158 TLI->getBypassSlowDivWidths();
159 for (Function::iterator I = F.begin(); I != F.end(); I++)
160 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
163 // Eliminate blocks that contain only PHI nodes and an
164 // unconditional branch.
165 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
167 // llvm.dbg.value is far away from the value then iSel may not be able
168 // handle it properly. iSel will drop llvm.dbg.value if it can not
169 // find a node corresponding to the value.
170 EverMadeChange |= PlaceDbgValues(F);
172 bool MadeChange = true;
175 for (Function::iterator I = F.begin(); I != F.end(); ) {
176 BasicBlock *BB = I++;
177 MadeChange |= OptimizeBlock(*BB);
179 EverMadeChange |= MadeChange;
184 if (!DisableBranchOpts) {
186 SmallPtrSet<BasicBlock*, 8> WorkList;
187 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
188 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
189 MadeChange |= ConstantFoldTerminator(BB, true);
190 if (!MadeChange) continue;
192 for (SmallVectorImpl<BasicBlock*>::iterator
193 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
194 if (pred_begin(*II) == pred_end(*II))
195 WorkList.insert(*II);
198 for (SmallPtrSet<BasicBlock*, 8>::iterator
199 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
202 // Merge pairs of basic blocks with unconditional branches, connected by
204 if (EverMadeChange || MadeChange)
205 MadeChange |= EliminateFallThrough(F);
209 EverMadeChange |= MadeChange;
212 if (ModifiedDT && DT)
213 DT->DT->recalculate(F);
215 return EverMadeChange;
218 /// EliminateFallThrough - Merge basic blocks which are connected
219 /// by a single edge, where one of the basic blocks has a single successor
220 /// pointing to the other basic block, which has a single predecessor.
221 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
222 bool Changed = false;
223 // Scan all of the blocks in the function, except for the entry block.
224 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
225 BasicBlock *BB = I++;
226 // If the destination block has a single pred, then this is a trivial
227 // edge, just collapse it.
228 BasicBlock *SinglePred = BB->getSinglePredecessor();
230 // Don't merge if BB's address is taken.
231 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
233 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
234 if (Term && !Term->isConditional()) {
236 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
237 // Remember if SinglePred was the entry block of the function.
238 // If so, we will need to move BB back to the entry position.
239 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
240 MergeBasicBlockIntoOnlyPred(BB, this);
242 if (isEntry && BB != &BB->getParent()->getEntryBlock())
243 BB->moveBefore(&BB->getParent()->getEntryBlock());
245 // We have erased a block. Update the iterator.
252 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
253 /// debug info directives, and an unconditional branch. Passes before isel
254 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
255 /// isel. Start by eliminating these blocks so we can split them the way we
257 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
258 bool MadeChange = false;
259 // Note that this intentionally skips the entry block.
260 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
261 BasicBlock *BB = I++;
263 // If this block doesn't end with an uncond branch, ignore it.
264 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
265 if (!BI || !BI->isUnconditional())
268 // If the instruction before the branch (skipping debug info) isn't a phi
269 // node, then other stuff is happening here.
270 BasicBlock::iterator BBI = BI;
271 if (BBI != BB->begin()) {
273 while (isa<DbgInfoIntrinsic>(BBI)) {
274 if (BBI == BB->begin())
278 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
282 // Do not break infinite loops.
283 BasicBlock *DestBB = BI->getSuccessor(0);
287 if (!CanMergeBlocks(BB, DestBB))
290 EliminateMostlyEmptyBlock(BB);
296 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
297 /// single uncond branch between them, and BB contains no other non-phi
299 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
300 const BasicBlock *DestBB) const {
301 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
302 // the successor. If there are more complex condition (e.g. preheaders),
303 // don't mess around with them.
304 BasicBlock::const_iterator BBI = BB->begin();
305 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
306 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
308 const Instruction *User = cast<Instruction>(*UI);
309 if (User->getParent() != DestBB || !isa<PHINode>(User))
311 // If User is inside DestBB block and it is a PHINode then check
312 // incoming value. If incoming value is not from BB then this is
313 // a complex condition (e.g. preheaders) we want to avoid here.
314 if (User->getParent() == DestBB) {
315 if (const PHINode *UPN = dyn_cast<PHINode>(User))
316 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
317 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
318 if (Insn && Insn->getParent() == BB &&
319 Insn->getParent() != UPN->getIncomingBlock(I))
326 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
327 // and DestBB may have conflicting incoming values for the block. If so, we
328 // can't merge the block.
329 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
330 if (!DestBBPN) return true; // no conflict.
332 // Collect the preds of BB.
333 SmallPtrSet<const BasicBlock*, 16> BBPreds;
334 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
335 // It is faster to get preds from a PHI than with pred_iterator.
336 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
337 BBPreds.insert(BBPN->getIncomingBlock(i));
339 BBPreds.insert(pred_begin(BB), pred_end(BB));
342 // Walk the preds of DestBB.
343 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
344 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
345 if (BBPreds.count(Pred)) { // Common predecessor?
346 BBI = DestBB->begin();
347 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
348 const Value *V1 = PN->getIncomingValueForBlock(Pred);
349 const Value *V2 = PN->getIncomingValueForBlock(BB);
351 // If V2 is a phi node in BB, look up what the mapped value will be.
352 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
353 if (V2PN->getParent() == BB)
354 V2 = V2PN->getIncomingValueForBlock(Pred);
356 // If there is a conflict, bail out.
357 if (V1 != V2) return false;
366 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
367 /// an unconditional branch in it.
368 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
369 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
370 BasicBlock *DestBB = BI->getSuccessor(0);
372 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
374 // If the destination block has a single pred, then this is a trivial edge,
376 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
377 if (SinglePred != DestBB) {
378 // Remember if SinglePred was the entry block of the function. If so, we
379 // will need to move BB back to the entry position.
380 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
381 MergeBasicBlockIntoOnlyPred(DestBB, this);
383 if (isEntry && BB != &BB->getParent()->getEntryBlock())
384 BB->moveBefore(&BB->getParent()->getEntryBlock());
386 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
391 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
392 // to handle the new incoming edges it is about to have.
394 for (BasicBlock::iterator BBI = DestBB->begin();
395 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
396 // Remove the incoming value for BB, and remember it.
397 Value *InVal = PN->removeIncomingValue(BB, false);
399 // Two options: either the InVal is a phi node defined in BB or it is some
400 // value that dominates BB.
401 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
402 if (InValPhi && InValPhi->getParent() == BB) {
403 // Add all of the input values of the input PHI as inputs of this phi.
404 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
405 PN->addIncoming(InValPhi->getIncomingValue(i),
406 InValPhi->getIncomingBlock(i));
408 // Otherwise, add one instance of the dominating value for each edge that
409 // we will be adding.
410 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
411 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
412 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
414 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
415 PN->addIncoming(InVal, *PI);
420 // The PHIs are now updated, change everything that refers to BB to use
421 // DestBB and remove BB.
422 BB->replaceAllUsesWith(DestBB);
423 if (DT && !ModifiedDT) {
424 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
425 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
426 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
427 DT->changeImmediateDominator(DestBB, NewIDom);
431 PFI->replaceAllUses(BB, DestBB);
432 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
434 BB->eraseFromParent();
437 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
440 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
441 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
442 /// sink it into user blocks to reduce the number of virtual
443 /// registers that must be created and coalesced.
445 /// Return true if any changes are made.
447 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
448 // If this is a noop copy,
449 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
450 EVT DstVT = TLI.getValueType(CI->getType());
452 // This is an fp<->int conversion?
453 if (SrcVT.isInteger() != DstVT.isInteger())
456 // If this is an extension, it will be a zero or sign extension, which
458 if (SrcVT.bitsLT(DstVT)) return false;
460 // If these values will be promoted, find out what they will be promoted
461 // to. This helps us consider truncates on PPC as noop copies when they
463 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
464 TargetLowering::TypePromoteInteger)
465 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
466 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
467 TargetLowering::TypePromoteInteger)
468 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
470 // If, after promotion, these are the same types, this is a noop copy.
474 BasicBlock *DefBB = CI->getParent();
476 /// InsertedCasts - Only insert a cast in each block once.
477 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
479 bool MadeChange = false;
480 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
482 Use &TheUse = UI.getUse();
483 Instruction *User = cast<Instruction>(*UI);
485 // Figure out which BB this cast is used in. For PHI's this is the
486 // appropriate predecessor block.
487 BasicBlock *UserBB = User->getParent();
488 if (PHINode *PN = dyn_cast<PHINode>(User)) {
489 UserBB = PN->getIncomingBlock(UI);
492 // Preincrement use iterator so we don't invalidate it.
495 // If this user is in the same block as the cast, don't change the cast.
496 if (UserBB == DefBB) continue;
498 // If we have already inserted a cast into this block, use it.
499 CastInst *&InsertedCast = InsertedCasts[UserBB];
502 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
504 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
509 // Replace a use of the cast with a use of the new cast.
510 TheUse = InsertedCast;
514 // If we removed all uses, nuke the cast.
515 if (CI->use_empty()) {
516 CI->eraseFromParent();
523 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
524 /// the number of virtual registers that must be created and coalesced. This is
525 /// a clear win except on targets with multiple condition code registers
526 /// (PowerPC), where it might lose; some adjustment may be wanted there.
528 /// Return true if any changes are made.
529 static bool OptimizeCmpExpression(CmpInst *CI) {
530 BasicBlock *DefBB = CI->getParent();
532 /// InsertedCmp - Only insert a cmp in each block once.
533 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
535 bool MadeChange = false;
536 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
538 Use &TheUse = UI.getUse();
539 Instruction *User = cast<Instruction>(*UI);
541 // Preincrement use iterator so we don't invalidate it.
544 // Don't bother for PHI nodes.
545 if (isa<PHINode>(User))
548 // Figure out which BB this cmp is used in.
549 BasicBlock *UserBB = User->getParent();
551 // If this user is in the same block as the cmp, don't change the cmp.
552 if (UserBB == DefBB) continue;
554 // If we have already inserted a cmp into this block, use it.
555 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
558 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
560 CmpInst::Create(CI->getOpcode(),
561 CI->getPredicate(), CI->getOperand(0),
562 CI->getOperand(1), "", InsertPt);
566 // Replace a use of the cmp with a use of the new cmp.
567 TheUse = InsertedCmp;
571 // If we removed all uses, nuke the cmp.
573 CI->eraseFromParent();
579 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
581 void replaceCall(Value *With) {
582 CI->replaceAllUsesWith(With);
583 CI->eraseFromParent();
585 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
586 if (ConstantInt *SizeCI =
587 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
588 return SizeCI->isAllOnesValue();
592 } // end anonymous namespace
594 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
595 BasicBlock *BB = CI->getParent();
597 // Lower inline assembly if we can.
598 // If we found an inline asm expession, and if the target knows how to
599 // lower it to normal LLVM code, do so now.
600 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
601 if (TLI->ExpandInlineAsm(CI)) {
602 // Avoid invalidating the iterator.
603 CurInstIterator = BB->begin();
604 // Avoid processing instructions out of order, which could cause
605 // reuse before a value is defined.
609 // Sink address computing for memory operands into the block.
610 if (OptimizeInlineAsmInst(CI))
614 // Lower all uses of llvm.objectsize.*
615 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
616 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
617 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
618 Type *ReturnTy = CI->getType();
619 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
621 // Substituting this can cause recursive simplifications, which can
622 // invalidate our iterator. Use a WeakVH to hold onto it in case this
624 WeakVH IterHandle(CurInstIterator);
626 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
627 TLInfo, ModifiedDT ? 0 : DT);
629 // If the iterator instruction was recursively deleted, start over at the
630 // start of the block.
631 if (IterHandle != CurInstIterator) {
632 CurInstIterator = BB->begin();
639 SmallVector<Value*, 2> PtrOps;
641 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
642 while (!PtrOps.empty())
643 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
647 // From here on out we're working with named functions.
648 if (CI->getCalledFunction() == 0) return false;
650 // We'll need DataLayout from here on out.
651 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
652 if (!TD) return false;
654 // Lower all default uses of _chk calls. This is very similar
655 // to what InstCombineCalls does, but here we are only lowering calls
656 // that have the default "don't know" as the objectsize. Anything else
657 // should be left alone.
658 CodeGenPrepareFortifiedLibCalls Simplifier;
659 return Simplifier.fold(CI, TD, TLInfo);
662 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
663 /// instructions to the predecessor to enable tail call optimizations. The
664 /// case it is currently looking for is:
667 /// %tmp0 = tail call i32 @f0()
670 /// %tmp1 = tail call i32 @f1()
673 /// %tmp2 = tail call i32 @f2()
676 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
684 /// %tmp0 = tail call i32 @f0()
687 /// %tmp1 = tail call i32 @f1()
690 /// %tmp2 = tail call i32 @f2()
693 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
698 BitCastInst *BCI = 0;
699 Value *V = RI->getReturnValue();
701 BCI = dyn_cast<BitCastInst>(V);
703 V = BCI->getOperand(0);
705 PN = dyn_cast<PHINode>(V);
710 BasicBlock *BB = RI->getParent();
711 if (PN && PN->getParent() != BB)
714 // It's not safe to eliminate the sign / zero extension of the return value.
715 // See llvm::isInTailCallPosition().
716 const Function *F = BB->getParent();
717 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
718 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
719 CallerRetAttr.hasAttribute(Attributes::SExt))
722 // Make sure there are no instructions between the PHI and return, or that the
723 // return is the first instruction in the block.
725 BasicBlock::iterator BI = BB->begin();
726 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
728 // Also skip over the bitcast.
733 BasicBlock::iterator BI = BB->begin();
734 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
739 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
741 SmallVector<CallInst*, 4> TailCalls;
743 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
744 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
745 // Make sure the phi value is indeed produced by the tail call.
746 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
747 TLI->mayBeEmittedAsTailCall(CI))
748 TailCalls.push_back(CI);
751 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
752 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
753 if (!VisitedBBs.insert(*PI))
756 BasicBlock::InstListType &InstList = (*PI)->getInstList();
757 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
758 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
759 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
763 CallInst *CI = dyn_cast<CallInst>(&*RI);
764 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
765 TailCalls.push_back(CI);
769 bool Changed = false;
770 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
771 CallInst *CI = TailCalls[i];
774 // Conservatively require the attributes of the call to match those of the
775 // return. Ignore noalias because it doesn't affect the call sequence.
776 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
777 if (Attributes::Builder(CalleeRetAttr ^ CallerRetAttr)
778 .removeAttribute(Attributes::NoAlias).hasAttributes())
781 // Make sure the call instruction is followed by an unconditional branch to
783 BasicBlock *CallBB = CI->getParent();
784 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
785 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
788 // Duplicate the return into CallBB.
789 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
790 ModifiedDT = Changed = true;
794 // If we eliminated all predecessors of the block, delete the block now.
795 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
796 BB->eraseFromParent();
801 //===----------------------------------------------------------------------===//
802 // Memory Optimization
803 //===----------------------------------------------------------------------===//
805 /// IsNonLocalValue - Return true if the specified values are defined in a
806 /// different basic block than BB.
807 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
808 if (Instruction *I = dyn_cast<Instruction>(V))
809 return I->getParent() != BB;
813 /// OptimizeMemoryInst - Load and Store Instructions often have
814 /// addressing modes that can do significant amounts of computation. As such,
815 /// instruction selection will try to get the load or store to do as much
816 /// computation as possible for the program. The problem is that isel can only
817 /// see within a single block. As such, we sink as much legal addressing mode
818 /// stuff into the block as possible.
820 /// This method is used to optimize both load/store and inline asms with memory
822 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
826 // Try to collapse single-value PHI nodes. This is necessary to undo
827 // unprofitable PRE transformations.
828 SmallVector<Value*, 8> worklist;
829 SmallPtrSet<Value*, 16> Visited;
830 worklist.push_back(Addr);
832 // Use a worklist to iteratively look through PHI nodes, and ensure that
833 // the addressing mode obtained from the non-PHI roots of the graph
835 Value *Consensus = 0;
836 unsigned NumUsesConsensus = 0;
837 bool IsNumUsesConsensusValid = false;
838 SmallVector<Instruction*, 16> AddrModeInsts;
839 ExtAddrMode AddrMode;
840 while (!worklist.empty()) {
841 Value *V = worklist.back();
844 // Break use-def graph loops.
845 if (!Visited.insert(V)) {
850 // For a PHI node, push all of its incoming values.
851 if (PHINode *P = dyn_cast<PHINode>(V)) {
852 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
853 worklist.push_back(P->getIncomingValue(i));
857 // For non-PHIs, determine the addressing mode being computed.
858 SmallVector<Instruction*, 16> NewAddrModeInsts;
859 ExtAddrMode NewAddrMode =
860 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
861 NewAddrModeInsts, *TLI);
863 // This check is broken into two cases with very similar code to avoid using
864 // getNumUses() as much as possible. Some values have a lot of uses, so
865 // calling getNumUses() unconditionally caused a significant compile-time
869 AddrMode = NewAddrMode;
870 AddrModeInsts = NewAddrModeInsts;
872 } else if (NewAddrMode == AddrMode) {
873 if (!IsNumUsesConsensusValid) {
874 NumUsesConsensus = Consensus->getNumUses();
875 IsNumUsesConsensusValid = true;
878 // Ensure that the obtained addressing mode is equivalent to that obtained
879 // for all other roots of the PHI traversal. Also, when choosing one
880 // such root as representative, select the one with the most uses in order
881 // to keep the cost modeling heuristics in AddressingModeMatcher
883 unsigned NumUses = V->getNumUses();
884 if (NumUses > NumUsesConsensus) {
886 NumUsesConsensus = NumUses;
887 AddrModeInsts = NewAddrModeInsts;
896 // If the addressing mode couldn't be determined, or if multiple different
897 // ones were determined, bail out now.
898 if (!Consensus) return false;
900 // Check to see if any of the instructions supersumed by this addr mode are
901 // non-local to I's BB.
902 bool AnyNonLocal = false;
903 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
904 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
910 // If all the instructions matched are already in this BB, don't do anything.
912 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
916 // Insert this computation right after this user. Since our caller is
917 // scanning from the top of the BB to the bottom, reuse of the expr are
918 // guaranteed to happen later.
919 IRBuilder<> Builder(MemoryInst);
921 // Now that we determined the addressing expression we want to use and know
922 // that we have to sink it into this block. Check to see if we have already
923 // done this for some other load/store instr in this block. If so, reuse the
925 Value *&SunkAddr = SunkAddrs[Addr];
927 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
929 if (SunkAddr->getType() != Addr->getType())
930 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
932 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
935 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
939 // Start with the base register. Do this first so that subsequent address
940 // matching finds it last, which will prevent it from trying to match it
941 // as the scaled value in case it happens to be a mul. That would be
942 // problematic if we've sunk a different mul for the scale, because then
943 // we'd end up sinking both muls.
944 if (AddrMode.BaseReg) {
945 Value *V = AddrMode.BaseReg;
946 if (V->getType()->isPointerTy())
947 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
948 if (V->getType() != IntPtrTy)
949 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
953 // Add the scale value.
954 if (AddrMode.Scale) {
955 Value *V = AddrMode.ScaledReg;
956 if (V->getType() == IntPtrTy) {
958 } else if (V->getType()->isPointerTy()) {
959 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
960 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
961 cast<IntegerType>(V->getType())->getBitWidth()) {
962 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
964 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
966 if (AddrMode.Scale != 1)
967 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
970 Result = Builder.CreateAdd(Result, V, "sunkaddr");
975 // Add in the BaseGV if present.
976 if (AddrMode.BaseGV) {
977 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
979 Result = Builder.CreateAdd(Result, V, "sunkaddr");
984 // Add in the Base Offset if present.
985 if (AddrMode.BaseOffs) {
986 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
988 Result = Builder.CreateAdd(Result, V, "sunkaddr");
994 SunkAddr = Constant::getNullValue(Addr->getType());
996 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
999 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1001 // If we have no uses, recursively delete the value and all dead instructions
1003 if (Repl->use_empty()) {
1004 // This can cause recursive deletion, which can invalidate our iterator.
1005 // Use a WeakVH to hold onto it in case this happens.
1006 WeakVH IterHandle(CurInstIterator);
1007 BasicBlock *BB = CurInstIterator->getParent();
1009 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1011 if (IterHandle != CurInstIterator) {
1012 // If the iterator instruction was recursively deleted, start over at the
1013 // start of the block.
1014 CurInstIterator = BB->begin();
1017 // This address is now available for reassignment, so erase the table
1018 // entry; we don't want to match some completely different instruction.
1019 SunkAddrs[Addr] = 0;
1026 /// OptimizeInlineAsmInst - If there are any memory operands, use
1027 /// OptimizeMemoryInst to sink their address computing into the block when
1028 /// possible / profitable.
1029 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1030 bool MadeChange = false;
1032 TargetLowering::AsmOperandInfoVector
1033 TargetConstraints = TLI->ParseConstraints(CS);
1035 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1036 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1038 // Compute the constraint code and ConstraintType to use.
1039 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1041 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1042 OpInfo.isIndirect) {
1043 Value *OpVal = CS->getArgOperand(ArgNo++);
1044 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1045 } else if (OpInfo.Type == InlineAsm::isInput)
1052 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1053 /// basic block as the load, unless conditions are unfavorable. This allows
1054 /// SelectionDAG to fold the extend into the load.
1056 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1057 // Look for a load being extended.
1058 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1059 if (!LI) return false;
1061 // If they're already in the same block, there's nothing to do.
1062 if (LI->getParent() == I->getParent())
1065 // If the load has other users and the truncate is not free, this probably
1066 // isn't worthwhile.
1067 if (!LI->hasOneUse() &&
1068 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1069 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1070 !TLI->isTruncateFree(I->getType(), LI->getType()))
1073 // Check whether the target supports casts folded into loads.
1075 if (isa<ZExtInst>(I))
1076 LType = ISD::ZEXTLOAD;
1078 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1079 LType = ISD::SEXTLOAD;
1081 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1084 // Move the extend into the same block as the load, so that SelectionDAG
1086 I->removeFromParent();
1092 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1093 BasicBlock *DefBB = I->getParent();
1095 // If the result of a {s|z}ext and its source are both live out, rewrite all
1096 // other uses of the source with result of extension.
1097 Value *Src = I->getOperand(0);
1098 if (Src->hasOneUse())
1101 // Only do this xform if truncating is free.
1102 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1105 // Only safe to perform the optimization if the source is also defined in
1107 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1110 bool DefIsLiveOut = false;
1111 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1113 Instruction *User = cast<Instruction>(*UI);
1115 // Figure out which BB this ext is used in.
1116 BasicBlock *UserBB = User->getParent();
1117 if (UserBB == DefBB) continue;
1118 DefIsLiveOut = true;
1124 // Make sure non of the uses are PHI nodes.
1125 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1127 Instruction *User = cast<Instruction>(*UI);
1128 BasicBlock *UserBB = User->getParent();
1129 if (UserBB == DefBB) continue;
1130 // Be conservative. We don't want this xform to end up introducing
1131 // reloads just before load / store instructions.
1132 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1136 // InsertedTruncs - Only insert one trunc in each block once.
1137 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1139 bool MadeChange = false;
1140 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1142 Use &TheUse = UI.getUse();
1143 Instruction *User = cast<Instruction>(*UI);
1145 // Figure out which BB this ext is used in.
1146 BasicBlock *UserBB = User->getParent();
1147 if (UserBB == DefBB) continue;
1149 // Both src and def are live in this block. Rewrite the use.
1150 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1152 if (!InsertedTrunc) {
1153 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1154 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1157 // Replace a use of the {s|z}ext source with a use of the result.
1158 TheUse = InsertedTrunc;
1166 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1167 /// turned into an explicit branch.
1168 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1169 // FIXME: This should use the same heuristics as IfConversion to determine
1170 // whether a select is better represented as a branch. This requires that
1171 // branch probability metadata is preserved for the select, which is not the
1174 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1176 // If the branch is predicted right, an out of order CPU can avoid blocking on
1177 // the compare. Emit cmovs on compares with a memory operand as branches to
1178 // avoid stalls on the load from memory. If the compare has more than one use
1179 // there's probably another cmov or setcc around so it's not worth emitting a
1184 Value *CmpOp0 = Cmp->getOperand(0);
1185 Value *CmpOp1 = Cmp->getOperand(1);
1187 // We check that the memory operand has one use to avoid uses of the loaded
1188 // value directly after the compare, making branches unprofitable.
1189 return Cmp->hasOneUse() &&
1190 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1191 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1195 /// If we have a SelectInst that will likely profit from branch prediction,
1196 /// turn it into a branch.
1197 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1198 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1200 // Can we convert the 'select' to CF ?
1201 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1204 TargetLowering::SelectSupportKind SelectKind;
1206 SelectKind = TargetLowering::VectorMaskSelect;
1207 else if (SI->getType()->isVectorTy())
1208 SelectKind = TargetLowering::ScalarCondVectorVal;
1210 SelectKind = TargetLowering::ScalarValSelect;
1212 // Do we have efficient codegen support for this kind of 'selects' ?
1213 if (TLI->isSelectSupported(SelectKind)) {
1214 // We have efficient codegen support for the select instruction.
1215 // Check if it is profitable to keep this 'select'.
1216 if (!TLI->isPredictableSelectExpensive() ||
1217 !isFormingBranchFromSelectProfitable(SI))
1223 // First, we split the block containing the select into 2 blocks.
1224 BasicBlock *StartBlock = SI->getParent();
1225 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1226 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1228 // Create a new block serving as the landing pad for the branch.
1229 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1230 NextBlock->getParent(), NextBlock);
1232 // Move the unconditional branch from the block with the select in it into our
1233 // landing pad block.
1234 StartBlock->getTerminator()->eraseFromParent();
1235 BranchInst::Create(NextBlock, SmallBlock);
1237 // Insert the real conditional branch based on the original condition.
1238 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1240 // The select itself is replaced with a PHI Node.
1241 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1243 PN->addIncoming(SI->getTrueValue(), StartBlock);
1244 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1245 SI->replaceAllUsesWith(PN);
1246 SI->eraseFromParent();
1248 // Instruct OptimizeBlock to skip to the next block.
1249 CurInstIterator = StartBlock->end();
1250 ++NumSelectsExpanded;
1254 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1255 if (PHINode *P = dyn_cast<PHINode>(I)) {
1256 // It is possible for very late stage optimizations (such as SimplifyCFG)
1257 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1258 // trivial PHI, go ahead and zap it here.
1259 if (Value *V = SimplifyInstruction(P)) {
1260 P->replaceAllUsesWith(V);
1261 P->eraseFromParent();
1268 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1269 // If the source of the cast is a constant, then this should have
1270 // already been constant folded. The only reason NOT to constant fold
1271 // it is if something (e.g. LSR) was careful to place the constant
1272 // evaluation in a block other than then one that uses it (e.g. to hoist
1273 // the address of globals out of a loop). If this is the case, we don't
1274 // want to forward-subst the cast.
1275 if (isa<Constant>(CI->getOperand(0)))
1278 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1281 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1282 bool MadeChange = MoveExtToFormExtLoad(I);
1283 return MadeChange | OptimizeExtUses(I);
1288 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1289 return OptimizeCmpExpression(CI);
1291 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1292 bool Changed = false;
1294 Changed |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1295 Changed |= ConvertLoadToSwitch(LI);
1299 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1301 return OptimizeMemoryInst(I, SI->getOperand(1),
1302 SI->getOperand(0)->getType());
1306 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1307 if (GEPI->hasAllZeroIndices()) {
1308 /// The GEP operand must be a pointer, so must its result -> BitCast
1309 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1310 GEPI->getName(), GEPI);
1311 GEPI->replaceAllUsesWith(NC);
1312 GEPI->eraseFromParent();
1320 if (CallInst *CI = dyn_cast<CallInst>(I))
1321 return OptimizeCallInst(CI);
1323 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1324 return DupRetToEnableTailCallOpts(RI);
1326 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1327 return OptimizeSelectInst(SI);
1332 // In this pass we look for GEP and cast instructions that are used
1333 // across basic blocks and rewrite them to improve basic-block-at-a-time
1335 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1337 bool MadeChange = false;
1339 CurInstIterator = BB.begin();
1340 while (CurInstIterator != BB.end())
1341 MadeChange |= OptimizeInst(CurInstIterator++);
1346 // llvm.dbg.value is far away from the value then iSel may not be able
1347 // handle it properly. iSel will drop llvm.dbg.value if it can not
1348 // find a node corresponding to the value.
1349 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1350 bool MadeChange = false;
1351 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1352 Instruction *PrevNonDbgInst = NULL;
1353 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1354 Instruction *Insn = BI; ++BI;
1355 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1357 PrevNonDbgInst = Insn;
1361 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1362 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1363 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1364 DVI->removeFromParent();
1365 if (isa<PHINode>(VI))
1366 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1368 DVI->insertAfter(VI);
1377 static bool TargetSupportsJumpTables(const TargetLowering &TLI) {
1378 return TLI.supportJumpTables() &&
1379 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1380 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1383 /// ConvertLoadToSwitch - Convert loads from constant lookup tables into
1384 /// switches. This undos the switch-to-lookup table transformation in
1385 /// SimplifyCFG for targets where that is inprofitable.
1386 bool CodeGenPrepare::ConvertLoadToSwitch(LoadInst *LI) {
1387 // This only applies to targets that don't support jump tables.
1388 if (!TLI || TargetSupportsJumpTables(*TLI))
1391 // FIXME: In the future, it would be desirable to have enough target
1392 // information in SimplifyCFG, so we could decide at that stage whether to
1393 // transform the switch to a lookup table or not, and this
1394 // reverse-transformation could be removed.
1396 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
1397 if (!GEP || !GEP->isInBounds() || GEP->getPointerAddressSpace())
1399 if (GEP->getNumIndices() != 2)
1401 Value *FirstIndex = GEP->idx_begin()[0];
1402 ConstantInt *FirstIndexInt = dyn_cast<ConstantInt>(FirstIndex);
1403 if (!FirstIndexInt || !FirstIndexInt->isZero())
1406 Value *TableIndex = GEP->idx_begin()[1];
1407 IntegerType *TableIndexTy = cast<IntegerType>(TableIndex->getType());
1409 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1410 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1413 Constant *Arr = GV->getInitializer();
1414 uint64_t NumElements;
1415 if (ConstantArray *CA = dyn_cast<ConstantArray>(Arr))
1416 NumElements = CA->getType()->getNumElements();
1417 else if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Arr))
1418 NumElements = CDA->getNumElements();
1421 if (NumElements < 2)
1425 BasicBlock *OriginalBB = LI->getParent();
1426 BasicBlock *PostSwitchBB = OriginalBB->splitBasicBlock(LI);
1428 // Replace OriginalBB's terminator with a switch.
1429 IRBuilder<> Builder(OriginalBB->getTerminator());
1430 SwitchInst *Switch = Builder.CreateSwitch(TableIndex, PostSwitchBB,
1432 OriginalBB->getTerminator()->eraseFromParent();
1434 // Count the frequency of each value to decide which to use as default.
1435 SmallDenseMap<Constant*, uint64_t> ValueFreq;
1436 for (uint64_t I = 0; I < NumElements; ++I)
1437 ++ValueFreq[Arr->getAggregateElement(I)];
1438 uint64_t MaxCount = 0;
1439 Constant *DefaultValue = NULL;
1440 for (SmallDenseMap<Constant*, uint64_t>::iterator I = ValueFreq.begin(),
1441 E = ValueFreq.end(); I != E; ++I) {
1442 if (I->second > MaxCount) {
1443 MaxCount = I->second;
1444 DefaultValue = I->first;
1447 assert(DefaultValue && "No values in the array?");
1449 // Create the phi node in PostSwitchBB, which will replace the load.
1450 Builder.SetInsertPoint(PostSwitchBB->begin());
1451 PHINode *PHI = Builder.CreatePHI(LI->getType(), NumElements);
1452 PHI->addIncoming(DefaultValue, OriginalBB);
1454 // Build basic blocks to target with the switch.
1455 for (uint64_t I = 0; I < NumElements; ++I) {
1456 Constant *C = Arr->getAggregateElement(I);
1457 if (C == DefaultValue) continue; // Already covered by the default case.
1459 BasicBlock *BB = BasicBlock::Create(PostSwitchBB->getContext(),
1461 PostSwitchBB->getParent(),
1463 Switch->addCase(ConstantInt::get(TableIndexTy, I), BB);
1464 Builder.SetInsertPoint(BB);
1465 Builder.CreateBr(PostSwitchBB);
1466 PHI->addIncoming(C, BB);
1470 LI->replaceAllUsesWith(PHI);
1471 LI->eraseFromParent();
1474 if (GEP->use_empty())
1475 GEP->eraseFromParent();
1476 if (GV->hasUnnamedAddr() && GV->hasPrivateLinkage() && GV->use_empty())
1477 GV->eraseFromParent();
1479 CurInstIterator = Switch;