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/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.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/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/Assembly/Writer.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
42 using namespace llvm::PatternMatch;
44 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
48 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
49 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
53 /// BackEdges - Keep a set of all the loop back edges.
55 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
57 static char ID; // Pass identification, replacement for typeid
58 explicit CodeGenPrepare(const TargetLowering *tli = 0)
59 : FunctionPass(&ID), TLI(tli) {}
60 bool runOnFunction(Function &F);
63 bool EliminateMostlyEmptyBlocks(Function &F);
64 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65 void EliminateMostlyEmptyBlock(BasicBlock *BB);
66 bool OptimizeBlock(BasicBlock &BB);
67 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68 DenseMap<Value*,Value*> &SunkAddrs);
69 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70 DenseMap<Value*,Value*> &SunkAddrs);
71 bool OptimizeExtUses(Instruction *I);
72 void findLoopBackEdges(Function &F);
76 char CodeGenPrepare::ID = 0;
77 static RegisterPass<CodeGenPrepare> X("codegenprepare",
78 "Optimize for code generation");
80 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81 return new CodeGenPrepare(TLI);
84 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
86 void CodeGenPrepare::findLoopBackEdges(Function &F) {
87 SmallPtrSet<BasicBlock*, 8> Visited;
88 SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
89 SmallPtrSet<BasicBlock*, 8> InStack;
91 BasicBlock *BB = &F.getEntryBlock();
92 if (succ_begin(BB) == succ_end(BB))
95 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
98 std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
99 BasicBlock *ParentBB = Top.first;
100 succ_iterator &I = Top.second;
102 bool FoundNew = false;
103 while (I != succ_end(ParentBB)) {
105 if (Visited.insert(BB)) {
109 // Successor is in VisitStack, it's a back edge.
110 if (InStack.count(BB))
111 BackEdges.insert(std::make_pair(ParentBB, BB));
115 // Go down one level if there is a unvisited successor.
117 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
120 std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
121 InStack.erase(Pop.first);
122 VisitStack.pop_back();
124 } while (!VisitStack.empty());
128 bool CodeGenPrepare::runOnFunction(Function &F) {
129 bool EverMadeChange = false;
131 // First pass, eliminate blocks that contain only PHI nodes and an
132 // unconditional branch.
133 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
135 // Now find loop back edges.
136 findLoopBackEdges(F);
138 bool MadeChange = true;
141 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
142 MadeChange |= OptimizeBlock(*BB);
143 EverMadeChange |= MadeChange;
145 return EverMadeChange;
148 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
149 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
150 /// often split edges in ways that are non-optimal for isel. Start by
151 /// eliminating these blocks so we can split them the way we want them.
152 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
153 bool MadeChange = false;
154 // Note that this intentionally skips the entry block.
155 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
156 BasicBlock *BB = I++;
158 // If this block doesn't end with an uncond branch, ignore it.
159 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
160 if (!BI || !BI->isUnconditional())
163 // If the instruction before the branch isn't a phi node, then other stuff
164 // is happening here.
165 BasicBlock::iterator BBI = BI;
166 if (BBI != BB->begin()) {
168 if (!isa<PHINode>(BBI)) continue;
171 // Do not break infinite loops.
172 BasicBlock *DestBB = BI->getSuccessor(0);
176 if (!CanMergeBlocks(BB, DestBB))
179 EliminateMostlyEmptyBlock(BB);
185 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
186 /// single uncond branch between them, and BB contains no other non-phi
188 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
189 const BasicBlock *DestBB) const {
190 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
191 // the successor. If there are more complex condition (e.g. preheaders),
192 // don't mess around with them.
193 BasicBlock::const_iterator BBI = BB->begin();
194 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
195 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
197 const Instruction *User = cast<Instruction>(*UI);
198 if (User->getParent() != DestBB || !isa<PHINode>(User))
200 // If User is inside DestBB block and it is a PHINode then check
201 // incoming value. If incoming value is not from BB then this is
202 // a complex condition (e.g. preheaders) we want to avoid here.
203 if (User->getParent() == DestBB) {
204 if (const PHINode *UPN = dyn_cast<PHINode>(User))
205 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
206 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
207 if (Insn && Insn->getParent() == BB &&
208 Insn->getParent() != UPN->getIncomingBlock(I))
215 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
216 // and DestBB may have conflicting incoming values for the block. If so, we
217 // can't merge the block.
218 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
219 if (!DestBBPN) return true; // no conflict.
221 // Collect the preds of BB.
222 SmallPtrSet<const BasicBlock*, 16> BBPreds;
223 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
224 // It is faster to get preds from a PHI than with pred_iterator.
225 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
226 BBPreds.insert(BBPN->getIncomingBlock(i));
228 BBPreds.insert(pred_begin(BB), pred_end(BB));
231 // Walk the preds of DestBB.
232 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
233 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
234 if (BBPreds.count(Pred)) { // Common predecessor?
235 BBI = DestBB->begin();
236 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
237 const Value *V1 = PN->getIncomingValueForBlock(Pred);
238 const Value *V2 = PN->getIncomingValueForBlock(BB);
240 // If V2 is a phi node in BB, look up what the mapped value will be.
241 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
242 if (V2PN->getParent() == BB)
243 V2 = V2PN->getIncomingValueForBlock(Pred);
245 // If there is a conflict, bail out.
246 if (V1 != V2) return false;
255 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
256 /// an unconditional branch in it.
257 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
258 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
259 BasicBlock *DestBB = BI->getSuccessor(0);
261 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
263 // If the destination block has a single pred, then this is a trivial edge,
265 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
266 if (SinglePred != DestBB) {
267 // Remember if SinglePred was the entry block of the function. If so, we
268 // will need to move BB back to the entry position.
269 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
270 MergeBasicBlockIntoOnlyPred(DestBB);
272 if (isEntry && BB != &BB->getParent()->getEntryBlock())
273 BB->moveBefore(&BB->getParent()->getEntryBlock());
275 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
280 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
281 // to handle the new incoming edges it is about to have.
283 for (BasicBlock::iterator BBI = DestBB->begin();
284 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
285 // Remove the incoming value for BB, and remember it.
286 Value *InVal = PN->removeIncomingValue(BB, false);
288 // Two options: either the InVal is a phi node defined in BB or it is some
289 // value that dominates BB.
290 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
291 if (InValPhi && InValPhi->getParent() == BB) {
292 // Add all of the input values of the input PHI as inputs of this phi.
293 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
294 PN->addIncoming(InValPhi->getIncomingValue(i),
295 InValPhi->getIncomingBlock(i));
297 // Otherwise, add one instance of the dominating value for each edge that
298 // we will be adding.
299 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
300 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
301 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
303 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
304 PN->addIncoming(InVal, *PI);
309 // The PHIs are now updated, change everything that refers to BB to use
310 // DestBB and remove BB.
311 BB->replaceAllUsesWith(DestBB);
312 BB->eraseFromParent();
314 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
318 /// SplitEdgeNicely - Split the critical edge from TI to its specified
319 /// successor if it will improve codegen. We only do this if the successor has
320 /// phi nodes (otherwise critical edges are ok). If there is already another
321 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
322 /// instead of introducing a new block.
323 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
324 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
326 BasicBlock *TIBB = TI->getParent();
327 BasicBlock *Dest = TI->getSuccessor(SuccNum);
328 assert(isa<PHINode>(Dest->begin()) &&
329 "This should only be called if Dest has a PHI!");
331 // Do not split edges to EH landing pads.
332 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
333 if (Invoke->getSuccessor(1) == Dest)
337 // As a hack, never split backedges of loops. Even though the copy for any
338 // PHIs inserted on the backedge would be dead for exits from the loop, we
339 // assume that the cost of *splitting* the backedge would be too high.
340 if (BackEdges.count(std::make_pair(TIBB, Dest)))
343 if (!FactorCommonPreds) {
344 /// TIPHIValues - This array is lazily computed to determine the values of
345 /// PHIs in Dest that TI would provide.
346 SmallVector<Value*, 32> TIPHIValues;
348 // Check to see if Dest has any blocks that can be used as a split edge for
350 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
351 BasicBlock *Pred = *PI;
352 // To be usable, the pred has to end with an uncond branch to the dest.
353 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
354 if (!PredBr || !PredBr->isUnconditional())
356 // Must be empty other than the branch and debug info.
357 BasicBlock::iterator I = Pred->begin();
358 while (isa<DbgInfoIntrinsic>(I))
360 if (dyn_cast<Instruction>(I) != PredBr)
362 // Cannot be the entry block; its label does not get emitted.
363 if (Pred == &(Dest->getParent()->getEntryBlock()))
366 // Finally, since we know that Dest has phi nodes in it, we have to make
367 // sure that jumping to Pred will have the same effect as going to Dest in
368 // terms of PHI values.
371 bool FoundMatch = true;
372 for (BasicBlock::iterator I = Dest->begin();
373 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
374 if (PHINo == TIPHIValues.size())
375 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
377 // If the PHI entry doesn't work, we can't use this pred.
378 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
384 // If we found a workable predecessor, change TI to branch to Succ.
386 Dest->removePredecessor(TIBB);
387 TI->setSuccessor(SuccNum, Pred);
392 SplitCriticalEdge(TI, SuccNum, P, true);
397 SmallVector<Value*, 8> TIPHIValues;
398 for (BasicBlock::iterator I = Dest->begin();
399 (PN = dyn_cast<PHINode>(I)); ++I)
400 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
402 SmallVector<BasicBlock*, 8> IdenticalPreds;
403 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
404 BasicBlock *Pred = *PI;
405 if (BackEdges.count(std::make_pair(Pred, Dest)))
408 IdenticalPreds.push_back(Pred);
410 bool Identical = true;
412 for (BasicBlock::iterator I = Dest->begin();
413 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
414 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
419 IdenticalPreds.push_back(Pred);
423 assert(!IdenticalPreds.empty());
424 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
429 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
430 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
431 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
432 /// registers that must be created and coalesced.
434 /// Return true if any changes are made.
436 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
437 // If this is a noop copy,
438 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
439 MVT DstVT = TLI.getValueType(CI->getType());
441 // This is an fp<->int conversion?
442 if (SrcVT.isInteger() != DstVT.isInteger())
445 // If this is an extension, it will be a zero or sign extension, which
447 if (SrcVT.bitsLT(DstVT)) return false;
449 // If these values will be promoted, find out what they will be promoted
450 // to. This helps us consider truncates on PPC as noop copies when they
452 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
453 SrcVT = TLI.getTypeToTransformTo(SrcVT);
454 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
455 DstVT = TLI.getTypeToTransformTo(DstVT);
457 // If, after promotion, these are the same types, this is a noop copy.
461 BasicBlock *DefBB = CI->getParent();
463 /// InsertedCasts - Only insert a cast in each block once.
464 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
466 bool MadeChange = false;
467 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
469 Use &TheUse = UI.getUse();
470 Instruction *User = cast<Instruction>(*UI);
472 // Figure out which BB this cast is used in. For PHI's this is the
473 // appropriate predecessor block.
474 BasicBlock *UserBB = User->getParent();
475 if (PHINode *PN = dyn_cast<PHINode>(User)) {
476 UserBB = PN->getIncomingBlock(UI);
479 // Preincrement use iterator so we don't invalidate it.
482 // If this user is in the same block as the cast, don't change the cast.
483 if (UserBB == DefBB) continue;
485 // If we have already inserted a cast into this block, use it.
486 CastInst *&InsertedCast = InsertedCasts[UserBB];
489 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
492 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
497 // Replace a use of the cast with a use of the new cast.
498 TheUse = InsertedCast;
501 // If we removed all uses, nuke the cast.
502 if (CI->use_empty()) {
503 CI->eraseFromParent();
510 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
511 /// the number of virtual registers that must be created and coalesced. This is
512 /// a clear win except on targets with multiple condition code registers
513 /// (PowerPC), where it might lose; some adjustment may be wanted there.
515 /// Return true if any changes are made.
516 static bool OptimizeCmpExpression(CmpInst *CI) {
517 BasicBlock *DefBB = CI->getParent();
519 /// InsertedCmp - Only insert a cmp in each block once.
520 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
522 bool MadeChange = false;
523 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
525 Use &TheUse = UI.getUse();
526 Instruction *User = cast<Instruction>(*UI);
528 // Preincrement use iterator so we don't invalidate it.
531 // Don't bother for PHI nodes.
532 if (isa<PHINode>(User))
535 // Figure out which BB this cmp is used in.
536 BasicBlock *UserBB = User->getParent();
538 // If this user is in the same block as the cmp, don't change the cmp.
539 if (UserBB == DefBB) continue;
541 // If we have already inserted a cmp into this block, use it.
542 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
545 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
548 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
549 CI->getOperand(1), "", InsertPt);
553 // Replace a use of the cmp with a use of the new cmp.
554 TheUse = InsertedCmp;
557 // If we removed all uses, nuke the cmp.
559 CI->eraseFromParent();
564 //===----------------------------------------------------------------------===//
565 // Addressing Mode Analysis and Optimization
566 //===----------------------------------------------------------------------===//
568 //===----------------------------------------------------------------------===//
569 // Memory Optimization
570 //===----------------------------------------------------------------------===//
572 /// IsNonLocalValue - Return true if the specified values are defined in a
573 /// different basic block than BB.
574 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
575 if (Instruction *I = dyn_cast<Instruction>(V))
576 return I->getParent() != BB;
580 /// OptimizeMemoryInst - Load and Store Instructions have often have
581 /// addressing modes that can do significant amounts of computation. As such,
582 /// instruction selection will try to get the load or store to do as much
583 /// computation as possible for the program. The problem is that isel can only
584 /// see within a single block. As such, we sink as much legal addressing mode
585 /// stuff into the block as possible.
587 /// This method is used to optimize both load/store and inline asms with memory
589 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
590 const Type *AccessTy,
591 DenseMap<Value*,Value*> &SunkAddrs) {
592 // Figure out what addressing mode will be built up for this operation.
593 SmallVector<Instruction*, 16> AddrModeInsts;
594 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
595 AddrModeInsts, *TLI);
597 // Check to see if any of the instructions supersumed by this addr mode are
598 // non-local to I's BB.
599 bool AnyNonLocal = false;
600 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
601 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
607 // If all the instructions matched are already in this BB, don't do anything.
609 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
613 // Insert this computation right after this user. Since our caller is
614 // scanning from the top of the BB to the bottom, reuse of the expr are
615 // guaranteed to happen later.
616 BasicBlock::iterator InsertPt = MemoryInst;
618 // Now that we determined the addressing expression we want to use and know
619 // that we have to sink it into this block. Check to see if we have already
620 // done this for some other load/store instr in this block. If so, reuse the
622 Value *&SunkAddr = SunkAddrs[Addr];
624 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
626 if (SunkAddr->getType() != Addr->getType())
627 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
629 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
631 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
634 // Start with the scale value.
635 if (AddrMode.Scale) {
636 Value *V = AddrMode.ScaledReg;
637 if (V->getType() == IntPtrTy) {
639 } else if (isa<PointerType>(V->getType())) {
640 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
641 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
642 cast<IntegerType>(V->getType())->getBitWidth()) {
643 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
645 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
647 if (AddrMode.Scale != 1)
648 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
650 "sunkaddr", InsertPt);
654 // Add in the base register.
655 if (AddrMode.BaseReg) {
656 Value *V = AddrMode.BaseReg;
657 if (V->getType() != IntPtrTy)
658 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
660 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
665 // Add in the BaseGV if present.
666 if (AddrMode.BaseGV) {
667 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
670 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
675 // Add in the Base Offset if present.
676 if (AddrMode.BaseOffs) {
677 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
679 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
685 SunkAddr = Constant::getNullValue(Addr->getType());
687 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
690 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
692 if (Addr->use_empty())
693 RecursivelyDeleteTriviallyDeadInstructions(Addr);
697 /// OptimizeInlineAsmInst - If there are any memory operands, use
698 /// OptimizeMemoryInst to sink their address computing into the block when
699 /// possible / profitable.
700 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
701 DenseMap<Value*,Value*> &SunkAddrs) {
702 bool MadeChange = false;
703 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
705 // Do a prepass over the constraints, canonicalizing them, and building up the
706 // ConstraintOperands list.
707 std::vector<InlineAsm::ConstraintInfo>
708 ConstraintInfos = IA->ParseConstraints();
710 /// ConstraintOperands - Information about all of the constraints.
711 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
712 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
713 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
715 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
716 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
718 // Compute the value type for each operand.
719 switch (OpInfo.Type) {
720 case InlineAsm::isOutput:
721 if (OpInfo.isIndirect)
722 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
724 case InlineAsm::isInput:
725 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
727 case InlineAsm::isClobber:
732 // Compute the constraint code and ConstraintType to use.
733 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
734 OpInfo.ConstraintType == TargetLowering::C_Memory);
736 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
738 Value *OpVal = OpInfo.CallOperandVal;
739 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
746 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
747 BasicBlock *DefBB = I->getParent();
749 // If both result of the {s|z}xt and its source are live out, rewrite all
750 // other uses of the source with result of extension.
751 Value *Src = I->getOperand(0);
752 if (Src->hasOneUse())
755 // Only do this xform if truncating is free.
756 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
759 // Only safe to perform the optimization if the source is also defined in
761 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
764 bool DefIsLiveOut = false;
765 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
767 Instruction *User = cast<Instruction>(*UI);
769 // Figure out which BB this ext is used in.
770 BasicBlock *UserBB = User->getParent();
771 if (UserBB == DefBB) continue;
778 // Make sure non of the uses are PHI nodes.
779 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
781 Instruction *User = cast<Instruction>(*UI);
782 BasicBlock *UserBB = User->getParent();
783 if (UserBB == DefBB) continue;
784 // Be conservative. We don't want this xform to end up introducing
785 // reloads just before load / store instructions.
786 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
790 // InsertedTruncs - Only insert one trunc in each block once.
791 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
793 bool MadeChange = false;
794 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
796 Use &TheUse = UI.getUse();
797 Instruction *User = cast<Instruction>(*UI);
799 // Figure out which BB this ext is used in.
800 BasicBlock *UserBB = User->getParent();
801 if (UserBB == DefBB) continue;
803 // Both src and def are live in this block. Rewrite the use.
804 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
806 if (!InsertedTrunc) {
807 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
809 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
812 // Replace a use of the {s|z}ext source with a use of the result.
813 TheUse = InsertedTrunc;
821 // In this pass we look for GEP and cast instructions that are used
822 // across basic blocks and rewrite them to improve basic-block-at-a-time
824 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
825 bool MadeChange = false;
827 // Split all critical edges where the dest block has a PHI.
828 TerminatorInst *BBTI = BB.getTerminator();
829 if (BBTI->getNumSuccessors() > 1) {
830 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
831 BasicBlock *SuccBB = BBTI->getSuccessor(i);
832 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
833 SplitEdgeNicely(BBTI, i, BackEdges, this);
837 // Keep track of non-local addresses that have been sunk into this block.
838 // This allows us to avoid inserting duplicate code for blocks with multiple
839 // load/stores of the same address.
840 DenseMap<Value*, Value*> SunkAddrs;
842 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
843 Instruction *I = BBI++;
845 if (CastInst *CI = dyn_cast<CastInst>(I)) {
846 // If the source of the cast is a constant, then this should have
847 // already been constant folded. The only reason NOT to constant fold
848 // it is if something (e.g. LSR) was careful to place the constant
849 // evaluation in a block other than then one that uses it (e.g. to hoist
850 // the address of globals out of a loop). If this is the case, we don't
851 // want to forward-subst the cast.
852 if (isa<Constant>(CI->getOperand(0)))
857 Change = OptimizeNoopCopyExpression(CI, *TLI);
858 MadeChange |= Change;
861 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
862 MadeChange |= OptimizeExtUses(I);
863 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
864 MadeChange |= OptimizeCmpExpression(CI);
865 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
867 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
869 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
871 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
872 SI->getOperand(0)->getType(),
874 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
875 if (GEPI->hasAllZeroIndices()) {
876 /// The GEP operand must be a pointer, so must its result -> BitCast
877 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
878 GEPI->getName(), GEPI);
879 GEPI->replaceAllUsesWith(NC);
880 GEPI->eraseFromParent();
884 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
885 // If we found an inline asm expession, and if the target knows how to
886 // lower it to normal LLVM code, do so now.
887 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
888 if (const TargetAsmInfo *TAI =
889 TLI->getTargetMachine().getTargetAsmInfo()) {
890 if (TAI->ExpandInlineAsm(CI)) {
892 // Avoid processing instructions out of order, which could cause
893 // reuse before a value is defined.
896 // Sink address computing for memory operands into the block.
897 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);