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/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/ProfileInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Transforms/Utils/BuildLibCalls.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Assembly/Writer.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/GetElementPtrTypeIterator.h"
42 #include "llvm/Support/PatternMatch.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/ValueHandle.h"
47 using namespace llvm::PatternMatch;
49 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
50 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
52 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
58 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61 static cl::opt<bool> DisableBranchOpts(
62 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
63 cl::desc("Disable branch optimizations in CodeGenPrepare"));
66 class CodeGenPrepare : public FunctionPass {
67 /// TLI - Keep a pointer of a TargetLowering to consult for determining
68 /// transformation profitability.
69 const TargetLowering *TLI;
73 /// CurInstIterator - As we scan instructions optimizing them, this is the
74 /// next instruction to optimize. Xforms that can invalidate this should
76 BasicBlock::iterator CurInstIterator;
78 // Keeps track of non-local addresses that have been sunk into a block. This
79 // allows us to avoid inserting duplicate code for blocks with multiple
80 // load/stores of the same address.
81 DenseMap<Value*, Value*> SunkAddrs;
84 static char ID; // Pass identification, replacement for typeid
85 explicit CodeGenPrepare(const TargetLowering *tli = 0)
86 : FunctionPass(ID), TLI(tli) {
87 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
89 bool runOnFunction(Function &F);
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addPreserved<DominatorTree>();
93 AU.addPreserved<ProfileInfo>();
97 bool EliminateMostlyEmptyBlocks(Function &F);
98 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
99 void EliminateMostlyEmptyBlock(BasicBlock *BB);
100 bool OptimizeBlock(BasicBlock &BB);
101 bool OptimizeInst(Instruction *I);
102 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy);
103 bool OptimizeInlineAsmInst(CallInst *CS);
104 bool OptimizeCallInst(CallInst *CI);
105 bool MoveExtToFormExtLoad(Instruction *I);
106 bool OptimizeExtUses(Instruction *I);
110 char CodeGenPrepare::ID = 0;
111 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
112 "Optimize for code generation", false, false)
114 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
115 return new CodeGenPrepare(TLI);
118 bool CodeGenPrepare::runOnFunction(Function &F) {
119 bool EverMadeChange = false;
121 DT = getAnalysisIfAvailable<DominatorTree>();
122 PFI = getAnalysisIfAvailable<ProfileInfo>();
123 // First pass, eliminate blocks that contain only PHI nodes and an
124 // unconditional branch.
125 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
127 bool MadeChange = true;
130 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
131 MadeChange |= OptimizeBlock(*BB);
132 EverMadeChange |= MadeChange;
137 if (!DisableBranchOpts) {
139 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
140 MadeChange |= ConstantFoldTerminator(BB);
142 if (MadeChange && DT)
143 DT->DT->recalculate(F);
144 EverMadeChange |= MadeChange;
147 return EverMadeChange;
150 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
151 /// debug info directives, and an unconditional branch. Passes before isel
152 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
153 /// isel. Start by eliminating these blocks so we can split them the way we
155 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
156 bool MadeChange = false;
157 // Note that this intentionally skips the entry block.
158 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
159 BasicBlock *BB = I++;
161 // If this block doesn't end with an uncond branch, ignore it.
162 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
163 if (!BI || !BI->isUnconditional())
166 // If the instruction before the branch (skipping debug info) isn't a phi
167 // node, then other stuff is happening here.
168 BasicBlock::iterator BBI = BI;
169 if (BBI != BB->begin()) {
171 while (isa<DbgInfoIntrinsic>(BBI)) {
172 if (BBI == BB->begin())
176 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
180 // Do not break infinite loops.
181 BasicBlock *DestBB = BI->getSuccessor(0);
185 if (!CanMergeBlocks(BB, DestBB))
188 EliminateMostlyEmptyBlock(BB);
194 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
195 /// single uncond branch between them, and BB contains no other non-phi
197 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
198 const BasicBlock *DestBB) const {
199 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
200 // the successor. If there are more complex condition (e.g. preheaders),
201 // don't mess around with them.
202 BasicBlock::const_iterator BBI = BB->begin();
203 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
204 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
206 const Instruction *User = cast<Instruction>(*UI);
207 if (User->getParent() != DestBB || !isa<PHINode>(User))
209 // If User is inside DestBB block and it is a PHINode then check
210 // incoming value. If incoming value is not from BB then this is
211 // a complex condition (e.g. preheaders) we want to avoid here.
212 if (User->getParent() == DestBB) {
213 if (const PHINode *UPN = dyn_cast<PHINode>(User))
214 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
215 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
216 if (Insn && Insn->getParent() == BB &&
217 Insn->getParent() != UPN->getIncomingBlock(I))
224 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
225 // and DestBB may have conflicting incoming values for the block. If so, we
226 // can't merge the block.
227 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
228 if (!DestBBPN) return true; // no conflict.
230 // Collect the preds of BB.
231 SmallPtrSet<const BasicBlock*, 16> BBPreds;
232 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
233 // It is faster to get preds from a PHI than with pred_iterator.
234 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
235 BBPreds.insert(BBPN->getIncomingBlock(i));
237 BBPreds.insert(pred_begin(BB), pred_end(BB));
240 // Walk the preds of DestBB.
241 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
242 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
243 if (BBPreds.count(Pred)) { // Common predecessor?
244 BBI = DestBB->begin();
245 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
246 const Value *V1 = PN->getIncomingValueForBlock(Pred);
247 const Value *V2 = PN->getIncomingValueForBlock(BB);
249 // If V2 is a phi node in BB, look up what the mapped value will be.
250 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
251 if (V2PN->getParent() == BB)
252 V2 = V2PN->getIncomingValueForBlock(Pred);
254 // If there is a conflict, bail out.
255 if (V1 != V2) return false;
264 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
265 /// an unconditional branch in it.
266 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
267 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
268 BasicBlock *DestBB = BI->getSuccessor(0);
270 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
272 // If the destination block has a single pred, then this is a trivial edge,
274 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
275 if (SinglePred != DestBB) {
276 // Remember if SinglePred was the entry block of the function. If so, we
277 // will need to move BB back to the entry position.
278 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
279 MergeBasicBlockIntoOnlyPred(DestBB, this);
281 if (isEntry && BB != &BB->getParent()->getEntryBlock())
282 BB->moveBefore(&BB->getParent()->getEntryBlock());
284 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
289 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
290 // to handle the new incoming edges it is about to have.
292 for (BasicBlock::iterator BBI = DestBB->begin();
293 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
294 // Remove the incoming value for BB, and remember it.
295 Value *InVal = PN->removeIncomingValue(BB, false);
297 // Two options: either the InVal is a phi node defined in BB or it is some
298 // value that dominates BB.
299 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
300 if (InValPhi && InValPhi->getParent() == BB) {
301 // Add all of the input values of the input PHI as inputs of this phi.
302 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
303 PN->addIncoming(InValPhi->getIncomingValue(i),
304 InValPhi->getIncomingBlock(i));
306 // Otherwise, add one instance of the dominating value for each edge that
307 // we will be adding.
308 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
309 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
310 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
312 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
313 PN->addIncoming(InVal, *PI);
318 // The PHIs are now updated, change everything that refers to BB to use
319 // DestBB and remove BB.
320 BB->replaceAllUsesWith(DestBB);
322 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
323 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
324 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
325 DT->changeImmediateDominator(DestBB, NewIDom);
329 PFI->replaceAllUses(BB, DestBB);
330 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
332 BB->eraseFromParent();
335 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
338 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
339 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
340 /// sink it into user blocks to reduce the number of virtual
341 /// registers that must be created and coalesced.
343 /// Return true if any changes are made.
345 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
346 // If this is a noop copy,
347 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
348 EVT DstVT = TLI.getValueType(CI->getType());
350 // This is an fp<->int conversion?
351 if (SrcVT.isInteger() != DstVT.isInteger())
354 // If this is an extension, it will be a zero or sign extension, which
356 if (SrcVT.bitsLT(DstVT)) return false;
358 // If these values will be promoted, find out what they will be promoted
359 // to. This helps us consider truncates on PPC as noop copies when they
361 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
362 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
363 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
364 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
366 // If, after promotion, these are the same types, this is a noop copy.
370 BasicBlock *DefBB = CI->getParent();
372 /// InsertedCasts - Only insert a cast in each block once.
373 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
375 bool MadeChange = false;
376 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
378 Use &TheUse = UI.getUse();
379 Instruction *User = cast<Instruction>(*UI);
381 // Figure out which BB this cast is used in. For PHI's this is the
382 // appropriate predecessor block.
383 BasicBlock *UserBB = User->getParent();
384 if (PHINode *PN = dyn_cast<PHINode>(User)) {
385 UserBB = PN->getIncomingBlock(UI);
388 // Preincrement use iterator so we don't invalidate it.
391 // If this user is in the same block as the cast, don't change the cast.
392 if (UserBB == DefBB) continue;
394 // If we have already inserted a cast into this block, use it.
395 CastInst *&InsertedCast = InsertedCasts[UserBB];
398 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
401 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
406 // Replace a use of the cast with a use of the new cast.
407 TheUse = InsertedCast;
411 // If we removed all uses, nuke the cast.
412 if (CI->use_empty()) {
413 CI->eraseFromParent();
420 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
421 /// the number of virtual registers that must be created and coalesced. This is
422 /// a clear win except on targets with multiple condition code registers
423 /// (PowerPC), where it might lose; some adjustment may be wanted there.
425 /// Return true if any changes are made.
426 static bool OptimizeCmpExpression(CmpInst *CI) {
427 BasicBlock *DefBB = CI->getParent();
429 /// InsertedCmp - Only insert a cmp in each block once.
430 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
432 bool MadeChange = false;
433 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
435 Use &TheUse = UI.getUse();
436 Instruction *User = cast<Instruction>(*UI);
438 // Preincrement use iterator so we don't invalidate it.
441 // Don't bother for PHI nodes.
442 if (isa<PHINode>(User))
445 // Figure out which BB this cmp is used in.
446 BasicBlock *UserBB = User->getParent();
448 // If this user is in the same block as the cmp, don't change the cmp.
449 if (UserBB == DefBB) continue;
451 // If we have already inserted a cmp into this block, use it.
452 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
455 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
458 CmpInst::Create(CI->getOpcode(),
459 CI->getPredicate(), CI->getOperand(0),
460 CI->getOperand(1), "", InsertPt);
464 // Replace a use of the cmp with a use of the new cmp.
465 TheUse = InsertedCmp;
469 // If we removed all uses, nuke the cmp.
471 CI->eraseFromParent();
477 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
479 void replaceCall(Value *With) {
480 CI->replaceAllUsesWith(With);
481 CI->eraseFromParent();
483 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
484 if (ConstantInt *SizeCI =
485 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
486 return SizeCI->isAllOnesValue();
490 } // end anonymous namespace
492 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
493 BasicBlock *BB = CI->getParent();
495 // Lower inline assembly if we can.
496 // If we found an inline asm expession, and if the target knows how to
497 // lower it to normal LLVM code, do so now.
498 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
499 if (TLI->ExpandInlineAsm(CI)) {
500 // Avoid invalidating the iterator.
501 CurInstIterator = BB->begin();
502 // Avoid processing instructions out of order, which could cause
503 // reuse before a value is defined.
507 // Sink address computing for memory operands into the block.
508 if (OptimizeInlineAsmInst(CI))
512 // Lower all uses of llvm.objectsize.*
513 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
514 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
515 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
516 const Type *ReturnTy = CI->getType();
517 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
519 // Substituting this can cause recursive simplifications, which can
520 // invalidate our iterator. Use a WeakVH to hold onto it in case this
522 WeakVH IterHandle(CurInstIterator);
524 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
526 // If the iterator instruction was recursively deleted, start over at the
527 // start of the block.
528 if (IterHandle != CurInstIterator) {
529 CurInstIterator = BB->begin();
535 // From here on out we're working with named functions.
536 if (CI->getCalledFunction() == 0) return false;
538 // We'll need TargetData from here on out.
539 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
540 if (!TD) return false;
542 // Lower all default uses of _chk calls. This is very similar
543 // to what InstCombineCalls does, but here we are only lowering calls
544 // that have the default "don't know" as the objectsize. Anything else
545 // should be left alone.
546 CodeGenPrepareFortifiedLibCalls Simplifier;
547 return Simplifier.fold(CI, TD);
550 //===----------------------------------------------------------------------===//
551 // Memory Optimization
552 //===----------------------------------------------------------------------===//
554 /// IsNonLocalValue - Return true if the specified values are defined in a
555 /// different basic block than BB.
556 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
557 if (Instruction *I = dyn_cast<Instruction>(V))
558 return I->getParent() != BB;
562 /// OptimizeMemoryInst - Load and Store Instructions often have
563 /// addressing modes that can do significant amounts of computation. As such,
564 /// instruction selection will try to get the load or store to do as much
565 /// computation as possible for the program. The problem is that isel can only
566 /// see within a single block. As such, we sink as much legal addressing mode
567 /// stuff into the block as possible.
569 /// This method is used to optimize both load/store and inline asms with memory
571 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
572 const Type *AccessTy) {
575 // Try to collapse single-value PHI nodes. This is necessary to undo
576 // unprofitable PRE transformations.
577 SmallVector<Value*, 8> worklist;
578 SmallPtrSet<Value*, 16> Visited;
579 worklist.push_back(Addr);
581 // Use a worklist to iteratively look through PHI nodes, and ensure that
582 // the addressing mode obtained from the non-PHI roots of the graph
584 Value *Consensus = 0;
585 unsigned NumUsesConsensus = 0;
586 bool IsNumUsesConsensusValid = false;
587 SmallVector<Instruction*, 16> AddrModeInsts;
588 ExtAddrMode AddrMode;
589 while (!worklist.empty()) {
590 Value *V = worklist.back();
593 // Break use-def graph loops.
594 if (Visited.count(V)) {
601 // For a PHI node, push all of its incoming values.
602 if (PHINode *P = dyn_cast<PHINode>(V)) {
603 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
604 worklist.push_back(P->getIncomingValue(i));
608 // For non-PHIs, determine the addressing mode being computed.
609 SmallVector<Instruction*, 16> NewAddrModeInsts;
610 ExtAddrMode NewAddrMode =
611 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
612 NewAddrModeInsts, *TLI);
614 // This check is broken into two cases with very similar code to avoid using
615 // getNumUses() as much as possible. Some values have a lot of uses, so
616 // calling getNumUses() unconditionally caused a significant compile-time
620 AddrMode = NewAddrMode;
621 AddrModeInsts = NewAddrModeInsts;
623 } else if (NewAddrMode == AddrMode) {
624 if (!IsNumUsesConsensusValid) {
625 NumUsesConsensus = Consensus->getNumUses();
626 IsNumUsesConsensusValid = true;
629 // Ensure that the obtained addressing mode is equivalent to that obtained
630 // for all other roots of the PHI traversal. Also, when choosing one
631 // such root as representative, select the one with the most uses in order
632 // to keep the cost modeling heuristics in AddressingModeMatcher
634 unsigned NumUses = V->getNumUses();
635 if (NumUses > NumUsesConsensus) {
637 NumUsesConsensus = NumUses;
638 AddrModeInsts = NewAddrModeInsts;
647 // If the addressing mode couldn't be determined, or if multiple different
648 // ones were determined, bail out now.
649 if (!Consensus) return false;
651 // Check to see if any of the instructions supersumed by this addr mode are
652 // non-local to I's BB.
653 bool AnyNonLocal = false;
654 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
655 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
661 // If all the instructions matched are already in this BB, don't do anything.
663 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
667 // Insert this computation right after this user. Since our caller is
668 // scanning from the top of the BB to the bottom, reuse of the expr are
669 // guaranteed to happen later.
670 BasicBlock::iterator InsertPt = MemoryInst;
672 // Now that we determined the addressing expression we want to use and know
673 // that we have to sink it into this block. Check to see if we have already
674 // done this for some other load/store instr in this block. If so, reuse the
676 Value *&SunkAddr = SunkAddrs[Addr];
678 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
680 if (SunkAddr->getType() != Addr->getType())
681 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
683 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
685 const Type *IntPtrTy =
686 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
690 // Start with the base register. Do this first so that subsequent address
691 // matching finds it last, which will prevent it from trying to match it
692 // as the scaled value in case it happens to be a mul. That would be
693 // problematic if we've sunk a different mul for the scale, because then
694 // we'd end up sinking both muls.
695 if (AddrMode.BaseReg) {
696 Value *V = AddrMode.BaseReg;
697 if (V->getType()->isPointerTy())
698 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
699 if (V->getType() != IntPtrTy)
700 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
701 "sunkaddr", InsertPt);
705 // Add the scale value.
706 if (AddrMode.Scale) {
707 Value *V = AddrMode.ScaledReg;
708 if (V->getType() == IntPtrTy) {
710 } else if (V->getType()->isPointerTy()) {
711 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
712 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
713 cast<IntegerType>(V->getType())->getBitWidth()) {
714 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
716 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
718 if (AddrMode.Scale != 1)
719 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
721 "sunkaddr", InsertPt);
723 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
728 // Add in the BaseGV if present.
729 if (AddrMode.BaseGV) {
730 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
733 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
738 // Add in the Base Offset if present.
739 if (AddrMode.BaseOffs) {
740 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
742 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
748 SunkAddr = Constant::getNullValue(Addr->getType());
750 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
753 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
755 if (Repl->use_empty()) {
756 RecursivelyDeleteTriviallyDeadInstructions(Repl);
757 // This address is now available for reassignment, so erase the table entry;
758 // we don't want to match some completely different instruction.
765 /// OptimizeInlineAsmInst - If there are any memory operands, use
766 /// OptimizeMemoryInst to sink their address computing into the block when
767 /// possible / profitable.
768 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
769 bool MadeChange = false;
771 TargetLowering::AsmOperandInfoVector
772 TargetConstraints = TLI->ParseConstraints(CS);
774 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
775 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
777 // Compute the constraint code and ConstraintType to use.
778 TLI->ComputeConstraintToUse(OpInfo, SDValue());
780 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
782 Value *OpVal = CS->getArgOperand(ArgNo++);
783 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
784 } else if (OpInfo.Type == InlineAsm::isInput)
791 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
792 /// basic block as the load, unless conditions are unfavorable. This allows
793 /// SelectionDAG to fold the extend into the load.
795 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
796 // Look for a load being extended.
797 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
798 if (!LI) return false;
800 // If they're already in the same block, there's nothing to do.
801 if (LI->getParent() == I->getParent())
804 // If the load has other users and the truncate is not free, this probably
806 if (!LI->hasOneUse() &&
807 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
808 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
809 !TLI->isTruncateFree(I->getType(), LI->getType()))
812 // Check whether the target supports casts folded into loads.
814 if (isa<ZExtInst>(I))
815 LType = ISD::ZEXTLOAD;
817 assert(isa<SExtInst>(I) && "Unexpected ext type!");
818 LType = ISD::SEXTLOAD;
820 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
823 // Move the extend into the same block as the load, so that SelectionDAG
825 I->removeFromParent();
831 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
832 BasicBlock *DefBB = I->getParent();
834 // If the result of a {s|z}ext and its source are both live out, rewrite all
835 // other uses of the source with result of extension.
836 Value *Src = I->getOperand(0);
837 if (Src->hasOneUse())
840 // Only do this xform if truncating is free.
841 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
844 // Only safe to perform the optimization if the source is also defined in
846 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
849 bool DefIsLiveOut = false;
850 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
852 Instruction *User = cast<Instruction>(*UI);
854 // Figure out which BB this ext is used in.
855 BasicBlock *UserBB = User->getParent();
856 if (UserBB == DefBB) continue;
863 // Make sure non of the uses are PHI nodes.
864 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
866 Instruction *User = cast<Instruction>(*UI);
867 BasicBlock *UserBB = User->getParent();
868 if (UserBB == DefBB) continue;
869 // Be conservative. We don't want this xform to end up introducing
870 // reloads just before load / store instructions.
871 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
875 // InsertedTruncs - Only insert one trunc in each block once.
876 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
878 bool MadeChange = false;
879 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
881 Use &TheUse = UI.getUse();
882 Instruction *User = cast<Instruction>(*UI);
884 // Figure out which BB this ext is used in.
885 BasicBlock *UserBB = User->getParent();
886 if (UserBB == DefBB) continue;
888 // Both src and def are live in this block. Rewrite the use.
889 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
891 if (!InsertedTrunc) {
892 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
894 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
897 // Replace a use of the {s|z}ext source with a use of the result.
898 TheUse = InsertedTrunc;
906 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
907 if (PHINode *P = dyn_cast<PHINode>(I)) {
908 // It is possible for very late stage optimizations (such as SimplifyCFG)
909 // to introduce PHI nodes too late to be cleaned up. If we detect such a
910 // trivial PHI, go ahead and zap it here.
911 if (Value *V = SimplifyInstruction(P)) {
912 P->replaceAllUsesWith(V);
913 P->eraseFromParent();
920 if (CastInst *CI = dyn_cast<CastInst>(I)) {
921 // If the source of the cast is a constant, then this should have
922 // already been constant folded. The only reason NOT to constant fold
923 // it is if something (e.g. LSR) was careful to place the constant
924 // evaluation in a block other than then one that uses it (e.g. to hoist
925 // the address of globals out of a loop). If this is the case, we don't
926 // want to forward-subst the cast.
927 if (isa<Constant>(CI->getOperand(0)))
930 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
933 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
934 bool MadeChange = MoveExtToFormExtLoad(I);
935 return MadeChange | OptimizeExtUses(I);
940 if (CmpInst *CI = dyn_cast<CmpInst>(I))
941 return OptimizeCmpExpression(CI);
943 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
945 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
949 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
951 return OptimizeMemoryInst(I, SI->getOperand(1),
952 SI->getOperand(0)->getType());
956 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
957 if (GEPI->hasAllZeroIndices()) {
958 /// The GEP operand must be a pointer, so must its result -> BitCast
959 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
960 GEPI->getName(), GEPI);
961 GEPI->replaceAllUsesWith(NC);
962 GEPI->eraseFromParent();
970 if (CallInst *CI = dyn_cast<CallInst>(I))
971 return OptimizeCallInst(CI);
976 // In this pass we look for GEP and cast instructions that are used
977 // across basic blocks and rewrite them to improve basic-block-at-a-time
979 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
981 bool MadeChange = false;
983 CurInstIterator = BB.begin();
984 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
985 MadeChange |= OptimizeInst(CurInstIterator++);