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/ProfileInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/Assembly/Writer.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm::PatternMatch;
43 class CodeGenPrepare : public FunctionPass {
44 /// TLI - Keep a pointer of a TargetLowering to consult for determining
45 /// transformation profitability.
46 const TargetLowering *TLI;
49 /// BackEdges - Keep a set of all the loop back edges.
51 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
53 static char ID; // Pass identification, replacement for typeid
54 explicit CodeGenPrepare(const TargetLowering *tli = 0)
55 : FunctionPass(&ID), TLI(tli) {}
56 bool runOnFunction(Function &F);
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addPreserved<ProfileInfo>();
62 virtual void releaseMemory() {
67 bool EliminateMostlyEmptyBlocks(Function &F);
68 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
69 void EliminateMostlyEmptyBlock(BasicBlock *BB);
70 bool OptimizeBlock(BasicBlock &BB);
71 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
72 DenseMap<Value*,Value*> &SunkAddrs);
73 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
74 DenseMap<Value*,Value*> &SunkAddrs);
75 bool MoveExtToFormExtLoad(Instruction *I);
76 bool OptimizeExtUses(Instruction *I);
77 void findLoopBackEdges(const Function &F);
81 char CodeGenPrepare::ID = 0;
82 static RegisterPass<CodeGenPrepare> X("codegenprepare",
83 "Optimize for code generation");
85 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
86 return new CodeGenPrepare(TLI);
89 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
91 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
92 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
93 FindFunctionBackedges(F, Edges);
95 BackEdges.insert(Edges.begin(), Edges.end());
99 bool CodeGenPrepare::runOnFunction(Function &F) {
100 bool EverMadeChange = false;
102 PFI = getAnalysisIfAvailable<ProfileInfo>();
103 // First pass, eliminate blocks that contain only PHI nodes and an
104 // unconditional branch.
105 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
107 // Now find loop back edges.
108 findLoopBackEdges(F);
110 bool MadeChange = true;
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
114 MadeChange |= OptimizeBlock(*BB);
115 EverMadeChange |= MadeChange;
117 return EverMadeChange;
120 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
121 /// debug info directives, and an unconditional branch. Passes before isel
122 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
123 /// isel. Start by eliminating these blocks so we can split them the way we
125 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
126 bool MadeChange = false;
127 // Note that this intentionally skips the entry block.
128 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
129 BasicBlock *BB = I++;
131 // If this block doesn't end with an uncond branch, ignore it.
132 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
133 if (!BI || !BI->isUnconditional())
136 // If the instruction before the branch (skipping debug info) isn't a phi
137 // node, then other stuff is happening here.
138 BasicBlock::iterator BBI = BI;
139 if (BBI != BB->begin()) {
141 while (isa<DbgInfoIntrinsic>(BBI)) {
142 if (BBI == BB->begin())
146 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
150 // Do not break infinite loops.
151 BasicBlock *DestBB = BI->getSuccessor(0);
155 if (!CanMergeBlocks(BB, DestBB))
158 EliminateMostlyEmptyBlock(BB);
164 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
165 /// single uncond branch between them, and BB contains no other non-phi
167 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
168 const BasicBlock *DestBB) const {
169 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
170 // the successor. If there are more complex condition (e.g. preheaders),
171 // don't mess around with them.
172 BasicBlock::const_iterator BBI = BB->begin();
173 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
174 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
176 const Instruction *User = cast<Instruction>(*UI);
177 if (User->getParent() != DestBB || !isa<PHINode>(User))
179 // If User is inside DestBB block and it is a PHINode then check
180 // incoming value. If incoming value is not from BB then this is
181 // a complex condition (e.g. preheaders) we want to avoid here.
182 if (User->getParent() == DestBB) {
183 if (const PHINode *UPN = dyn_cast<PHINode>(User))
184 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
185 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
186 if (Insn && Insn->getParent() == BB &&
187 Insn->getParent() != UPN->getIncomingBlock(I))
194 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
195 // and DestBB may have conflicting incoming values for the block. If so, we
196 // can't merge the block.
197 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
198 if (!DestBBPN) return true; // no conflict.
200 // Collect the preds of BB.
201 SmallPtrSet<const BasicBlock*, 16> BBPreds;
202 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
203 // It is faster to get preds from a PHI than with pred_iterator.
204 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
205 BBPreds.insert(BBPN->getIncomingBlock(i));
207 BBPreds.insert(pred_begin(BB), pred_end(BB));
210 // Walk the preds of DestBB.
211 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
212 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
213 if (BBPreds.count(Pred)) { // Common predecessor?
214 BBI = DestBB->begin();
215 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
216 const Value *V1 = PN->getIncomingValueForBlock(Pred);
217 const Value *V2 = PN->getIncomingValueForBlock(BB);
219 // If V2 is a phi node in BB, look up what the mapped value will be.
220 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
221 if (V2PN->getParent() == BB)
222 V2 = V2PN->getIncomingValueForBlock(Pred);
224 // If there is a conflict, bail out.
225 if (V1 != V2) return false;
234 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
235 /// an unconditional branch in it.
236 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
237 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
238 BasicBlock *DestBB = BI->getSuccessor(0);
240 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
242 // If the destination block has a single pred, then this is a trivial edge,
244 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
245 if (SinglePred != DestBB) {
246 // Remember if SinglePred was the entry block of the function. If so, we
247 // will need to move BB back to the entry position.
248 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
249 MergeBasicBlockIntoOnlyPred(DestBB, this);
251 if (isEntry && BB != &BB->getParent()->getEntryBlock())
252 BB->moveBefore(&BB->getParent()->getEntryBlock());
254 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
259 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
260 // to handle the new incoming edges it is about to have.
262 for (BasicBlock::iterator BBI = DestBB->begin();
263 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
264 // Remove the incoming value for BB, and remember it.
265 Value *InVal = PN->removeIncomingValue(BB, false);
267 // Two options: either the InVal is a phi node defined in BB or it is some
268 // value that dominates BB.
269 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
270 if (InValPhi && InValPhi->getParent() == BB) {
271 // Add all of the input values of the input PHI as inputs of this phi.
272 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
273 PN->addIncoming(InValPhi->getIncomingValue(i),
274 InValPhi->getIncomingBlock(i));
276 // Otherwise, add one instance of the dominating value for each edge that
277 // we will be adding.
278 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
279 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
280 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
282 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
283 PN->addIncoming(InVal, *PI);
288 // The PHIs are now updated, change everything that refers to BB to use
289 // DestBB and remove BB.
290 BB->replaceAllUsesWith(DestBB);
292 PFI->replaceAllUses(BB, DestBB);
293 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
295 BB->eraseFromParent();
297 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
300 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
301 /// lives in to see if there is a block that we can reuse as a critical edge
303 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
304 BasicBlock *Dest = DestPHI->getParent();
306 /// TIPHIValues - This array is lazily computed to determine the values of
307 /// PHIs in Dest that TI would provide.
308 SmallVector<Value*, 32> TIPHIValues;
310 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
311 unsigned TIBBEntryNo = 0;
313 // Check to see if Dest has any blocks that can be used as a split edge for
315 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
316 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
317 // To be usable, the pred has to end with an uncond branch to the dest.
318 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
319 if (!PredBr || !PredBr->isUnconditional())
321 // Must be empty other than the branch and debug info.
322 BasicBlock::iterator I = Pred->begin();
323 while (isa<DbgInfoIntrinsic>(I))
327 // Cannot be the entry block; its label does not get emitted.
328 if (Pred == &Dest->getParent()->getEntryBlock())
331 // Finally, since we know that Dest has phi nodes in it, we have to make
332 // sure that jumping to Pred will have the same effect as going to Dest in
333 // terms of PHI values.
336 unsigned PredEntryNo = pi;
338 bool FoundMatch = true;
339 for (BasicBlock::iterator I = Dest->begin();
340 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
341 if (PHINo == TIPHIValues.size()) {
342 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
343 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
344 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
347 // If the PHI entry doesn't work, we can't use this pred.
348 if (PN->getIncomingBlock(PredEntryNo) != Pred)
349 PredEntryNo = PN->getBasicBlockIndex(Pred);
351 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
357 // If we found a workable predecessor, change TI to branch to Succ.
365 /// SplitEdgeNicely - Split the critical edge from TI to its specified
366 /// successor if it will improve codegen. We only do this if the successor has
367 /// phi nodes (otherwise critical edges are ok). If there is already another
368 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
369 /// instead of introducing a new block.
370 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
371 SmallSet<std::pair<const BasicBlock*,
372 const BasicBlock*>, 8> &BackEdges,
374 BasicBlock *TIBB = TI->getParent();
375 BasicBlock *Dest = TI->getSuccessor(SuccNum);
376 assert(isa<PHINode>(Dest->begin()) &&
377 "This should only be called if Dest has a PHI!");
378 PHINode *DestPHI = cast<PHINode>(Dest->begin());
380 // Do not split edges to EH landing pads.
381 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
382 if (Invoke->getSuccessor(1) == Dest)
385 // As a hack, never split backedges of loops. Even though the copy for any
386 // PHIs inserted on the backedge would be dead for exits from the loop, we
387 // assume that the cost of *splitting* the backedge would be too high.
388 if (BackEdges.count(std::make_pair(TIBB, Dest)))
391 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
392 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
394 PFI->splitEdge(TIBB, Dest, ReuseBB);
395 Dest->removePredecessor(TIBB);
396 TI->setSuccessor(SuccNum, ReuseBB);
400 SplitCriticalEdge(TI, SuccNum, P, true);
404 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
405 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
406 /// sink it into user blocks to reduce the number of virtual
407 /// registers that must be created and coalesced.
409 /// Return true if any changes are made.
411 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
412 // If this is a noop copy,
413 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
414 EVT DstVT = TLI.getValueType(CI->getType());
416 // This is an fp<->int conversion?
417 if (SrcVT.isInteger() != DstVT.isInteger())
420 // If this is an extension, it will be a zero or sign extension, which
422 if (SrcVT.bitsLT(DstVT)) return false;
424 // If these values will be promoted, find out what they will be promoted
425 // to. This helps us consider truncates on PPC as noop copies when they
427 if (TLI.getTypeAction(CI->getContext(), SrcVT) == TargetLowering::Promote)
428 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
429 if (TLI.getTypeAction(CI->getContext(), DstVT) == TargetLowering::Promote)
430 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
432 // If, after promotion, these are the same types, this is a noop copy.
436 BasicBlock *DefBB = CI->getParent();
438 /// InsertedCasts - Only insert a cast in each block once.
439 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
441 bool MadeChange = false;
442 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
444 Use &TheUse = UI.getUse();
445 Instruction *User = cast<Instruction>(*UI);
447 // Figure out which BB this cast is used in. For PHI's this is the
448 // appropriate predecessor block.
449 BasicBlock *UserBB = User->getParent();
450 if (PHINode *PN = dyn_cast<PHINode>(User)) {
451 UserBB = PN->getIncomingBlock(UI);
454 // Preincrement use iterator so we don't invalidate it.
457 // If this user is in the same block as the cast, don't change the cast.
458 if (UserBB == DefBB) continue;
460 // If we have already inserted a cast into this block, use it.
461 CastInst *&InsertedCast = InsertedCasts[UserBB];
464 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
467 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
472 // Replace a use of the cast with a use of the new cast.
473 TheUse = InsertedCast;
476 // If we removed all uses, nuke the cast.
477 if (CI->use_empty()) {
478 CI->eraseFromParent();
485 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
486 /// the number of virtual registers that must be created and coalesced. This is
487 /// a clear win except on targets with multiple condition code registers
488 /// (PowerPC), where it might lose; some adjustment may be wanted there.
490 /// Return true if any changes are made.
491 static bool OptimizeCmpExpression(CmpInst *CI) {
492 BasicBlock *DefBB = CI->getParent();
494 /// InsertedCmp - Only insert a cmp in each block once.
495 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
497 bool MadeChange = false;
498 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
500 Use &TheUse = UI.getUse();
501 Instruction *User = cast<Instruction>(*UI);
503 // Preincrement use iterator so we don't invalidate it.
506 // Don't bother for PHI nodes.
507 if (isa<PHINode>(User))
510 // Figure out which BB this cmp is used in.
511 BasicBlock *UserBB = User->getParent();
513 // If this user is in the same block as the cmp, don't change the cmp.
514 if (UserBB == DefBB) continue;
516 // If we have already inserted a cmp into this block, use it.
517 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
520 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
523 CmpInst::Create(CI->getOpcode(),
524 CI->getPredicate(), CI->getOperand(0),
525 CI->getOperand(1), "", InsertPt);
529 // Replace a use of the cmp with a use of the new cmp.
530 TheUse = InsertedCmp;
533 // If we removed all uses, nuke the cmp.
535 CI->eraseFromParent();
540 //===----------------------------------------------------------------------===//
541 // Memory Optimization
542 //===----------------------------------------------------------------------===//
544 /// IsNonLocalValue - Return true if the specified values are defined in a
545 /// different basic block than BB.
546 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
547 if (Instruction *I = dyn_cast<Instruction>(V))
548 return I->getParent() != BB;
552 /// OptimizeMemoryInst - Load and Store Instructions often have
553 /// addressing modes that can do significant amounts of computation. As such,
554 /// instruction selection will try to get the load or store to do as much
555 /// computation as possible for the program. The problem is that isel can only
556 /// see within a single block. As such, we sink as much legal addressing mode
557 /// stuff into the block as possible.
559 /// This method is used to optimize both load/store and inline asms with memory
561 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
562 const Type *AccessTy,
563 DenseMap<Value*,Value*> &SunkAddrs) {
564 // Figure out what addressing mode will be built up for this operation.
565 SmallVector<Instruction*, 16> AddrModeInsts;
566 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
567 AddrModeInsts, *TLI);
569 // Check to see if any of the instructions supersumed by this addr mode are
570 // non-local to I's BB.
571 bool AnyNonLocal = false;
572 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
573 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
579 // If all the instructions matched are already in this BB, don't do anything.
581 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
585 // Insert this computation right after this user. Since our caller is
586 // scanning from the top of the BB to the bottom, reuse of the expr are
587 // guaranteed to happen later.
588 BasicBlock::iterator InsertPt = MemoryInst;
590 // Now that we determined the addressing expression we want to use and know
591 // that we have to sink it into this block. Check to see if we have already
592 // done this for some other load/store instr in this block. If so, reuse the
594 Value *&SunkAddr = SunkAddrs[Addr];
596 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
598 if (SunkAddr->getType() != Addr->getType())
599 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
601 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
603 const Type *IntPtrTy =
604 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
608 // Start with the base register. Do this first so that subsequent address
609 // matching finds it last, which will prevent it from trying to match it
610 // as the scaled value in case it happens to be a mul. That would be
611 // problematic if we've sunk a different mul for the scale, because then
612 // we'd end up sinking both muls.
613 if (AddrMode.BaseReg) {
614 Value *V = AddrMode.BaseReg;
615 if (V->getType()->isPointerTy())
616 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
617 if (V->getType() != IntPtrTy)
618 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
619 "sunkaddr", InsertPt);
623 // Add the scale value.
624 if (AddrMode.Scale) {
625 Value *V = AddrMode.ScaledReg;
626 if (V->getType() == IntPtrTy) {
628 } else if (V->getType()->isPointerTy()) {
629 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
630 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
631 cast<IntegerType>(V->getType())->getBitWidth()) {
632 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
634 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
636 if (AddrMode.Scale != 1)
637 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
639 "sunkaddr", InsertPt);
641 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
646 // Add in the BaseGV if present.
647 if (AddrMode.BaseGV) {
648 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
651 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
656 // Add in the Base Offset if present.
657 if (AddrMode.BaseOffs) {
658 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
660 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
666 SunkAddr = Constant::getNullValue(Addr->getType());
668 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
671 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
673 if (Addr->use_empty())
674 RecursivelyDeleteTriviallyDeadInstructions(Addr);
678 /// OptimizeInlineAsmInst - If there are any memory operands, use
679 /// OptimizeMemoryInst to sink their address computing into the block when
680 /// possible / profitable.
681 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
682 DenseMap<Value*,Value*> &SunkAddrs) {
683 bool MadeChange = false;
684 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
686 // Do a prepass over the constraints, canonicalizing them, and building up the
687 // ConstraintOperands list.
688 std::vector<InlineAsm::ConstraintInfo>
689 ConstraintInfos = IA->ParseConstraints();
691 /// ConstraintOperands - Information about all of the constraints.
692 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
693 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
694 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
696 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
697 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
699 // Compute the value type for each operand.
700 switch (OpInfo.Type) {
701 case InlineAsm::isOutput:
702 if (OpInfo.isIndirect)
703 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
705 case InlineAsm::isInput:
706 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
708 case InlineAsm::isClobber:
713 // Compute the constraint code and ConstraintType to use.
714 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
715 OpInfo.ConstraintType == TargetLowering::C_Memory);
717 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
719 Value *OpVal = OpInfo.CallOperandVal;
720 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
727 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
728 /// basic block as the load, unless conditions are unfavorable. This allows
729 /// SelectionDAG to fold the extend into the load.
731 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
732 // Look for a load being extended.
733 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
734 if (!LI) return false;
736 // If they're already in the same block, there's nothing to do.
737 if (LI->getParent() == I->getParent())
740 // If the load has other users and the truncate is not free, this probably
742 if (!LI->hasOneUse() &&
743 TLI && !TLI->isTruncateFree(I->getType(), LI->getType()))
746 // Check whether the target supports casts folded into loads.
748 if (isa<ZExtInst>(I))
749 LType = ISD::ZEXTLOAD;
751 assert(isa<SExtInst>(I) && "Unexpected ext type!");
752 LType = ISD::SEXTLOAD;
754 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
757 // Move the extend into the same block as the load, so that SelectionDAG
759 I->removeFromParent();
764 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
765 BasicBlock *DefBB = I->getParent();
767 // If both result of the {s|z}xt and its source are live out, rewrite all
768 // other uses of the source with result of extension.
769 Value *Src = I->getOperand(0);
770 if (Src->hasOneUse())
773 // Only do this xform if truncating is free.
774 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
777 // Only safe to perform the optimization if the source is also defined in
779 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
782 bool DefIsLiveOut = false;
783 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
785 Instruction *User = cast<Instruction>(*UI);
787 // Figure out which BB this ext is used in.
788 BasicBlock *UserBB = User->getParent();
789 if (UserBB == DefBB) continue;
796 // Make sure non of the uses are PHI nodes.
797 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
799 Instruction *User = cast<Instruction>(*UI);
800 BasicBlock *UserBB = User->getParent();
801 if (UserBB == DefBB) continue;
802 // Be conservative. We don't want this xform to end up introducing
803 // reloads just before load / store instructions.
804 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
808 // InsertedTruncs - Only insert one trunc in each block once.
809 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
811 bool MadeChange = false;
812 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
814 Use &TheUse = UI.getUse();
815 Instruction *User = cast<Instruction>(*UI);
817 // Figure out which BB this ext is used in.
818 BasicBlock *UserBB = User->getParent();
819 if (UserBB == DefBB) continue;
821 // Both src and def are live in this block. Rewrite the use.
822 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
824 if (!InsertedTrunc) {
825 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
827 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
830 // Replace a use of the {s|z}ext source with a use of the result.
831 TheUse = InsertedTrunc;
839 // In this pass we look for GEP and cast instructions that are used
840 // across basic blocks and rewrite them to improve basic-block-at-a-time
842 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
843 bool MadeChange = false;
845 // Split all critical edges where the dest block has a PHI.
846 TerminatorInst *BBTI = BB.getTerminator();
847 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
848 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
849 BasicBlock *SuccBB = BBTI->getSuccessor(i);
850 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
851 SplitEdgeNicely(BBTI, i, BackEdges, this);
855 // Keep track of non-local addresses that have been sunk into this block.
856 // This allows us to avoid inserting duplicate code for blocks with multiple
857 // load/stores of the same address.
858 DenseMap<Value*, Value*> SunkAddrs;
860 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
861 Instruction *I = BBI++;
863 if (CastInst *CI = dyn_cast<CastInst>(I)) {
864 // If the source of the cast is a constant, then this should have
865 // already been constant folded. The only reason NOT to constant fold
866 // it is if something (e.g. LSR) was careful to place the constant
867 // evaluation in a block other than then one that uses it (e.g. to hoist
868 // the address of globals out of a loop). If this is the case, we don't
869 // want to forward-subst the cast.
870 if (isa<Constant>(CI->getOperand(0)))
875 Change = OptimizeNoopCopyExpression(CI, *TLI);
876 MadeChange |= Change;
879 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
880 MadeChange |= MoveExtToFormExtLoad(I);
881 MadeChange |= OptimizeExtUses(I);
883 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
884 MadeChange |= OptimizeCmpExpression(CI);
885 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
887 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
889 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
891 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
892 SI->getOperand(0)->getType(),
894 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
895 if (GEPI->hasAllZeroIndices()) {
896 /// The GEP operand must be a pointer, so must its result -> BitCast
897 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
898 GEPI->getName(), GEPI);
899 GEPI->replaceAllUsesWith(NC);
900 GEPI->eraseFromParent();
904 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
905 // If we found an inline asm expession, and if the target knows how to
906 // lower it to normal LLVM code, do so now.
907 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
908 if (TLI->ExpandInlineAsm(CI)) {
910 // Avoid processing instructions out of order, which could cause
911 // reuse before a value is defined.
914 // Sink address computing for memory operands into the block.
915 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);