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");
62 class CodeGenPrepare : public FunctionPass {
63 /// TLI - Keep a pointer of a TargetLowering to consult for determining
64 /// transformation profitability.
65 const TargetLowering *TLI;
69 /// CurInstIterator - As we scan instructions optimizing them, this is the
70 /// next instruction to optimize. Xforms that can invalidate this should
72 BasicBlock::iterator CurInstIterator;
74 /// BackEdges - Keep a set of all the loop back edges.
76 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
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>();
96 virtual void releaseMemory() {
101 bool EliminateMostlyEmptyBlocks(Function &F);
102 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
103 void EliminateMostlyEmptyBlock(BasicBlock *BB);
104 bool OptimizeBlock(BasicBlock &BB);
105 bool OptimizeInst(Instruction *I);
106 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy);
107 bool OptimizeInlineAsmInst(CallInst *CS);
108 bool OptimizeCallInst(CallInst *CI);
109 bool MoveExtToFormExtLoad(Instruction *I);
110 bool OptimizeExtUses(Instruction *I);
111 void findLoopBackEdges(const Function &F);
115 char CodeGenPrepare::ID = 0;
116 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
117 "Optimize for code generation", false, false)
119 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
120 return new CodeGenPrepare(TLI);
123 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
125 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
126 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
127 FindFunctionBackedges(F, Edges);
129 BackEdges.insert(Edges.begin(), Edges.end());
133 bool CodeGenPrepare::runOnFunction(Function &F) {
134 bool EverMadeChange = false;
136 DT = getAnalysisIfAvailable<DominatorTree>();
137 PFI = getAnalysisIfAvailable<ProfileInfo>();
138 // First pass, eliminate blocks that contain only PHI nodes and an
139 // unconditional branch.
140 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
142 bool MadeChange = true;
145 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
146 MadeChange |= OptimizeBlock(*BB);
147 EverMadeChange |= MadeChange;
152 return EverMadeChange;
155 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
156 /// debug info directives, and an unconditional branch. Passes before isel
157 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
158 /// isel. Start by eliminating these blocks so we can split them the way we
160 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
161 bool MadeChange = false;
162 // Note that this intentionally skips the entry block.
163 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
164 BasicBlock *BB = I++;
166 // If this block doesn't end with an uncond branch, ignore it.
167 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
168 if (!BI || !BI->isUnconditional())
171 // If the instruction before the branch (skipping debug info) isn't a phi
172 // node, then other stuff is happening here.
173 BasicBlock::iterator BBI = BI;
174 if (BBI != BB->begin()) {
176 while (isa<DbgInfoIntrinsic>(BBI)) {
177 if (BBI == BB->begin())
181 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
185 // Do not break infinite loops.
186 BasicBlock *DestBB = BI->getSuccessor(0);
190 if (!CanMergeBlocks(BB, DestBB))
193 EliminateMostlyEmptyBlock(BB);
199 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
200 /// single uncond branch between them, and BB contains no other non-phi
202 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
203 const BasicBlock *DestBB) const {
204 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
205 // the successor. If there are more complex condition (e.g. preheaders),
206 // don't mess around with them.
207 BasicBlock::const_iterator BBI = BB->begin();
208 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
209 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
211 const Instruction *User = cast<Instruction>(*UI);
212 if (User->getParent() != DestBB || !isa<PHINode>(User))
214 // If User is inside DestBB block and it is a PHINode then check
215 // incoming value. If incoming value is not from BB then this is
216 // a complex condition (e.g. preheaders) we want to avoid here.
217 if (User->getParent() == DestBB) {
218 if (const PHINode *UPN = dyn_cast<PHINode>(User))
219 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
220 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
221 if (Insn && Insn->getParent() == BB &&
222 Insn->getParent() != UPN->getIncomingBlock(I))
229 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
230 // and DestBB may have conflicting incoming values for the block. If so, we
231 // can't merge the block.
232 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
233 if (!DestBBPN) return true; // no conflict.
235 // Collect the preds of BB.
236 SmallPtrSet<const BasicBlock*, 16> BBPreds;
237 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
238 // It is faster to get preds from a PHI than with pred_iterator.
239 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
240 BBPreds.insert(BBPN->getIncomingBlock(i));
242 BBPreds.insert(pred_begin(BB), pred_end(BB));
245 // Walk the preds of DestBB.
246 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
247 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
248 if (BBPreds.count(Pred)) { // Common predecessor?
249 BBI = DestBB->begin();
250 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
251 const Value *V1 = PN->getIncomingValueForBlock(Pred);
252 const Value *V2 = PN->getIncomingValueForBlock(BB);
254 // If V2 is a phi node in BB, look up what the mapped value will be.
255 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
256 if (V2PN->getParent() == BB)
257 V2 = V2PN->getIncomingValueForBlock(Pred);
259 // If there is a conflict, bail out.
260 if (V1 != V2) return false;
269 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
270 /// an unconditional branch in it.
271 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
272 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
273 BasicBlock *DestBB = BI->getSuccessor(0);
275 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
277 // If the destination block has a single pred, then this is a trivial edge,
279 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
280 if (SinglePred != DestBB) {
281 // Remember if SinglePred was the entry block of the function. If so, we
282 // will need to move BB back to the entry position.
283 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
284 MergeBasicBlockIntoOnlyPred(DestBB, this);
286 if (isEntry && BB != &BB->getParent()->getEntryBlock())
287 BB->moveBefore(&BB->getParent()->getEntryBlock());
289 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
294 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
295 // to handle the new incoming edges it is about to have.
297 for (BasicBlock::iterator BBI = DestBB->begin();
298 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
299 // Remove the incoming value for BB, and remember it.
300 Value *InVal = PN->removeIncomingValue(BB, false);
302 // Two options: either the InVal is a phi node defined in BB or it is some
303 // value that dominates BB.
304 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
305 if (InValPhi && InValPhi->getParent() == BB) {
306 // Add all of the input values of the input PHI as inputs of this phi.
307 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
308 PN->addIncoming(InValPhi->getIncomingValue(i),
309 InValPhi->getIncomingBlock(i));
311 // Otherwise, add one instance of the dominating value for each edge that
312 // we will be adding.
313 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
314 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
315 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
317 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
318 PN->addIncoming(InVal, *PI);
323 // The PHIs are now updated, change everything that refers to BB to use
324 // DestBB and remove BB.
325 BB->replaceAllUsesWith(DestBB);
327 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
328 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
329 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
330 DT->changeImmediateDominator(DestBB, NewIDom);
334 PFI->replaceAllUses(BB, DestBB);
335 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
337 BB->eraseFromParent();
340 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
343 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
344 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
345 /// sink it into user blocks to reduce the number of virtual
346 /// registers that must be created and coalesced.
348 /// Return true if any changes are made.
350 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
351 // If this is a noop copy,
352 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
353 EVT DstVT = TLI.getValueType(CI->getType());
355 // This is an fp<->int conversion?
356 if (SrcVT.isInteger() != DstVT.isInteger())
359 // If this is an extension, it will be a zero or sign extension, which
361 if (SrcVT.bitsLT(DstVT)) return false;
363 // If these values will be promoted, find out what they will be promoted
364 // to. This helps us consider truncates on PPC as noop copies when they
366 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
367 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
368 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
369 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
371 // If, after promotion, these are the same types, this is a noop copy.
375 BasicBlock *DefBB = CI->getParent();
377 /// InsertedCasts - Only insert a cast in each block once.
378 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
380 bool MadeChange = false;
381 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
383 Use &TheUse = UI.getUse();
384 Instruction *User = cast<Instruction>(*UI);
386 // Figure out which BB this cast is used in. For PHI's this is the
387 // appropriate predecessor block.
388 BasicBlock *UserBB = User->getParent();
389 if (PHINode *PN = dyn_cast<PHINode>(User)) {
390 UserBB = PN->getIncomingBlock(UI);
393 // Preincrement use iterator so we don't invalidate it.
396 // If this user is in the same block as the cast, don't change the cast.
397 if (UserBB == DefBB) continue;
399 // If we have already inserted a cast into this block, use it.
400 CastInst *&InsertedCast = InsertedCasts[UserBB];
403 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
406 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
411 // Replace a use of the cast with a use of the new cast.
412 TheUse = InsertedCast;
416 // If we removed all uses, nuke the cast.
417 if (CI->use_empty()) {
418 CI->eraseFromParent();
425 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
426 /// the number of virtual registers that must be created and coalesced. This is
427 /// a clear win except on targets with multiple condition code registers
428 /// (PowerPC), where it might lose; some adjustment may be wanted there.
430 /// Return true if any changes are made.
431 static bool OptimizeCmpExpression(CmpInst *CI) {
432 BasicBlock *DefBB = CI->getParent();
434 /// InsertedCmp - Only insert a cmp in each block once.
435 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
437 bool MadeChange = false;
438 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
440 Use &TheUse = UI.getUse();
441 Instruction *User = cast<Instruction>(*UI);
443 // Preincrement use iterator so we don't invalidate it.
446 // Don't bother for PHI nodes.
447 if (isa<PHINode>(User))
450 // Figure out which BB this cmp is used in.
451 BasicBlock *UserBB = User->getParent();
453 // If this user is in the same block as the cmp, don't change the cmp.
454 if (UserBB == DefBB) continue;
456 // If we have already inserted a cmp into this block, use it.
457 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
460 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
463 CmpInst::Create(CI->getOpcode(),
464 CI->getPredicate(), CI->getOperand(0),
465 CI->getOperand(1), "", InsertPt);
469 // Replace a use of the cmp with a use of the new cmp.
470 TheUse = InsertedCmp;
474 // If we removed all uses, nuke the cmp.
476 CI->eraseFromParent();
482 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
484 void replaceCall(Value *With) {
485 CI->replaceAllUsesWith(With);
486 CI->eraseFromParent();
488 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
489 if (ConstantInt *SizeCI =
490 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
491 return SizeCI->isAllOnesValue();
495 } // end anonymous namespace
497 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
498 BasicBlock *BB = CI->getParent();
500 // Lower inline assembly if we can.
501 // If we found an inline asm expession, and if the target knows how to
502 // lower it to normal LLVM code, do so now.
503 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
504 if (TLI->ExpandInlineAsm(CI)) {
505 // Avoid invalidating the iterator.
506 CurInstIterator = BB->begin();
507 // Avoid processing instructions out of order, which could cause
508 // reuse before a value is defined.
512 // Sink address computing for memory operands into the block.
513 if (OptimizeInlineAsmInst(CI))
517 // Lower all uses of llvm.objectsize.*
518 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
519 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
520 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
521 const Type *ReturnTy = CI->getType();
522 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
524 // Substituting this can cause recursive simplifications, which can
525 // invalidate our iterator. Use a WeakVH to hold onto it in case this
527 WeakVH IterHandle(CurInstIterator);
529 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
531 // If the iterator instruction was recursively deleted, start over at the
532 // start of the block.
533 if (IterHandle != CurInstIterator) {
534 CurInstIterator = BB->begin();
540 // From here on out we're working with named functions.
541 if (CI->getCalledFunction() == 0) return false;
543 // We'll need TargetData from here on out.
544 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
545 if (!TD) return false;
547 // Lower all default uses of _chk calls. This is very similar
548 // to what InstCombineCalls does, but here we are only lowering calls
549 // that have the default "don't know" as the objectsize. Anything else
550 // should be left alone.
551 CodeGenPrepareFortifiedLibCalls Simplifier;
552 return Simplifier.fold(CI, TD);
555 //===----------------------------------------------------------------------===//
556 // Memory Optimization
557 //===----------------------------------------------------------------------===//
559 /// IsNonLocalValue - Return true if the specified values are defined in a
560 /// different basic block than BB.
561 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
562 if (Instruction *I = dyn_cast<Instruction>(V))
563 return I->getParent() != BB;
567 /// OptimizeMemoryInst - Load and Store Instructions often have
568 /// addressing modes that can do significant amounts of computation. As such,
569 /// instruction selection will try to get the load or store to do as much
570 /// computation as possible for the program. The problem is that isel can only
571 /// see within a single block. As such, we sink as much legal addressing mode
572 /// stuff into the block as possible.
574 /// This method is used to optimize both load/store and inline asms with memory
576 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
577 const Type *AccessTy) {
580 // Try to collapse single-value PHI nodes. This is necessary to undo
581 // unprofitable PRE transformations.
582 SmallVector<Value*, 8> worklist;
583 SmallPtrSet<Value*, 16> Visited;
584 worklist.push_back(Addr);
586 // Use a worklist to iteratively look through PHI nodes, and ensure that
587 // the addressing mode obtained from the non-PHI roots of the graph
589 Value *Consensus = 0;
590 unsigned NumUsesConsensus = 0;
591 SmallVector<Instruction*, 16> AddrModeInsts;
592 ExtAddrMode AddrMode;
593 while (!worklist.empty()) {
594 Value *V = worklist.back();
597 // Break use-def graph loops.
598 if (Visited.count(V)) {
605 // For a PHI node, push all of its incoming values.
606 if (PHINode *P = dyn_cast<PHINode>(V)) {
607 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
608 worklist.push_back(P->getIncomingValue(i));
612 // For non-PHIs, determine the addressing mode being computed.
613 SmallVector<Instruction*, 16> NewAddrModeInsts;
614 ExtAddrMode NewAddrMode =
615 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
616 NewAddrModeInsts, *TLI);
618 // Ensure that the obtained addressing mode is equivalent to that obtained
619 // for all other roots of the PHI traversal. Also, when choosing one
620 // such root as representative, select the one with the most uses in order
621 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
622 if (!Consensus || NewAddrMode == AddrMode) {
623 unsigned NumUses = V->getNumUses();
624 if (NumUses > NumUsesConsensus) {
626 NumUsesConsensus = NumUses;
627 AddrMode = NewAddrMode;
628 AddrModeInsts = NewAddrModeInsts;
637 // If the addressing mode couldn't be determined, or if multiple different
638 // ones were determined, bail out now.
639 if (!Consensus) return false;
641 // Check to see if any of the instructions supersumed by this addr mode are
642 // non-local to I's BB.
643 bool AnyNonLocal = false;
644 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
645 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
651 // If all the instructions matched are already in this BB, don't do anything.
653 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
657 // Insert this computation right after this user. Since our caller is
658 // scanning from the top of the BB to the bottom, reuse of the expr are
659 // guaranteed to happen later.
660 BasicBlock::iterator InsertPt = MemoryInst;
662 // Now that we determined the addressing expression we want to use and know
663 // that we have to sink it into this block. Check to see if we have already
664 // done this for some other load/store instr in this block. If so, reuse the
666 Value *&SunkAddr = SunkAddrs[Addr];
668 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
670 if (SunkAddr->getType() != Addr->getType())
671 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
673 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
675 const Type *IntPtrTy =
676 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
680 // Start with the base register. Do this first so that subsequent address
681 // matching finds it last, which will prevent it from trying to match it
682 // as the scaled value in case it happens to be a mul. That would be
683 // problematic if we've sunk a different mul for the scale, because then
684 // we'd end up sinking both muls.
685 if (AddrMode.BaseReg) {
686 Value *V = AddrMode.BaseReg;
687 if (V->getType()->isPointerTy())
688 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
689 if (V->getType() != IntPtrTy)
690 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
691 "sunkaddr", InsertPt);
695 // Add the scale value.
696 if (AddrMode.Scale) {
697 Value *V = AddrMode.ScaledReg;
698 if (V->getType() == IntPtrTy) {
700 } else if (V->getType()->isPointerTy()) {
701 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
702 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
703 cast<IntegerType>(V->getType())->getBitWidth()) {
704 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
706 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
708 if (AddrMode.Scale != 1)
709 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
711 "sunkaddr", InsertPt);
713 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
718 // Add in the BaseGV if present.
719 if (AddrMode.BaseGV) {
720 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
723 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
728 // Add in the Base Offset if present.
729 if (AddrMode.BaseOffs) {
730 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
732 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
738 SunkAddr = Constant::getNullValue(Addr->getType());
740 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
743 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
745 if (Repl->use_empty()) {
746 RecursivelyDeleteTriviallyDeadInstructions(Repl);
747 // This address is now available for reassignment, so erase the table entry;
748 // we don't want to match some completely different instruction.
755 /// OptimizeInlineAsmInst - If there are any memory operands, use
756 /// OptimizeMemoryInst to sink their address computing into the block when
757 /// possible / profitable.
758 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
759 bool MadeChange = false;
761 TargetLowering::AsmOperandInfoVector
762 TargetConstraints = TLI->ParseConstraints(CS);
764 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
765 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
767 // Compute the constraint code and ConstraintType to use.
768 TLI->ComputeConstraintToUse(OpInfo, SDValue());
770 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
772 Value *OpVal = CS->getArgOperand(ArgNo++);
773 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
774 } else if (OpInfo.Type == InlineAsm::isInput)
781 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
782 /// basic block as the load, unless conditions are unfavorable. This allows
783 /// SelectionDAG to fold the extend into the load.
785 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
786 // Look for a load being extended.
787 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
788 if (!LI) return false;
790 // If they're already in the same block, there's nothing to do.
791 if (LI->getParent() == I->getParent())
794 // If the load has other users and the truncate is not free, this probably
796 if (!LI->hasOneUse() &&
797 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
798 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
799 !TLI->isTruncateFree(I->getType(), LI->getType()))
802 // Check whether the target supports casts folded into loads.
804 if (isa<ZExtInst>(I))
805 LType = ISD::ZEXTLOAD;
807 assert(isa<SExtInst>(I) && "Unexpected ext type!");
808 LType = ISD::SEXTLOAD;
810 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
813 // Move the extend into the same block as the load, so that SelectionDAG
815 I->removeFromParent();
821 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
822 BasicBlock *DefBB = I->getParent();
824 // If the result of a {s|z}ext and its source are both live out, rewrite all
825 // other uses of the source with result of extension.
826 Value *Src = I->getOperand(0);
827 if (Src->hasOneUse())
830 // Only do this xform if truncating is free.
831 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
834 // Only safe to perform the optimization if the source is also defined in
836 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
839 bool DefIsLiveOut = false;
840 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
842 Instruction *User = cast<Instruction>(*UI);
844 // Figure out which BB this ext is used in.
845 BasicBlock *UserBB = User->getParent();
846 if (UserBB == DefBB) continue;
853 // Make sure non of the uses are PHI nodes.
854 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
856 Instruction *User = cast<Instruction>(*UI);
857 BasicBlock *UserBB = User->getParent();
858 if (UserBB == DefBB) continue;
859 // Be conservative. We don't want this xform to end up introducing
860 // reloads just before load / store instructions.
861 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
865 // InsertedTruncs - Only insert one trunc in each block once.
866 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
868 bool MadeChange = false;
869 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
871 Use &TheUse = UI.getUse();
872 Instruction *User = cast<Instruction>(*UI);
874 // Figure out which BB this ext is used in.
875 BasicBlock *UserBB = User->getParent();
876 if (UserBB == DefBB) continue;
878 // Both src and def are live in this block. Rewrite the use.
879 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
881 if (!InsertedTrunc) {
882 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
884 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
887 // Replace a use of the {s|z}ext source with a use of the result.
888 TheUse = InsertedTrunc;
896 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
897 if (PHINode *P = dyn_cast<PHINode>(I)) {
898 // It is possible for very late stage optimizations (such as SimplifyCFG)
899 // to introduce PHI nodes too late to be cleaned up. If we detect such a
900 // trivial PHI, go ahead and zap it here.
901 if (Value *V = SimplifyInstruction(P)) {
902 P->replaceAllUsesWith(V);
903 P->eraseFromParent();
910 if (CastInst *CI = dyn_cast<CastInst>(I)) {
911 // If the source of the cast is a constant, then this should have
912 // already been constant folded. The only reason NOT to constant fold
913 // it is if something (e.g. LSR) was careful to place the constant
914 // evaluation in a block other than then one that uses it (e.g. to hoist
915 // the address of globals out of a loop). If this is the case, we don't
916 // want to forward-subst the cast.
917 if (isa<Constant>(CI->getOperand(0)))
920 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
923 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
924 bool MadeChange = MoveExtToFormExtLoad(I);
925 return MadeChange | OptimizeExtUses(I);
930 if (CmpInst *CI = dyn_cast<CmpInst>(I))
931 return OptimizeCmpExpression(CI);
933 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
935 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
939 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
941 return OptimizeMemoryInst(I, SI->getOperand(1),
942 SI->getOperand(0)->getType());
946 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
947 if (GEPI->hasAllZeroIndices()) {
948 /// The GEP operand must be a pointer, so must its result -> BitCast
949 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
950 GEPI->getName(), GEPI);
951 GEPI->replaceAllUsesWith(NC);
952 GEPI->eraseFromParent();
960 if (CallInst *CI = dyn_cast<CallInst>(I))
961 return OptimizeCallInst(CI);
966 // In this pass we look for GEP and cast instructions that are used
967 // across basic blocks and rewrite them to improve basic-block-at-a-time
969 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
971 bool MadeChange = false;
973 CurInstIterator = BB.begin();
974 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
975 MadeChange |= OptimizeInst(CurInstIterator++);