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/InstructionSimplify.h"
26 #include "llvm/Analysis/ProfileInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Transforms/Utils/BuildLibCalls.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Assembly/Writer.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/GetElementPtrTypeIterator.h"
41 #include "llvm/Support/PatternMatch.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/IRBuilder.h"
45 using namespace llvm::PatternMatch;
47 STATISTIC(NumElim, "Number of blocks eliminated");
50 CriticalEdgeSplit("cgp-critical-edge-splitting",
51 cl::desc("Split critical edges during codegen prepare"),
52 cl::init(false), cl::Hidden);
55 class CodeGenPrepare : public FunctionPass {
56 /// TLI - Keep a pointer of a TargetLowering to consult for determining
57 /// transformation profitability.
58 const TargetLowering *TLI;
61 /// BackEdges - Keep a set of all the loop back edges.
63 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
65 static char ID; // Pass identification, replacement for typeid
66 explicit CodeGenPrepare(const TargetLowering *tli = 0)
67 : FunctionPass(ID), TLI(tli) {
68 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
70 bool runOnFunction(Function &F);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.addPreserved<ProfileInfo>();
76 virtual void releaseMemory() {
81 bool EliminateMostlyEmptyBlocks(Function &F);
82 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
83 void EliminateMostlyEmptyBlock(BasicBlock *BB);
84 bool OptimizeBlock(BasicBlock &BB);
85 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
86 DenseMap<Value*,Value*> &SunkAddrs);
87 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
88 DenseMap<Value*,Value*> &SunkAddrs);
89 bool OptimizeCallInst(CallInst *CI);
90 bool MoveExtToFormExtLoad(Instruction *I);
91 bool OptimizeExtUses(Instruction *I);
92 void findLoopBackEdges(const Function &F);
96 char CodeGenPrepare::ID = 0;
97 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
98 "Optimize for code generation", false, false)
100 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
101 return new CodeGenPrepare(TLI);
104 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
106 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
107 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
108 FindFunctionBackedges(F, Edges);
110 BackEdges.insert(Edges.begin(), Edges.end());
114 bool CodeGenPrepare::runOnFunction(Function &F) {
115 bool EverMadeChange = false;
117 PFI = getAnalysisIfAvailable<ProfileInfo>();
118 // First pass, eliminate blocks that contain only PHI nodes and an
119 // unconditional branch.
120 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
122 // Now find loop back edges.
123 findLoopBackEdges(F);
125 bool MadeChange = true;
128 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
129 MadeChange |= OptimizeBlock(*BB);
130 EverMadeChange |= MadeChange;
132 return EverMadeChange;
135 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
136 /// debug info directives, and an unconditional branch. Passes before isel
137 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
138 /// isel. Start by eliminating these blocks so we can split them the way we
140 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
141 bool MadeChange = false;
142 // Note that this intentionally skips the entry block.
143 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
144 BasicBlock *BB = I++;
146 // If this block doesn't end with an uncond branch, ignore it.
147 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
148 if (!BI || !BI->isUnconditional())
151 // If the instruction before the branch (skipping debug info) isn't a phi
152 // node, then other stuff is happening here.
153 BasicBlock::iterator BBI = BI;
154 if (BBI != BB->begin()) {
156 while (isa<DbgInfoIntrinsic>(BBI)) {
157 if (BBI == BB->begin())
161 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
165 // Do not break infinite loops.
166 BasicBlock *DestBB = BI->getSuccessor(0);
170 if (!CanMergeBlocks(BB, DestBB))
173 EliminateMostlyEmptyBlock(BB);
179 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
180 /// single uncond branch between them, and BB contains no other non-phi
182 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
183 const BasicBlock *DestBB) const {
184 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
185 // the successor. If there are more complex condition (e.g. preheaders),
186 // don't mess around with them.
187 BasicBlock::const_iterator BBI = BB->begin();
188 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
189 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
191 const Instruction *User = cast<Instruction>(*UI);
192 if (User->getParent() != DestBB || !isa<PHINode>(User))
194 // If User is inside DestBB block and it is a PHINode then check
195 // incoming value. If incoming value is not from BB then this is
196 // a complex condition (e.g. preheaders) we want to avoid here.
197 if (User->getParent() == DestBB) {
198 if (const PHINode *UPN = dyn_cast<PHINode>(User))
199 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
200 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
201 if (Insn && Insn->getParent() == BB &&
202 Insn->getParent() != UPN->getIncomingBlock(I))
209 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
210 // and DestBB may have conflicting incoming values for the block. If so, we
211 // can't merge the block.
212 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
213 if (!DestBBPN) return true; // no conflict.
215 // Collect the preds of BB.
216 SmallPtrSet<const BasicBlock*, 16> BBPreds;
217 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
218 // It is faster to get preds from a PHI than with pred_iterator.
219 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
220 BBPreds.insert(BBPN->getIncomingBlock(i));
222 BBPreds.insert(pred_begin(BB), pred_end(BB));
225 // Walk the preds of DestBB.
226 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
227 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
228 if (BBPreds.count(Pred)) { // Common predecessor?
229 BBI = DestBB->begin();
230 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
231 const Value *V1 = PN->getIncomingValueForBlock(Pred);
232 const Value *V2 = PN->getIncomingValueForBlock(BB);
234 // If V2 is a phi node in BB, look up what the mapped value will be.
235 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
236 if (V2PN->getParent() == BB)
237 V2 = V2PN->getIncomingValueForBlock(Pred);
239 // If there is a conflict, bail out.
240 if (V1 != V2) return false;
249 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
250 /// an unconditional branch in it.
251 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
252 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
253 BasicBlock *DestBB = BI->getSuccessor(0);
255 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
257 // If the destination block has a single pred, then this is a trivial edge,
259 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
260 if (SinglePred != DestBB) {
261 // Remember if SinglePred was the entry block of the function. If so, we
262 // will need to move BB back to the entry position.
263 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
264 MergeBasicBlockIntoOnlyPred(DestBB, this);
266 if (isEntry && BB != &BB->getParent()->getEntryBlock())
267 BB->moveBefore(&BB->getParent()->getEntryBlock());
269 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
274 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
275 // to handle the new incoming edges it is about to have.
277 for (BasicBlock::iterator BBI = DestBB->begin();
278 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
279 // Remove the incoming value for BB, and remember it.
280 Value *InVal = PN->removeIncomingValue(BB, false);
282 // Two options: either the InVal is a phi node defined in BB or it is some
283 // value that dominates BB.
284 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
285 if (InValPhi && InValPhi->getParent() == BB) {
286 // Add all of the input values of the input PHI as inputs of this phi.
287 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
288 PN->addIncoming(InValPhi->getIncomingValue(i),
289 InValPhi->getIncomingBlock(i));
291 // Otherwise, add one instance of the dominating value for each edge that
292 // we will be adding.
293 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
294 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
295 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
297 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
298 PN->addIncoming(InVal, *PI);
303 // The PHIs are now updated, change everything that refers to BB to use
304 // DestBB and remove BB.
305 BB->replaceAllUsesWith(DestBB);
307 PFI->replaceAllUses(BB, DestBB);
308 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
310 BB->eraseFromParent();
313 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
316 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
317 /// lives in to see if there is a block that we can reuse as a critical edge
319 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
320 BasicBlock *Dest = DestPHI->getParent();
322 /// TIPHIValues - This array is lazily computed to determine the values of
323 /// PHIs in Dest that TI would provide.
324 SmallVector<Value*, 32> TIPHIValues;
326 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
327 unsigned TIBBEntryNo = 0;
329 // Check to see if Dest has any blocks that can be used as a split edge for
331 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
332 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
333 // To be usable, the pred has to end with an uncond branch to the dest.
334 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
335 if (!PredBr || !PredBr->isUnconditional())
337 // Must be empty other than the branch and debug info.
338 BasicBlock::iterator I = Pred->begin();
339 while (isa<DbgInfoIntrinsic>(I))
343 // Cannot be the entry block; its label does not get emitted.
344 if (Pred == &Dest->getParent()->getEntryBlock())
347 // Finally, since we know that Dest has phi nodes in it, we have to make
348 // sure that jumping to Pred will have the same effect as going to Dest in
349 // terms of PHI values.
352 unsigned PredEntryNo = pi;
354 bool FoundMatch = true;
355 for (BasicBlock::iterator I = Dest->begin();
356 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
357 if (PHINo == TIPHIValues.size()) {
358 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
359 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
360 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
363 // If the PHI entry doesn't work, we can't use this pred.
364 if (PN->getIncomingBlock(PredEntryNo) != Pred)
365 PredEntryNo = PN->getBasicBlockIndex(Pred);
367 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
373 // If we found a workable predecessor, change TI to branch to Succ.
381 /// SplitEdgeNicely - Split the critical edge from TI to its specified
382 /// successor if it will improve codegen. We only do this if the successor has
383 /// phi nodes (otherwise critical edges are ok). If there is already another
384 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
385 /// instead of introducing a new block.
386 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
387 SmallSet<std::pair<const BasicBlock*,
388 const BasicBlock*>, 8> &BackEdges,
390 BasicBlock *TIBB = TI->getParent();
391 BasicBlock *Dest = TI->getSuccessor(SuccNum);
392 assert(isa<PHINode>(Dest->begin()) &&
393 "This should only be called if Dest has a PHI!");
394 PHINode *DestPHI = cast<PHINode>(Dest->begin());
396 // Do not split edges to EH landing pads.
397 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
398 if (Invoke->getSuccessor(1) == Dest)
401 // As a hack, never split backedges of loops. Even though the copy for any
402 // PHIs inserted on the backedge would be dead for exits from the loop, we
403 // assume that the cost of *splitting* the backedge would be too high.
404 if (BackEdges.count(std::make_pair(TIBB, Dest)))
407 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
408 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
410 PFI->splitEdge(TIBB, Dest, ReuseBB);
411 Dest->removePredecessor(TIBB);
412 TI->setSuccessor(SuccNum, ReuseBB);
416 SplitCriticalEdge(TI, SuccNum, P, true);
420 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
421 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
422 /// sink it into user blocks to reduce the number of virtual
423 /// registers that must be created and coalesced.
425 /// Return true if any changes are made.
427 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
428 // If this is a noop copy,
429 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
430 EVT DstVT = TLI.getValueType(CI->getType());
432 // This is an fp<->int conversion?
433 if (SrcVT.isInteger() != DstVT.isInteger())
436 // If this is an extension, it will be a zero or sign extension, which
438 if (SrcVT.bitsLT(DstVT)) return false;
440 // If these values will be promoted, find out what they will be promoted
441 // to. This helps us consider truncates on PPC as noop copies when they
443 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
444 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
445 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
446 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
448 // If, after promotion, these are the same types, this is a noop copy.
452 BasicBlock *DefBB = CI->getParent();
454 /// InsertedCasts - Only insert a cast in each block once.
455 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
457 bool MadeChange = false;
458 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
460 Use &TheUse = UI.getUse();
461 Instruction *User = cast<Instruction>(*UI);
463 // Figure out which BB this cast is used in. For PHI's this is the
464 // appropriate predecessor block.
465 BasicBlock *UserBB = User->getParent();
466 if (PHINode *PN = dyn_cast<PHINode>(User)) {
467 UserBB = PN->getIncomingBlock(UI);
470 // Preincrement use iterator so we don't invalidate it.
473 // If this user is in the same block as the cast, don't change the cast.
474 if (UserBB == DefBB) continue;
476 // If we have already inserted a cast into this block, use it.
477 CastInst *&InsertedCast = InsertedCasts[UserBB];
480 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
483 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
488 // Replace a use of the cast with a use of the new cast.
489 TheUse = InsertedCast;
492 // If we removed all uses, nuke the cast.
493 if (CI->use_empty()) {
494 CI->eraseFromParent();
501 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
502 /// the number of virtual registers that must be created and coalesced. This is
503 /// a clear win except on targets with multiple condition code registers
504 /// (PowerPC), where it might lose; some adjustment may be wanted there.
506 /// Return true if any changes are made.
507 static bool OptimizeCmpExpression(CmpInst *CI) {
508 BasicBlock *DefBB = CI->getParent();
510 /// InsertedCmp - Only insert a cmp in each block once.
511 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
513 bool MadeChange = false;
514 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
516 Use &TheUse = UI.getUse();
517 Instruction *User = cast<Instruction>(*UI);
519 // Preincrement use iterator so we don't invalidate it.
522 // Don't bother for PHI nodes.
523 if (isa<PHINode>(User))
526 // Figure out which BB this cmp is used in.
527 BasicBlock *UserBB = User->getParent();
529 // If this user is in the same block as the cmp, don't change the cmp.
530 if (UserBB == DefBB) continue;
532 // If we have already inserted a cmp into this block, use it.
533 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
536 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
539 CmpInst::Create(CI->getOpcode(),
540 CI->getPredicate(), CI->getOperand(0),
541 CI->getOperand(1), "", InsertPt);
545 // Replace a use of the cmp with a use of the new cmp.
546 TheUse = InsertedCmp;
549 // If we removed all uses, nuke the cmp.
551 CI->eraseFromParent();
557 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
559 void replaceCall(Value *With) {
560 CI->replaceAllUsesWith(With);
561 CI->eraseFromParent();
563 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
564 if (ConstantInt *SizeCI =
565 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
566 return SizeCI->isAllOnesValue();
570 } // end anonymous namespace
572 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
573 // Lower all uses of llvm.objectsize.*
574 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
575 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
576 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
577 const Type *ReturnTy = CI->getType();
578 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
579 CI->replaceAllUsesWith(RetVal);
580 CI->eraseFromParent();
584 // From here on out we're working with named functions.
585 if (CI->getCalledFunction() == 0) return false;
587 // We'll need TargetData from here on out.
588 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
589 if (!TD) return false;
591 // Lower all default uses of _chk calls. This is very similar
592 // to what InstCombineCalls does, but here we are only lowering calls
593 // that have the default "don't know" as the objectsize. Anything else
594 // should be left alone.
595 CodeGenPrepareFortifiedLibCalls Simplifier;
596 return Simplifier.fold(CI, TD);
598 //===----------------------------------------------------------------------===//
599 // Memory Optimization
600 //===----------------------------------------------------------------------===//
602 /// IsNonLocalValue - Return true if the specified values are defined in a
603 /// different basic block than BB.
604 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
605 if (Instruction *I = dyn_cast<Instruction>(V))
606 return I->getParent() != BB;
610 /// OptimizeMemoryInst - Load and Store Instructions often have
611 /// addressing modes that can do significant amounts of computation. As such,
612 /// instruction selection will try to get the load or store to do as much
613 /// computation as possible for the program. The problem is that isel can only
614 /// see within a single block. As such, we sink as much legal addressing mode
615 /// stuff into the block as possible.
617 /// This method is used to optimize both load/store and inline asms with memory
619 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
620 const Type *AccessTy,
621 DenseMap<Value*,Value*> &SunkAddrs) {
624 // Try to collapse single-value PHI nodes. This is necessary to undo
625 // unprofitable PRE transformations.
626 std::vector<Value*> worklist;
627 SmallPtrSet<Value*, 4> Visited;
628 worklist.push_back(Addr);
630 // Use a worklist to iteratively look through PHI nodes, and ensure that
631 // the addressing mode obtained from the non-PHI roots of the graph
633 Value *Consensus = 0;
634 unsigned NumUses = 0;
635 SmallVector<Instruction*, 16> AddrModeInsts;
636 ExtAddrMode AddrMode;
637 while (!worklist.empty()) {
638 Value *V = worklist.back();
641 // Break use-def graph loops.
642 if (Visited.count(V)) {
649 // For a PHI node, push all of its incoming values.
650 if (PHINode *P = dyn_cast<PHINode>(V)) {
651 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
652 worklist.push_back(P->getIncomingValue(i));
656 // For non-PHIs, determine the addressing mode being computed.
657 SmallVector<Instruction*, 16> NewAddrModeInsts;
658 ExtAddrMode NewAddrMode =
659 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
660 NewAddrModeInsts, *TLI);
662 // Ensure that the obtained addressing mode is equivalent to that obtained
663 // for all other roots of the PHI traversal. Also, when choosing one
664 // such root as representative, select the one with the most uses in order
665 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
666 if (!Consensus || NewAddrMode == AddrMode) {
667 if (V->getNumUses() > NumUses) {
669 NumUses = V->getNumUses();
670 AddrMode = NewAddrMode;
671 AddrModeInsts = NewAddrModeInsts;
680 // If the addressing mode couldn't be determined, or if multiple different
681 // ones were determined, bail out now.
682 if (!Consensus) return false;
684 // Check to see if any of the instructions supersumed by this addr mode are
685 // non-local to I's BB.
686 bool AnyNonLocal = false;
687 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
688 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
694 // If all the instructions matched are already in this BB, don't do anything.
696 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
700 // Insert this computation right after this user. Since our caller is
701 // scanning from the top of the BB to the bottom, reuse of the expr are
702 // guaranteed to happen later.
703 BasicBlock::iterator InsertPt = MemoryInst;
705 // Now that we determined the addressing expression we want to use and know
706 // that we have to sink it into this block. Check to see if we have already
707 // done this for some other load/store instr in this block. If so, reuse the
709 Value *&SunkAddr = SunkAddrs[Addr];
711 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
713 if (SunkAddr->getType() != Addr->getType())
714 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
716 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
718 const Type *IntPtrTy =
719 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
723 // Start with the base register. Do this first so that subsequent address
724 // matching finds it last, which will prevent it from trying to match it
725 // as the scaled value in case it happens to be a mul. That would be
726 // problematic if we've sunk a different mul for the scale, because then
727 // we'd end up sinking both muls.
728 if (AddrMode.BaseReg) {
729 Value *V = AddrMode.BaseReg;
730 if (V->getType()->isPointerTy())
731 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
732 if (V->getType() != IntPtrTy)
733 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
734 "sunkaddr", InsertPt);
738 // Add the scale value.
739 if (AddrMode.Scale) {
740 Value *V = AddrMode.ScaledReg;
741 if (V->getType() == IntPtrTy) {
743 } else if (V->getType()->isPointerTy()) {
744 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
745 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
746 cast<IntegerType>(V->getType())->getBitWidth()) {
747 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
749 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
751 if (AddrMode.Scale != 1)
752 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
754 "sunkaddr", InsertPt);
756 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
761 // Add in the BaseGV if present.
762 if (AddrMode.BaseGV) {
763 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
766 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
771 // Add in the Base Offset if present.
772 if (AddrMode.BaseOffs) {
773 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
775 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
781 SunkAddr = Constant::getNullValue(Addr->getType());
783 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
786 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
788 if (Repl->use_empty()) {
789 RecursivelyDeleteTriviallyDeadInstructions(Repl);
790 // This address is now available for reassignment, so erase the table entry;
791 // we don't want to match some completely different instruction.
797 /// OptimizeInlineAsmInst - If there are any memory operands, use
798 /// OptimizeMemoryInst to sink their address computing into the block when
799 /// possible / profitable.
800 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
801 DenseMap<Value*,Value*> &SunkAddrs) {
802 bool MadeChange = false;
804 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
806 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
807 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
809 // Compute the constraint code and ConstraintType to use.
810 TLI->ComputeConstraintToUse(OpInfo, SDValue());
812 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
814 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
815 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
816 } else if (OpInfo.Type == InlineAsm::isInput)
823 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
824 /// basic block as the load, unless conditions are unfavorable. This allows
825 /// SelectionDAG to fold the extend into the load.
827 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
828 // Look for a load being extended.
829 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
830 if (!LI) return false;
832 // If they're already in the same block, there's nothing to do.
833 if (LI->getParent() == I->getParent())
836 // If the load has other users and the truncate is not free, this probably
838 if (!LI->hasOneUse() &&
839 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
840 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
841 !TLI->isTruncateFree(I->getType(), LI->getType()))
844 // Check whether the target supports casts folded into loads.
846 if (isa<ZExtInst>(I))
847 LType = ISD::ZEXTLOAD;
849 assert(isa<SExtInst>(I) && "Unexpected ext type!");
850 LType = ISD::SEXTLOAD;
852 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
855 // Move the extend into the same block as the load, so that SelectionDAG
857 I->removeFromParent();
862 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
863 BasicBlock *DefBB = I->getParent();
865 // If the result of a {s|z}ext and its source are both live out, rewrite all
866 // other uses of the source with result of extension.
867 Value *Src = I->getOperand(0);
868 if (Src->hasOneUse())
871 // Only do this xform if truncating is free.
872 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
875 // Only safe to perform the optimization if the source is also defined in
877 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
880 bool DefIsLiveOut = false;
881 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
883 Instruction *User = cast<Instruction>(*UI);
885 // Figure out which BB this ext is used in.
886 BasicBlock *UserBB = User->getParent();
887 if (UserBB == DefBB) continue;
894 // Make sure non of the uses are PHI nodes.
895 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
897 Instruction *User = cast<Instruction>(*UI);
898 BasicBlock *UserBB = User->getParent();
899 if (UserBB == DefBB) continue;
900 // Be conservative. We don't want this xform to end up introducing
901 // reloads just before load / store instructions.
902 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
906 // InsertedTruncs - Only insert one trunc in each block once.
907 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
909 bool MadeChange = false;
910 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
912 Use &TheUse = UI.getUse();
913 Instruction *User = cast<Instruction>(*UI);
915 // Figure out which BB this ext is used in.
916 BasicBlock *UserBB = User->getParent();
917 if (UserBB == DefBB) continue;
919 // Both src and def are live in this block. Rewrite the use.
920 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
922 if (!InsertedTrunc) {
923 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
925 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
928 // Replace a use of the {s|z}ext source with a use of the result.
929 TheUse = InsertedTrunc;
937 // In this pass we look for GEP and cast instructions that are used
938 // across basic blocks and rewrite them to improve basic-block-at-a-time
940 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
941 bool MadeChange = false;
943 // Split all critical edges where the dest block has a PHI.
944 if (CriticalEdgeSplit) {
945 TerminatorInst *BBTI = BB.getTerminator();
946 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
947 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
948 BasicBlock *SuccBB = BBTI->getSuccessor(i);
949 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
950 SplitEdgeNicely(BBTI, i, BackEdges, this);
955 // Keep track of non-local addresses that have been sunk into this block.
956 // This allows us to avoid inserting duplicate code for blocks with multiple
957 // load/stores of the same address.
958 DenseMap<Value*, Value*> SunkAddrs;
960 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
961 Instruction *I = BBI++;
963 if (PHINode *P = dyn_cast<PHINode>(I)) {
964 // It is possible for very late stage optimizations (such as SimplifyCFG)
965 // to introduce PHI nodes too late to be cleaned up. If we detect such a
966 // trivial PHI, go ahead and zap it here.
967 if (Value *V = SimplifyInstruction(P)) {
968 P->replaceAllUsesWith(V);
969 P->eraseFromParent();
971 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
972 // If the source of the cast is a constant, then this should have
973 // already been constant folded. The only reason NOT to constant fold
974 // it is if something (e.g. LSR) was careful to place the constant
975 // evaluation in a block other than then one that uses it (e.g. to hoist
976 // the address of globals out of a loop). If this is the case, we don't
977 // want to forward-subst the cast.
978 if (isa<Constant>(CI->getOperand(0)))
983 Change = OptimizeNoopCopyExpression(CI, *TLI);
984 MadeChange |= Change;
987 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
988 MadeChange |= MoveExtToFormExtLoad(I);
989 MadeChange |= OptimizeExtUses(I);
991 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
992 MadeChange |= OptimizeCmpExpression(CI);
993 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
995 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
997 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
999 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1000 SI->getOperand(0)->getType(),
1002 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1003 if (GEPI->hasAllZeroIndices()) {
1004 /// The GEP operand must be a pointer, so must its result -> BitCast
1005 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1006 GEPI->getName(), GEPI);
1007 GEPI->replaceAllUsesWith(NC);
1008 GEPI->eraseFromParent();
1012 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1013 // If we found an inline asm expession, and if the target knows how to
1014 // lower it to normal LLVM code, do so now.
1015 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1016 if (TLI->ExpandInlineAsm(CI)) {
1018 // Avoid processing instructions out of order, which could cause
1019 // reuse before a value is defined.
1022 // Sink address computing for memory operands into the block.
1023 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1025 // Other CallInst optimizations that don't need to muck with the
1026 // enclosing iterator here.
1027 MadeChange |= OptimizeCallInst(CI);