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/Module.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/DominatorInternals.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/ProfileInfo.h"
34 #include "llvm/Assembly/Writer.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/PatternMatch.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/DataLayout.h"
43 #include "llvm/Target/TargetLibraryInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/BuildLibCalls.h"
48 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
49 #include "llvm/Transforms/Utils/Local.h"
51 using namespace llvm::PatternMatch;
53 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
54 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
55 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
56 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
58 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
60 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
61 "computations were sunk");
62 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
63 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
64 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
65 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
66 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
68 static cl::opt<bool> DisableBranchOpts(
69 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
70 cl::desc("Disable branch optimizations in CodeGenPrepare"));
72 static cl::opt<bool> DisableSelectToBranch(
73 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
74 cl::desc("Disable select to branch conversion."));
77 class CodeGenPrepare : public FunctionPass {
78 /// TLI - Keep a pointer of a TargetLowering to consult for determining
79 /// transformation profitability.
80 const TargetLowering *TLI;
81 const TargetLibraryInfo *TLInfo;
85 /// CurInstIterator - As we scan instructions optimizing them, this is the
86 /// next instruction to optimize. Xforms that can invalidate this should
88 BasicBlock::iterator CurInstIterator;
90 /// Keeps track of non-local addresses that have been sunk into a block.
91 /// This allows us to avoid inserting duplicate code for blocks with
92 /// multiple load/stores of the same address.
93 DenseMap<Value*, Value*> SunkAddrs;
95 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
99 /// OptSize - True if optimizing for size.
103 static char ID; // Pass identification, replacement for typeid
104 explicit CodeGenPrepare(const TargetLowering *tli = 0)
105 : FunctionPass(ID), TLI(tli) {
106 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
108 bool runOnFunction(Function &F);
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.addPreserved<DominatorTree>();
112 AU.addPreserved<ProfileInfo>();
113 AU.addRequired<TargetLibraryInfo>();
117 bool EliminateFallThrough(Function &F);
118 bool EliminateMostlyEmptyBlocks(Function &F);
119 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
120 void EliminateMostlyEmptyBlock(BasicBlock *BB);
121 bool OptimizeBlock(BasicBlock &BB);
122 bool OptimizeInst(Instruction *I);
123 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
124 bool OptimizeInlineAsmInst(CallInst *CS);
125 bool OptimizeCallInst(CallInst *CI);
126 bool MoveExtToFormExtLoad(Instruction *I);
127 bool OptimizeExtUses(Instruction *I);
128 bool OptimizeSelectInst(SelectInst *SI);
129 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
130 bool PlaceDbgValues(Function &F);
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 SmallPtrSet<BasicBlock*, 8> LPadList;
188 SmallVector<BasicBlock*, 8> ReturnList;
189 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
190 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
191 if (BB->isLandingPad()) LPadList.insert(BB);
192 if (isa<ReturnInst>(BB->getTerminator())) ReturnList.push_back(BB);
193 MadeChange |= ConstantFoldTerminator(BB, true);
194 if (!MadeChange) continue;
196 for (SmallVectorImpl<BasicBlock*>::iterator
197 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
198 if (pred_begin(*II) == pred_end(*II))
199 WorkList.insert(*II);
202 // Delete the dead blocks and any of their dead successors.
203 bool HadLPads = !LPadList.empty();
204 while (!WorkList.empty()) {
205 BasicBlock *BB = *WorkList.begin();
208 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
212 for (SmallVectorImpl<BasicBlock*>::iterator
213 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
214 if (pred_begin(*II) == pred_end(*II))
215 WorkList.insert(*II);
218 if (HadLPads && LPadList.empty()) {
219 // All of the landing pads were removed. Get rid of the SjLj EH context
221 Module *M = F.getParent();
223 // These functions must exist if we have SjLj EH code to clean up.
224 Constant *RegisterFn = M->getFunction("_Unwind_SjLj_Register");
225 Constant *UnregisterFn = M->getFunction("_Unwind_SjLj_Unregister");
228 Constant *LSDAAddrFn =
229 Intrinsic::getDeclaration(M, Intrinsic::eh_sjlj_lsda);
230 Constant *FrameAddrFn =
231 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
232 Constant *StackAddrFn =
233 Intrinsic::getDeclaration(M, Intrinsic::stacksave);
234 Constant *BuiltinSetjmpFn =
235 Intrinsic::getDeclaration(M, Intrinsic::eh_sjlj_setjmp);
236 Constant *FuncCtxFn =
237 Intrinsic::getDeclaration(M, Intrinsic::eh_sjlj_functioncontext);
239 BasicBlock &Entry = F.getEntryBlock();
240 SmallVector<Instruction*, 8> DeadInsts;
241 for (BasicBlock::iterator I = Entry.begin(), E = Entry.end();
243 if (CallInst *CI = dyn_cast<CallInst>(I)) {
244 Value *Callee = CI->getCalledValue();
246 if (Callee != LSDAAddrFn && Callee != FrameAddrFn &&
247 Callee != StackAddrFn && Callee != BuiltinSetjmpFn &&
248 Callee != FuncCtxFn && Callee != RegisterFn)
252 Type *Ty = CI->getType();
254 CI->replaceAllUsesWith(UndefValue::get(Ty));
255 DeadInsts.push_back(CI);
260 // Find and remove the unregister calls.
261 for (SmallVectorImpl<BasicBlock*>::iterator I = ReturnList.begin(),
262 E = ReturnList.end(); I != E; ++I) {
264 typedef BasicBlock::InstListType::reverse_iterator reverse_iterator;
266 for (reverse_iterator II = BB->getInstList().rbegin(),
267 IE = BB->getInstList().rend(); II != IE; ++II) {
268 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
269 Value *Callee = CI->getCalledValue();
271 if (Callee == UnregisterFn) {
272 DeadInsts.push_back(CI);
279 // Kill the dead instructions.
280 for (SmallVectorImpl<Instruction*>::iterator I = DeadInsts.begin(),
281 E = DeadInsts.end(); I != E; ++I)
282 (*I)->eraseFromParent();
286 // Merge pairs of basic blocks with unconditional branches, connected by
288 if (EverMadeChange || MadeChange)
289 MadeChange |= EliminateFallThrough(F);
293 EverMadeChange |= MadeChange;
296 if (ModifiedDT && DT)
297 DT->DT->recalculate(F);
299 return EverMadeChange;
302 /// EliminateFallThrough - Merge basic blocks which are connected
303 /// by a single edge, where one of the basic blocks has a single successor
304 /// pointing to the other basic block, which has a single predecessor.
305 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
306 bool Changed = false;
307 // Scan all of the blocks in the function, except for the entry block.
308 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
309 BasicBlock *BB = I++;
310 // If the destination block has a single pred, then this is a trivial
311 // edge, just collapse it.
312 BasicBlock *SinglePred = BB->getSinglePredecessor();
314 // Don't merge if BB's address is taken.
315 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
317 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
318 if (Term && !Term->isConditional()) {
320 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
321 // Remember if SinglePred was the entry block of the function.
322 // If so, we will need to move BB back to the entry position.
323 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
324 MergeBasicBlockIntoOnlyPred(BB, this);
326 if (isEntry && BB != &BB->getParent()->getEntryBlock())
327 BB->moveBefore(&BB->getParent()->getEntryBlock());
329 // We have erased a block. Update the iterator.
336 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
337 /// debug info directives, and an unconditional branch. Passes before isel
338 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
339 /// isel. Start by eliminating these blocks so we can split them the way we
341 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
342 bool MadeChange = false;
343 // Note that this intentionally skips the entry block.
344 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
345 BasicBlock *BB = I++;
347 // If this block doesn't end with an uncond branch, ignore it.
348 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
349 if (!BI || !BI->isUnconditional())
352 // If the instruction before the branch (skipping debug info) isn't a phi
353 // node, then other stuff is happening here.
354 BasicBlock::iterator BBI = BI;
355 if (BBI != BB->begin()) {
357 while (isa<DbgInfoIntrinsic>(BBI)) {
358 if (BBI == BB->begin())
362 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
366 // Do not break infinite loops.
367 BasicBlock *DestBB = BI->getSuccessor(0);
371 if (!CanMergeBlocks(BB, DestBB))
374 EliminateMostlyEmptyBlock(BB);
380 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
381 /// single uncond branch between them, and BB contains no other non-phi
383 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
384 const BasicBlock *DestBB) const {
385 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
386 // the successor. If there are more complex condition (e.g. preheaders),
387 // don't mess around with them.
388 BasicBlock::const_iterator BBI = BB->begin();
389 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
390 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
392 const Instruction *User = cast<Instruction>(*UI);
393 if (User->getParent() != DestBB || !isa<PHINode>(User))
395 // If User is inside DestBB block and it is a PHINode then check
396 // incoming value. If incoming value is not from BB then this is
397 // a complex condition (e.g. preheaders) we want to avoid here.
398 if (User->getParent() == DestBB) {
399 if (const PHINode *UPN = dyn_cast<PHINode>(User))
400 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
401 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
402 if (Insn && Insn->getParent() == BB &&
403 Insn->getParent() != UPN->getIncomingBlock(I))
410 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
411 // and DestBB may have conflicting incoming values for the block. If so, we
412 // can't merge the block.
413 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
414 if (!DestBBPN) return true; // no conflict.
416 // Collect the preds of BB.
417 SmallPtrSet<const BasicBlock*, 16> BBPreds;
418 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
419 // It is faster to get preds from a PHI than with pred_iterator.
420 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
421 BBPreds.insert(BBPN->getIncomingBlock(i));
423 BBPreds.insert(pred_begin(BB), pred_end(BB));
426 // Walk the preds of DestBB.
427 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
428 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
429 if (BBPreds.count(Pred)) { // Common predecessor?
430 BBI = DestBB->begin();
431 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
432 const Value *V1 = PN->getIncomingValueForBlock(Pred);
433 const Value *V2 = PN->getIncomingValueForBlock(BB);
435 // If V2 is a phi node in BB, look up what the mapped value will be.
436 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
437 if (V2PN->getParent() == BB)
438 V2 = V2PN->getIncomingValueForBlock(Pred);
440 // If there is a conflict, bail out.
441 if (V1 != V2) return false;
450 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
451 /// an unconditional branch in it.
452 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
453 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
454 BasicBlock *DestBB = BI->getSuccessor(0);
456 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
458 // If the destination block has a single pred, then this is a trivial edge,
460 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
461 if (SinglePred != DestBB) {
462 // Remember if SinglePred was the entry block of the function. If so, we
463 // will need to move BB back to the entry position.
464 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
465 MergeBasicBlockIntoOnlyPred(DestBB, this);
467 if (isEntry && BB != &BB->getParent()->getEntryBlock())
468 BB->moveBefore(&BB->getParent()->getEntryBlock());
470 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
475 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
476 // to handle the new incoming edges it is about to have.
478 for (BasicBlock::iterator BBI = DestBB->begin();
479 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
480 // Remove the incoming value for BB, and remember it.
481 Value *InVal = PN->removeIncomingValue(BB, false);
483 // Two options: either the InVal is a phi node defined in BB or it is some
484 // value that dominates BB.
485 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
486 if (InValPhi && InValPhi->getParent() == BB) {
487 // Add all of the input values of the input PHI as inputs of this phi.
488 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
489 PN->addIncoming(InValPhi->getIncomingValue(i),
490 InValPhi->getIncomingBlock(i));
492 // Otherwise, add one instance of the dominating value for each edge that
493 // we will be adding.
494 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
495 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
496 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
498 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
499 PN->addIncoming(InVal, *PI);
504 // The PHIs are now updated, change everything that refers to BB to use
505 // DestBB and remove BB.
506 BB->replaceAllUsesWith(DestBB);
507 if (DT && !ModifiedDT) {
508 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
509 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
510 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
511 DT->changeImmediateDominator(DestBB, NewIDom);
515 PFI->replaceAllUses(BB, DestBB);
516 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
518 BB->eraseFromParent();
521 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
524 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
525 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
526 /// sink it into user blocks to reduce the number of virtual
527 /// registers that must be created and coalesced.
529 /// Return true if any changes are made.
531 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
532 // If this is a noop copy,
533 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
534 EVT DstVT = TLI.getValueType(CI->getType());
536 // This is an fp<->int conversion?
537 if (SrcVT.isInteger() != DstVT.isInteger())
540 // If this is an extension, it will be a zero or sign extension, which
542 if (SrcVT.bitsLT(DstVT)) return false;
544 // If these values will be promoted, find out what they will be promoted
545 // to. This helps us consider truncates on PPC as noop copies when they
547 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
548 TargetLowering::TypePromoteInteger)
549 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
550 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
551 TargetLowering::TypePromoteInteger)
552 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
554 // If, after promotion, these are the same types, this is a noop copy.
558 BasicBlock *DefBB = CI->getParent();
560 /// InsertedCasts - Only insert a cast in each block once.
561 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
563 bool MadeChange = false;
564 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
566 Use &TheUse = UI.getUse();
567 Instruction *User = cast<Instruction>(*UI);
569 // Figure out which BB this cast is used in. For PHI's this is the
570 // appropriate predecessor block.
571 BasicBlock *UserBB = User->getParent();
572 if (PHINode *PN = dyn_cast<PHINode>(User)) {
573 UserBB = PN->getIncomingBlock(UI);
576 // Preincrement use iterator so we don't invalidate it.
579 // If this user is in the same block as the cast, don't change the cast.
580 if (UserBB == DefBB) continue;
582 // If we have already inserted a cast into this block, use it.
583 CastInst *&InsertedCast = InsertedCasts[UserBB];
586 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
588 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
593 // Replace a use of the cast with a use of the new cast.
594 TheUse = InsertedCast;
598 // If we removed all uses, nuke the cast.
599 if (CI->use_empty()) {
600 CI->eraseFromParent();
607 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
608 /// the number of virtual registers that must be created and coalesced. This is
609 /// a clear win except on targets with multiple condition code registers
610 /// (PowerPC), where it might lose; some adjustment may be wanted there.
612 /// Return true if any changes are made.
613 static bool OptimizeCmpExpression(CmpInst *CI) {
614 BasicBlock *DefBB = CI->getParent();
616 /// InsertedCmp - Only insert a cmp in each block once.
617 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
619 bool MadeChange = false;
620 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
622 Use &TheUse = UI.getUse();
623 Instruction *User = cast<Instruction>(*UI);
625 // Preincrement use iterator so we don't invalidate it.
628 // Don't bother for PHI nodes.
629 if (isa<PHINode>(User))
632 // Figure out which BB this cmp is used in.
633 BasicBlock *UserBB = User->getParent();
635 // If this user is in the same block as the cmp, don't change the cmp.
636 if (UserBB == DefBB) continue;
638 // If we have already inserted a cmp into this block, use it.
639 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
642 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
644 CmpInst::Create(CI->getOpcode(),
645 CI->getPredicate(), CI->getOperand(0),
646 CI->getOperand(1), "", InsertPt);
650 // Replace a use of the cmp with a use of the new cmp.
651 TheUse = InsertedCmp;
655 // If we removed all uses, nuke the cmp.
657 CI->eraseFromParent();
663 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
665 void replaceCall(Value *With) {
666 CI->replaceAllUsesWith(With);
667 CI->eraseFromParent();
669 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
670 if (ConstantInt *SizeCI =
671 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
672 return SizeCI->isAllOnesValue();
676 } // end anonymous namespace
678 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
679 BasicBlock *BB = CI->getParent();
681 // Lower inline assembly if we can.
682 // If we found an inline asm expession, and if the target knows how to
683 // lower it to normal LLVM code, do so now.
684 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
685 if (TLI->ExpandInlineAsm(CI)) {
686 // Avoid invalidating the iterator.
687 CurInstIterator = BB->begin();
688 // Avoid processing instructions out of order, which could cause
689 // reuse before a value is defined.
693 // Sink address computing for memory operands into the block.
694 if (OptimizeInlineAsmInst(CI))
698 // Lower all uses of llvm.objectsize.*
699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
700 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
701 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
702 Type *ReturnTy = CI->getType();
703 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
705 // Substituting this can cause recursive simplifications, which can
706 // invalidate our iterator. Use a WeakVH to hold onto it in case this
708 WeakVH IterHandle(CurInstIterator);
710 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
711 TLInfo, ModifiedDT ? 0 : DT);
713 // If the iterator instruction was recursively deleted, start over at the
714 // start of the block.
715 if (IterHandle != CurInstIterator) {
716 CurInstIterator = BB->begin();
723 SmallVector<Value*, 2> PtrOps;
725 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
726 while (!PtrOps.empty())
727 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
731 // From here on out we're working with named functions.
732 if (CI->getCalledFunction() == 0) return false;
734 // We'll need DataLayout from here on out.
735 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
736 if (!TD) return false;
738 // Lower all default uses of _chk calls. This is very similar
739 // to what InstCombineCalls does, but here we are only lowering calls
740 // that have the default "don't know" as the objectsize. Anything else
741 // should be left alone.
742 CodeGenPrepareFortifiedLibCalls Simplifier;
743 return Simplifier.fold(CI, TD, TLInfo);
746 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
747 /// instructions to the predecessor to enable tail call optimizations. The
748 /// case it is currently looking for is:
751 /// %tmp0 = tail call i32 @f0()
754 /// %tmp1 = tail call i32 @f1()
757 /// %tmp2 = tail call i32 @f2()
760 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
768 /// %tmp0 = tail call i32 @f0()
771 /// %tmp1 = tail call i32 @f1()
774 /// %tmp2 = tail call i32 @f2()
777 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
781 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
786 BitCastInst *BCI = 0;
787 Value *V = RI->getReturnValue();
789 BCI = dyn_cast<BitCastInst>(V);
791 V = BCI->getOperand(0);
793 PN = dyn_cast<PHINode>(V);
798 if (PN && PN->getParent() != BB)
801 // It's not safe to eliminate the sign / zero extension of the return value.
802 // See llvm::isInTailCallPosition().
803 const Function *F = BB->getParent();
804 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
805 if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
806 CallerRetAttr.hasAttribute(Attributes::SExt))
809 // Make sure there are no instructions between the PHI and return, or that the
810 // return is the first instruction in the block.
812 BasicBlock::iterator BI = BB->begin();
813 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
815 // Also skip over the bitcast.
820 BasicBlock::iterator BI = BB->begin();
821 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
826 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
828 SmallVector<CallInst*, 4> TailCalls;
830 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
831 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
832 // Make sure the phi value is indeed produced by the tail call.
833 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
834 TLI->mayBeEmittedAsTailCall(CI))
835 TailCalls.push_back(CI);
838 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
839 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
840 if (!VisitedBBs.insert(*PI))
843 BasicBlock::InstListType &InstList = (*PI)->getInstList();
844 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
845 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
846 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
850 CallInst *CI = dyn_cast<CallInst>(&*RI);
851 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
852 TailCalls.push_back(CI);
856 bool Changed = false;
857 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
858 CallInst *CI = TailCalls[i];
861 // Conservatively require the attributes of the call to match those of the
862 // return. Ignore noalias because it doesn't affect the call sequence.
863 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
864 if (AttrBuilder(CalleeRetAttr).
865 removeAttribute(Attributes::NoAlias) !=
866 AttrBuilder(CallerRetAttr).
867 removeAttribute(Attributes::NoAlias))
870 // Make sure the call instruction is followed by an unconditional branch to
872 BasicBlock *CallBB = CI->getParent();
873 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
874 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
877 // Duplicate the return into CallBB.
878 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
879 ModifiedDT = Changed = true;
883 // If we eliminated all predecessors of the block, delete the block now.
884 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
885 BB->eraseFromParent();
890 //===----------------------------------------------------------------------===//
891 // Memory Optimization
892 //===----------------------------------------------------------------------===//
894 /// IsNonLocalValue - Return true if the specified values are defined in a
895 /// different basic block than BB.
896 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
897 if (Instruction *I = dyn_cast<Instruction>(V))
898 return I->getParent() != BB;
902 /// OptimizeMemoryInst - Load and Store Instructions often have
903 /// addressing modes that can do significant amounts of computation. As such,
904 /// instruction selection will try to get the load or store to do as much
905 /// computation as possible for the program. The problem is that isel can only
906 /// see within a single block. As such, we sink as much legal addressing mode
907 /// stuff into the block as possible.
909 /// This method is used to optimize both load/store and inline asms with memory
911 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
915 // Try to collapse single-value PHI nodes. This is necessary to undo
916 // unprofitable PRE transformations.
917 SmallVector<Value*, 8> worklist;
918 SmallPtrSet<Value*, 16> Visited;
919 worklist.push_back(Addr);
921 // Use a worklist to iteratively look through PHI nodes, and ensure that
922 // the addressing mode obtained from the non-PHI roots of the graph
924 Value *Consensus = 0;
925 unsigned NumUsesConsensus = 0;
926 bool IsNumUsesConsensusValid = false;
927 SmallVector<Instruction*, 16> AddrModeInsts;
928 ExtAddrMode AddrMode;
929 while (!worklist.empty()) {
930 Value *V = worklist.back();
933 // Break use-def graph loops.
934 if (!Visited.insert(V)) {
939 // For a PHI node, push all of its incoming values.
940 if (PHINode *P = dyn_cast<PHINode>(V)) {
941 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
942 worklist.push_back(P->getIncomingValue(i));
946 // For non-PHIs, determine the addressing mode being computed.
947 SmallVector<Instruction*, 16> NewAddrModeInsts;
948 ExtAddrMode NewAddrMode =
949 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
950 NewAddrModeInsts, *TLI);
952 // This check is broken into two cases with very similar code to avoid using
953 // getNumUses() as much as possible. Some values have a lot of uses, so
954 // calling getNumUses() unconditionally caused a significant compile-time
958 AddrMode = NewAddrMode;
959 AddrModeInsts = NewAddrModeInsts;
961 } else if (NewAddrMode == AddrMode) {
962 if (!IsNumUsesConsensusValid) {
963 NumUsesConsensus = Consensus->getNumUses();
964 IsNumUsesConsensusValid = true;
967 // Ensure that the obtained addressing mode is equivalent to that obtained
968 // for all other roots of the PHI traversal. Also, when choosing one
969 // such root as representative, select the one with the most uses in order
970 // to keep the cost modeling heuristics in AddressingModeMatcher
972 unsigned NumUses = V->getNumUses();
973 if (NumUses > NumUsesConsensus) {
975 NumUsesConsensus = NumUses;
976 AddrModeInsts = NewAddrModeInsts;
985 // If the addressing mode couldn't be determined, or if multiple different
986 // ones were determined, bail out now.
987 if (!Consensus) return false;
989 // Check to see if any of the instructions supersumed by this addr mode are
990 // non-local to I's BB.
991 bool AnyNonLocal = false;
992 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
993 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
999 // If all the instructions matched are already in this BB, don't do anything.
1001 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
1005 // Insert this computation right after this user. Since our caller is
1006 // scanning from the top of the BB to the bottom, reuse of the expr are
1007 // guaranteed to happen later.
1008 IRBuilder<> Builder(MemoryInst);
1010 // Now that we determined the addressing expression we want to use and know
1011 // that we have to sink it into this block. Check to see if we have already
1012 // done this for some other load/store instr in this block. If so, reuse the
1014 Value *&SunkAddr = SunkAddrs[Addr];
1016 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
1018 if (SunkAddr->getType() != Addr->getType())
1019 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
1021 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
1024 TLI->getDataLayout()->getIntPtrType(AccessTy->getContext());
1028 // Start with the base register. Do this first so that subsequent address
1029 // matching finds it last, which will prevent it from trying to match it
1030 // as the scaled value in case it happens to be a mul. That would be
1031 // problematic if we've sunk a different mul for the scale, because then
1032 // we'd end up sinking both muls.
1033 if (AddrMode.BaseReg) {
1034 Value *V = AddrMode.BaseReg;
1035 if (V->getType()->isPointerTy())
1036 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1037 if (V->getType() != IntPtrTy)
1038 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
1042 // Add the scale value.
1043 if (AddrMode.Scale) {
1044 Value *V = AddrMode.ScaledReg;
1045 if (V->getType() == IntPtrTy) {
1047 } else if (V->getType()->isPointerTy()) {
1048 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1049 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1050 cast<IntegerType>(V->getType())->getBitWidth()) {
1051 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
1053 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
1055 if (AddrMode.Scale != 1)
1056 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
1059 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1064 // Add in the BaseGV if present.
1065 if (AddrMode.BaseGV) {
1066 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
1068 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1073 // Add in the Base Offset if present.
1074 if (AddrMode.BaseOffs) {
1075 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1077 Result = Builder.CreateAdd(Result, V, "sunkaddr");
1083 SunkAddr = Constant::getNullValue(Addr->getType());
1085 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1088 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1090 // If we have no uses, recursively delete the value and all dead instructions
1092 if (Repl->use_empty()) {
1093 // This can cause recursive deletion, which can invalidate our iterator.
1094 // Use a WeakVH to hold onto it in case this happens.
1095 WeakVH IterHandle(CurInstIterator);
1096 BasicBlock *BB = CurInstIterator->getParent();
1098 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1100 if (IterHandle != CurInstIterator) {
1101 // If the iterator instruction was recursively deleted, start over at the
1102 // start of the block.
1103 CurInstIterator = BB->begin();
1106 // This address is now available for reassignment, so erase the table
1107 // entry; we don't want to match some completely different instruction.
1108 SunkAddrs[Addr] = 0;
1115 /// OptimizeInlineAsmInst - If there are any memory operands, use
1116 /// OptimizeMemoryInst to sink their address computing into the block when
1117 /// possible / profitable.
1118 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1119 bool MadeChange = false;
1121 TargetLowering::AsmOperandInfoVector
1122 TargetConstraints = TLI->ParseConstraints(CS);
1124 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1125 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1127 // Compute the constraint code and ConstraintType to use.
1128 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1130 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1131 OpInfo.isIndirect) {
1132 Value *OpVal = CS->getArgOperand(ArgNo++);
1133 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1134 } else if (OpInfo.Type == InlineAsm::isInput)
1141 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1142 /// basic block as the load, unless conditions are unfavorable. This allows
1143 /// SelectionDAG to fold the extend into the load.
1145 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1146 // Look for a load being extended.
1147 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1148 if (!LI) return false;
1150 // If they're already in the same block, there's nothing to do.
1151 if (LI->getParent() == I->getParent())
1154 // If the load has other users and the truncate is not free, this probably
1155 // isn't worthwhile.
1156 if (!LI->hasOneUse() &&
1157 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1158 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1159 !TLI->isTruncateFree(I->getType(), LI->getType()))
1162 // Check whether the target supports casts folded into loads.
1164 if (isa<ZExtInst>(I))
1165 LType = ISD::ZEXTLOAD;
1167 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1168 LType = ISD::SEXTLOAD;
1170 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1173 // Move the extend into the same block as the load, so that SelectionDAG
1175 I->removeFromParent();
1181 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1182 BasicBlock *DefBB = I->getParent();
1184 // If the result of a {s|z}ext and its source are both live out, rewrite all
1185 // other uses of the source with result of extension.
1186 Value *Src = I->getOperand(0);
1187 if (Src->hasOneUse())
1190 // Only do this xform if truncating is free.
1191 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1194 // Only safe to perform the optimization if the source is also defined in
1196 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1199 bool DefIsLiveOut = false;
1200 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1202 Instruction *User = cast<Instruction>(*UI);
1204 // Figure out which BB this ext is used in.
1205 BasicBlock *UserBB = User->getParent();
1206 if (UserBB == DefBB) continue;
1207 DefIsLiveOut = true;
1213 // Make sure non of the uses are PHI nodes.
1214 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1216 Instruction *User = cast<Instruction>(*UI);
1217 BasicBlock *UserBB = User->getParent();
1218 if (UserBB == DefBB) continue;
1219 // Be conservative. We don't want this xform to end up introducing
1220 // reloads just before load / store instructions.
1221 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1225 // InsertedTruncs - Only insert one trunc in each block once.
1226 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1228 bool MadeChange = false;
1229 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1231 Use &TheUse = UI.getUse();
1232 Instruction *User = cast<Instruction>(*UI);
1234 // Figure out which BB this ext is used in.
1235 BasicBlock *UserBB = User->getParent();
1236 if (UserBB == DefBB) continue;
1238 // Both src and def are live in this block. Rewrite the use.
1239 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1241 if (!InsertedTrunc) {
1242 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1243 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1246 // Replace a use of the {s|z}ext source with a use of the result.
1247 TheUse = InsertedTrunc;
1255 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1256 /// turned into an explicit branch.
1257 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1258 // FIXME: This should use the same heuristics as IfConversion to determine
1259 // whether a select is better represented as a branch. This requires that
1260 // branch probability metadata is preserved for the select, which is not the
1263 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1265 // If the branch is predicted right, an out of order CPU can avoid blocking on
1266 // the compare. Emit cmovs on compares with a memory operand as branches to
1267 // avoid stalls on the load from memory. If the compare has more than one use
1268 // there's probably another cmov or setcc around so it's not worth emitting a
1273 Value *CmpOp0 = Cmp->getOperand(0);
1274 Value *CmpOp1 = Cmp->getOperand(1);
1276 // We check that the memory operand has one use to avoid uses of the loaded
1277 // value directly after the compare, making branches unprofitable.
1278 return Cmp->hasOneUse() &&
1279 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1280 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1284 /// If we have a SelectInst that will likely profit from branch prediction,
1285 /// turn it into a branch.
1286 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1287 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1289 // Can we convert the 'select' to CF ?
1290 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1293 TargetLowering::SelectSupportKind SelectKind;
1295 SelectKind = TargetLowering::VectorMaskSelect;
1296 else if (SI->getType()->isVectorTy())
1297 SelectKind = TargetLowering::ScalarCondVectorVal;
1299 SelectKind = TargetLowering::ScalarValSelect;
1301 // Do we have efficient codegen support for this kind of 'selects' ?
1302 if (TLI->isSelectSupported(SelectKind)) {
1303 // We have efficient codegen support for the select instruction.
1304 // Check if it is profitable to keep this 'select'.
1305 if (!TLI->isPredictableSelectExpensive() ||
1306 !isFormingBranchFromSelectProfitable(SI))
1312 // First, we split the block containing the select into 2 blocks.
1313 BasicBlock *StartBlock = SI->getParent();
1314 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1315 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1317 // Create a new block serving as the landing pad for the branch.
1318 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1319 NextBlock->getParent(), NextBlock);
1321 // Move the unconditional branch from the block with the select in it into our
1322 // landing pad block.
1323 StartBlock->getTerminator()->eraseFromParent();
1324 BranchInst::Create(NextBlock, SmallBlock);
1326 // Insert the real conditional branch based on the original condition.
1327 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1329 // The select itself is replaced with a PHI Node.
1330 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1332 PN->addIncoming(SI->getTrueValue(), StartBlock);
1333 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1334 SI->replaceAllUsesWith(PN);
1335 SI->eraseFromParent();
1337 // Instruct OptimizeBlock to skip to the next block.
1338 CurInstIterator = StartBlock->end();
1339 ++NumSelectsExpanded;
1343 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1344 if (PHINode *P = dyn_cast<PHINode>(I)) {
1345 // It is possible for very late stage optimizations (such as SimplifyCFG)
1346 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1347 // trivial PHI, go ahead and zap it here.
1348 if (Value *V = SimplifyInstruction(P)) {
1349 P->replaceAllUsesWith(V);
1350 P->eraseFromParent();
1357 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1358 // If the source of the cast is a constant, then this should have
1359 // already been constant folded. The only reason NOT to constant fold
1360 // it is if something (e.g. LSR) was careful to place the constant
1361 // evaluation in a block other than then one that uses it (e.g. to hoist
1362 // the address of globals out of a loop). If this is the case, we don't
1363 // want to forward-subst the cast.
1364 if (isa<Constant>(CI->getOperand(0)))
1367 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1370 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1371 bool MadeChange = MoveExtToFormExtLoad(I);
1372 return MadeChange | OptimizeExtUses(I);
1377 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1378 return OptimizeCmpExpression(CI);
1380 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1382 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1386 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1388 return OptimizeMemoryInst(I, SI->getOperand(1),
1389 SI->getOperand(0)->getType());
1393 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1394 if (GEPI->hasAllZeroIndices()) {
1395 /// The GEP operand must be a pointer, so must its result -> BitCast
1396 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1397 GEPI->getName(), GEPI);
1398 GEPI->replaceAllUsesWith(NC);
1399 GEPI->eraseFromParent();
1407 if (CallInst *CI = dyn_cast<CallInst>(I))
1408 return OptimizeCallInst(CI);
1410 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1411 return OptimizeSelectInst(SI);
1416 // In this pass we look for GEP and cast instructions that are used
1417 // across basic blocks and rewrite them to improve basic-block-at-a-time
1419 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1421 bool MadeChange = false;
1423 CurInstIterator = BB.begin();
1424 while (CurInstIterator != BB.end())
1425 MadeChange |= OptimizeInst(CurInstIterator++);
1427 MadeChange |= DupRetToEnableTailCallOpts(&BB);
1432 // llvm.dbg.value is far away from the value then iSel may not be able
1433 // handle it properly. iSel will drop llvm.dbg.value if it can not
1434 // find a node corresponding to the value.
1435 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1436 bool MadeChange = false;
1437 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1438 Instruction *PrevNonDbgInst = NULL;
1439 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1440 Instruction *Insn = BI; ++BI;
1441 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1443 PrevNonDbgInst = Insn;
1447 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1448 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1449 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1450 DVI->removeFromParent();
1451 if (isa<PHINode>(VI))
1452 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1454 DVI->insertAfter(VI);