1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 cl::opt<bool> OptExtUses("optimize-ext-uses",
39 cl::init(true), cl::Hidden);
43 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
44 /// TLI - Keep a pointer of a TargetLowering to consult for determining
45 /// transformation profitability.
46 const TargetLowering *TLI;
48 static char ID; // Pass identification, replacement for typeid
49 explicit CodeGenPrepare(const TargetLowering *tli = 0)
50 : FunctionPass((intptr_t)&ID), TLI(tli) {}
51 bool runOnFunction(Function &F);
54 bool EliminateMostlyEmptyBlocks(Function &F);
55 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
56 void EliminateMostlyEmptyBlock(BasicBlock *BB);
57 bool OptimizeBlock(BasicBlock &BB);
58 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
60 DenseMap<Value*,Value*> &SunkAddrs);
61 bool OptimizeExtUses(Instruction *I);
65 char CodeGenPrepare::ID = 0;
66 static RegisterPass<CodeGenPrepare> X("codegenprepare",
67 "Optimize for code generation");
69 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
70 return new CodeGenPrepare(TLI);
74 bool CodeGenPrepare::runOnFunction(Function &F) {
75 bool EverMadeChange = false;
77 // First pass, eliminate blocks that contain only PHI nodes and an
78 // unconditional branch.
79 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
81 bool MadeChange = true;
84 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
85 MadeChange |= OptimizeBlock(*BB);
86 EverMadeChange |= MadeChange;
88 return EverMadeChange;
91 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
92 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
93 /// often split edges in ways that are non-optimal for isel. Start by
94 /// eliminating these blocks so we can split them the way we want them.
95 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
96 bool MadeChange = false;
97 // Note that this intentionally skips the entry block.
98 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
101 // If this block doesn't end with an uncond branch, ignore it.
102 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
103 if (!BI || !BI->isUnconditional())
106 // If the instruction before the branch isn't a phi node, then other stuff
107 // is happening here.
108 BasicBlock::iterator BBI = BI;
109 if (BBI != BB->begin()) {
111 if (!isa<PHINode>(BBI)) continue;
114 // Do not break infinite loops.
115 BasicBlock *DestBB = BI->getSuccessor(0);
119 if (!CanMergeBlocks(BB, DestBB))
122 EliminateMostlyEmptyBlock(BB);
128 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
129 /// single uncond branch between them, and BB contains no other non-phi
131 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
132 const BasicBlock *DestBB) const {
133 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
134 // the successor. If there are more complex condition (e.g. preheaders),
135 // don't mess around with them.
136 BasicBlock::const_iterator BBI = BB->begin();
137 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
138 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
140 const Instruction *User = cast<Instruction>(*UI);
141 if (User->getParent() != DestBB || !isa<PHINode>(User))
143 // If User is inside DestBB block and it is a PHINode then check
144 // incoming value. If incoming value is not from BB then this is
145 // a complex condition (e.g. preheaders) we want to avoid here.
146 if (User->getParent() == DestBB) {
147 if (const PHINode *UPN = dyn_cast<PHINode>(User))
148 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
149 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
150 if (Insn && Insn->getParent() == BB &&
151 Insn->getParent() != UPN->getIncomingBlock(I))
158 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
159 // and DestBB may have conflicting incoming values for the block. If so, we
160 // can't merge the block.
161 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
162 if (!DestBBPN) return true; // no conflict.
164 // Collect the preds of BB.
165 SmallPtrSet<const BasicBlock*, 16> BBPreds;
166 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
167 // It is faster to get preds from a PHI than with pred_iterator.
168 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
169 BBPreds.insert(BBPN->getIncomingBlock(i));
171 BBPreds.insert(pred_begin(BB), pred_end(BB));
174 // Walk the preds of DestBB.
175 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
176 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
177 if (BBPreds.count(Pred)) { // Common predecessor?
178 BBI = DestBB->begin();
179 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
180 const Value *V1 = PN->getIncomingValueForBlock(Pred);
181 const Value *V2 = PN->getIncomingValueForBlock(BB);
183 // If V2 is a phi node in BB, look up what the mapped value will be.
184 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
185 if (V2PN->getParent() == BB)
186 V2 = V2PN->getIncomingValueForBlock(Pred);
188 // If there is a conflict, bail out.
189 if (V1 != V2) return false;
198 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
199 /// an unconditional branch in it.
200 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
201 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
202 BasicBlock *DestBB = BI->getSuccessor(0);
204 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
206 // If the destination block has a single pred, then this is a trivial edge,
208 if (DestBB->getSinglePredecessor()) {
209 // If DestBB has single-entry PHI nodes, fold them.
210 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
211 PN->replaceAllUsesWith(PN->getIncomingValue(0));
212 PN->eraseFromParent();
215 // Splice all the PHI nodes from BB over to DestBB.
216 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
219 // Anything that branched to BB now branches to DestBB.
220 BB->replaceAllUsesWith(DestBB);
223 BB->eraseFromParent();
225 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
229 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
230 // to handle the new incoming edges it is about to have.
232 for (BasicBlock::iterator BBI = DestBB->begin();
233 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
234 // Remove the incoming value for BB, and remember it.
235 Value *InVal = PN->removeIncomingValue(BB, false);
237 // Two options: either the InVal is a phi node defined in BB or it is some
238 // value that dominates BB.
239 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
240 if (InValPhi && InValPhi->getParent() == BB) {
241 // Add all of the input values of the input PHI as inputs of this phi.
242 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
243 PN->addIncoming(InValPhi->getIncomingValue(i),
244 InValPhi->getIncomingBlock(i));
246 // Otherwise, add one instance of the dominating value for each edge that
247 // we will be adding.
248 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
249 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
250 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
252 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
253 PN->addIncoming(InVal, *PI);
258 // The PHIs are now updated, change everything that refers to BB to use
259 // DestBB and remove BB.
260 BB->replaceAllUsesWith(DestBB);
261 BB->eraseFromParent();
263 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
267 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
268 /// successor if it will improve codegen. We only do this if the successor has
269 /// phi nodes (otherwise critical edges are ok). If there is already another
270 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
271 /// instead of introducing a new block.
272 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
273 BasicBlock *TIBB = TI->getParent();
274 BasicBlock *Dest = TI->getSuccessor(SuccNum);
275 assert(isa<PHINode>(Dest->begin()) &&
276 "This should only be called if Dest has a PHI!");
278 /// TIPHIValues - This array is lazily computed to determine the values of
279 /// PHIs in Dest that TI would provide.
280 std::vector<Value*> TIPHIValues;
282 // Check to see if Dest has any blocks that can be used as a split edge for
284 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
285 BasicBlock *Pred = *PI;
286 // To be usable, the pred has to end with an uncond branch to the dest.
287 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
288 if (!PredBr || !PredBr->isUnconditional() ||
289 // Must be empty other than the branch.
290 &Pred->front() != PredBr ||
291 // Cannot be the entry block; its label does not get emitted.
292 Pred == &(Dest->getParent()->getEntryBlock()))
295 // Finally, since we know that Dest has phi nodes in it, we have to make
296 // sure that jumping to Pred will have the same affect as going to Dest in
297 // terms of PHI values.
300 bool FoundMatch = true;
301 for (BasicBlock::iterator I = Dest->begin();
302 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
303 if (PHINo == TIPHIValues.size())
304 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
306 // If the PHI entry doesn't work, we can't use this pred.
307 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
313 // If we found a workable predecessor, change TI to branch to Succ.
315 Dest->removePredecessor(TIBB);
316 TI->setSuccessor(SuccNum, Pred);
321 SplitCriticalEdge(TI, SuccNum, P, true);
324 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
325 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
326 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
327 /// registers that must be created and coalesced.
329 /// Return true if any changes are made.
330 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
331 // If this is a noop copy,
332 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
333 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
335 // This is an fp<->int conversion?
336 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
339 // If this is an extension, it will be a zero or sign extension, which
341 if (SrcVT < DstVT) return false;
343 // If these values will be promoted, find out what they will be promoted
344 // to. This helps us consider truncates on PPC as noop copies when they
346 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
347 SrcVT = TLI.getTypeToTransformTo(SrcVT);
348 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
349 DstVT = TLI.getTypeToTransformTo(DstVT);
351 // If, after promotion, these are the same types, this is a noop copy.
355 BasicBlock *DefBB = CI->getParent();
357 /// InsertedCasts - Only insert a cast in each block once.
358 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
360 bool MadeChange = false;
361 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
363 Use &TheUse = UI.getUse();
364 Instruction *User = cast<Instruction>(*UI);
366 // Figure out which BB this cast is used in. For PHI's this is the
367 // appropriate predecessor block.
368 BasicBlock *UserBB = User->getParent();
369 if (PHINode *PN = dyn_cast<PHINode>(User)) {
370 unsigned OpVal = UI.getOperandNo()/2;
371 UserBB = PN->getIncomingBlock(OpVal);
374 // Preincrement use iterator so we don't invalidate it.
377 // If this user is in the same block as the cast, don't change the cast.
378 if (UserBB == DefBB) continue;
380 // If we have already inserted a cast into this block, use it.
381 CastInst *&InsertedCast = InsertedCasts[UserBB];
384 BasicBlock::iterator InsertPt = UserBB->begin();
385 while (isa<PHINode>(InsertPt)) ++InsertPt;
388 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
393 // Replace a use of the cast with a use of the new cast.
394 TheUse = InsertedCast;
397 // If we removed all uses, nuke the cast.
399 CI->eraseFromParent();
404 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
405 /// the number of virtual registers that must be created and coalesced. This is
406 /// a clear win except on targets with multiple condition code registers
407 /// (PowerPC), where it might lose; some adjustment may be wanted there.
409 /// Return true if any changes are made.
410 static bool OptimizeCmpExpression(CmpInst *CI){
412 BasicBlock *DefBB = CI->getParent();
414 /// InsertedCmp - Only insert a cmp in each block once.
415 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
417 bool MadeChange = false;
418 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
420 Use &TheUse = UI.getUse();
421 Instruction *User = cast<Instruction>(*UI);
423 // Preincrement use iterator so we don't invalidate it.
426 // Don't bother for PHI nodes.
427 if (isa<PHINode>(User))
430 // Figure out which BB this cmp is used in.
431 BasicBlock *UserBB = User->getParent();
433 // If this user is in the same block as the cmp, don't change the cmp.
434 if (UserBB == DefBB) continue;
436 // If we have already inserted a cmp into this block, use it.
437 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
440 BasicBlock::iterator InsertPt = UserBB->begin();
441 while (isa<PHINode>(InsertPt)) ++InsertPt;
444 CmpInst::create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
445 CI->getOperand(1), "", InsertPt);
449 // Replace a use of the cmp with a use of the new cmp.
450 TheUse = InsertedCmp;
453 // If we removed all uses, nuke the cmp.
455 CI->eraseFromParent();
460 /// EraseDeadInstructions - Erase any dead instructions
461 static void EraseDeadInstructions(Value *V) {
462 Instruction *I = dyn_cast<Instruction>(V);
463 if (!I || !I->use_empty()) return;
465 SmallPtrSet<Instruction*, 16> Insts;
468 while (!Insts.empty()) {
471 if (isInstructionTriviallyDead(I)) {
472 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
473 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
475 I->eraseFromParent();
481 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
482 /// holds actual Value*'s for register values.
483 struct ExtAddrMode : public TargetLowering::AddrMode {
486 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
490 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
491 bool NeedPlus = false;
494 OS << (NeedPlus ? " + " : "")
495 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
498 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
501 OS << (NeedPlus ? " + " : "")
502 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
504 OS << (NeedPlus ? " + " : "")
505 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
510 void ExtAddrMode::dump() const {
511 cerr << *this << "\n";
514 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
515 const Type *AccessTy, ExtAddrMode &AddrMode,
516 SmallVector<Instruction*, 16> &AddrModeInsts,
517 const TargetLowering &TLI, unsigned Depth);
519 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
520 /// Addr into the specified addressing mode. If Addr can't be added to AddrMode
521 /// this returns false. This assumes that Addr is either a pointer type or
522 /// intptr_t for the target.
523 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
524 ExtAddrMode &AddrMode,
525 SmallVector<Instruction*, 16> &AddrModeInsts,
526 const TargetLowering &TLI,
529 // If this is a global variable, fold it into the addressing mode if possible.
530 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
531 if (AddrMode.BaseGV == 0) {
532 AddrMode.BaseGV = GV;
533 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
537 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
538 AddrMode.BaseOffs += CI->getSExtValue();
539 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
541 AddrMode.BaseOffs -= CI->getSExtValue();
542 } else if (isa<ConstantPointerNull>(Addr)) {
546 // Look through constant exprs and instructions.
547 unsigned Opcode = ~0U;
549 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
550 Opcode = I->getOpcode();
552 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
553 Opcode = CE->getOpcode();
557 // Limit recursion to avoid exponential behavior.
558 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
560 // If this is really an instruction, add it to our list of related
562 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
563 AddrModeInsts.push_back(I);
566 case Instruction::PtrToInt:
567 // PtrToInt is always a noop, as we know that the int type is pointer sized.
568 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
569 AddrMode, AddrModeInsts, TLI, Depth))
572 case Instruction::IntToPtr:
573 // This inttoptr is a no-op if the integer type is pointer sized.
574 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
575 TLI.getPointerTy()) {
576 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
577 AddrMode, AddrModeInsts, TLI, Depth))
581 case Instruction::Add: {
582 // Check to see if we can merge in the RHS then the LHS. If so, we win.
583 ExtAddrMode BackupAddrMode = AddrMode;
584 unsigned OldSize = AddrModeInsts.size();
585 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
586 AddrMode, AddrModeInsts, TLI, Depth+1) &&
587 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
588 AddrMode, AddrModeInsts, TLI, Depth+1))
591 // Restore the old addr mode info.
592 AddrMode = BackupAddrMode;
593 AddrModeInsts.resize(OldSize);
595 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
596 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
597 AddrMode, AddrModeInsts, TLI, Depth+1) &&
598 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
599 AddrMode, AddrModeInsts, TLI, Depth+1))
602 // Otherwise we definitely can't merge the ADD in.
603 AddrMode = BackupAddrMode;
604 AddrModeInsts.resize(OldSize);
607 case Instruction::Or: {
608 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
610 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
613 case Instruction::Mul:
614 case Instruction::Shl: {
615 // Can only handle X*C and X << C, and can only handle this when the scale
616 // field is available.
617 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
619 int64_t Scale = RHS->getSExtValue();
620 if (Opcode == Instruction::Shl)
623 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
624 AddrMode, AddrModeInsts, TLI, Depth))
628 case Instruction::GetElementPtr: {
629 // Scan the GEP. We check it if it contains constant offsets and at most
630 // one variable offset.
631 int VariableOperand = -1;
632 unsigned VariableScale = 0;
634 int64_t ConstantOffset = 0;
635 const TargetData *TD = TLI.getTargetData();
636 gep_type_iterator GTI = gep_type_begin(AddrInst);
637 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
638 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
639 const StructLayout *SL = TD->getStructLayout(STy);
641 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
642 ConstantOffset += SL->getElementOffset(Idx);
644 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
645 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
646 ConstantOffset += CI->getSExtValue()*TypeSize;
647 } else if (TypeSize) { // Scales of zero don't do anything.
648 // We only allow one variable index at the moment.
649 if (VariableOperand != -1) {
650 VariableOperand = -2;
654 // Remember the variable index.
656 VariableScale = TypeSize;
661 // If the GEP had multiple variable indices, punt.
662 if (VariableOperand == -2)
665 // A common case is for the GEP to only do a constant offset. In this case,
666 // just add it to the disp field and check validity.
667 if (VariableOperand == -1) {
668 AddrMode.BaseOffs += ConstantOffset;
669 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
670 // Check to see if we can fold the base pointer in too.
671 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
672 AddrMode, AddrModeInsts, TLI,
676 AddrMode.BaseOffs -= ConstantOffset;
678 // Check that this has no base reg yet. If so, we won't have a place to
679 // put the base of the GEP (assuming it is not a null ptr).
680 bool SetBaseReg = false;
681 if (AddrMode.HasBaseReg) {
682 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
685 AddrMode.HasBaseReg = true;
686 AddrMode.BaseReg = AddrInst->getOperand(0);
690 // See if the scale amount is valid for this target.
691 AddrMode.BaseOffs += ConstantOffset;
692 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
693 VariableScale, AccessTy, AddrMode,
694 AddrModeInsts, TLI, Depth)) {
695 if (!SetBaseReg) return true;
697 // If this match succeeded, we know that we can form an address with the
698 // GepBase as the basereg. See if we can match *more*.
699 AddrMode.HasBaseReg = false;
700 AddrMode.BaseReg = 0;
701 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
702 AddrMode, AddrModeInsts, TLI,
705 // Strange, shouldn't happen. Restore the base reg and succeed the easy
707 AddrMode.HasBaseReg = true;
708 AddrMode.BaseReg = AddrInst->getOperand(0);
712 AddrMode.BaseOffs -= ConstantOffset;
714 AddrMode.HasBaseReg = false;
715 AddrMode.BaseReg = 0;
722 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
723 assert(AddrModeInsts.back() == I && "Stack imbalance");
724 AddrModeInsts.pop_back();
727 // Worse case, the target should support [reg] addressing modes. :)
728 if (!AddrMode.HasBaseReg) {
729 AddrMode.HasBaseReg = true;
730 // Still check for legality in case the target supports [imm] but not [i+r].
731 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
732 AddrMode.BaseReg = Addr;
735 AddrMode.HasBaseReg = false;
738 // If the base register is already taken, see if we can do [r+r].
739 if (AddrMode.Scale == 0) {
741 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
742 AddrMode.ScaledReg = Addr;
751 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
752 /// addressing mode. Return true if this addr mode is legal for the target,
754 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
755 const Type *AccessTy, ExtAddrMode &AddrMode,
756 SmallVector<Instruction*, 16> &AddrModeInsts,
757 const TargetLowering &TLI, unsigned Depth) {
758 // If we already have a scale of this value, we can add to it, otherwise, we
759 // need an available scale field.
760 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
763 ExtAddrMode InputAddrMode = AddrMode;
765 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
766 // [A+B + A*7] -> [B+A*8].
767 AddrMode.Scale += Scale;
768 AddrMode.ScaledReg = ScaleReg;
770 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
771 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
772 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
773 // X*Scale + C*Scale to addr mode.
774 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
775 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
776 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
778 InputAddrMode.Scale = Scale;
779 InputAddrMode.ScaledReg = BinOp->getOperand(0);
780 InputAddrMode.BaseOffs +=
781 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
782 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
783 AddrModeInsts.push_back(BinOp);
784 AddrMode = InputAddrMode;
789 // Otherwise, not (x+c)*scale, just return what we have.
793 // Otherwise, back this attempt out.
794 AddrMode.Scale -= Scale;
795 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
801 /// IsNonLocalValue - Return true if the specified values are defined in a
802 /// different basic block than BB.
803 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
804 if (Instruction *I = dyn_cast<Instruction>(V))
805 return I->getParent() != BB;
809 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
810 /// addressing modes that can do significant amounts of computation. As such,
811 /// instruction selection will try to get the load or store to do as much
812 /// computation as possible for the program. The problem is that isel can only
813 /// see within a single block. As such, we sink as much legal addressing mode
814 /// stuff into the block as possible.
815 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
816 const Type *AccessTy,
817 DenseMap<Value*,Value*> &SunkAddrs) {
818 // Figure out what addressing mode will be built up for this operation.
819 SmallVector<Instruction*, 16> AddrModeInsts;
820 ExtAddrMode AddrMode;
821 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
822 AddrModeInsts, *TLI, 0);
823 Success = Success; assert(Success && "Couldn't select *anything*?");
825 // Check to see if any of the instructions supersumed by this addr mode are
826 // non-local to I's BB.
827 bool AnyNonLocal = false;
828 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
829 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
835 // If all the instructions matched are already in this BB, don't do anything.
837 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
841 // Insert this computation right after this user. Since our caller is
842 // scanning from the top of the BB to the bottom, reuse of the expr are
843 // guaranteed to happen later.
844 BasicBlock::iterator InsertPt = LdStInst;
846 // Now that we determined the addressing expression we want to use and know
847 // that we have to sink it into this block. Check to see if we have already
848 // done this for some other load/store instr in this block. If so, reuse the
850 Value *&SunkAddr = SunkAddrs[Addr];
852 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
853 if (SunkAddr->getType() != Addr->getType())
854 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
856 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
857 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
860 // Start with the scale value.
861 if (AddrMode.Scale) {
862 Value *V = AddrMode.ScaledReg;
863 if (V->getType() == IntPtrTy) {
865 } else if (isa<PointerType>(V->getType())) {
866 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
867 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
868 cast<IntegerType>(V->getType())->getBitWidth()) {
869 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
871 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
873 if (AddrMode.Scale != 1)
874 V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
876 "sunkaddr", InsertPt);
880 // Add in the base register.
881 if (AddrMode.BaseReg) {
882 Value *V = AddrMode.BaseReg;
883 if (V->getType() != IntPtrTy)
884 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
886 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
891 // Add in the BaseGV if present.
892 if (AddrMode.BaseGV) {
893 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
896 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
901 // Add in the Base Offset if present.
902 if (AddrMode.BaseOffs) {
903 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
905 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
911 SunkAddr = Constant::getNullValue(Addr->getType());
913 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
916 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
918 if (Addr->use_empty())
919 EraseDeadInstructions(Addr);
923 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
924 BasicBlock *DefBB = I->getParent();
926 // If both result of the {s|z}xt and its source are live out, rewrite all
927 // other uses of the source with result of extension.
928 Value *Src = I->getOperand(0);
929 if (Src->hasOneUse())
932 // Only do this xform if truncating is free.
933 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
936 // Only safe to perform the optimization if the source is also defined in
938 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
941 bool DefIsLiveOut = false;
942 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
944 Instruction *User = cast<Instruction>(*UI);
946 // Figure out which BB this ext is used in.
947 BasicBlock *UserBB = User->getParent();
948 if (UserBB == DefBB) continue;
955 // Make sure non of the uses are PHI nodes.
956 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
958 Instruction *User = cast<Instruction>(*UI);
959 BasicBlock *UserBB = User->getParent();
960 if (UserBB == DefBB) continue;
961 // Be conservative. We don't want this xform to end up introducing
962 // reloads just before load / store instructions.
963 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
967 // InsertedTruncs - Only insert one trunc in each block once.
968 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
970 bool MadeChange = false;
971 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
973 Use &TheUse = UI.getUse();
974 Instruction *User = cast<Instruction>(*UI);
976 // Figure out which BB this ext is used in.
977 BasicBlock *UserBB = User->getParent();
978 if (UserBB == DefBB) continue;
980 // Both src and def are live in this block. Rewrite the use.
981 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
983 if (!InsertedTrunc) {
984 BasicBlock::iterator InsertPt = UserBB->begin();
985 while (isa<PHINode>(InsertPt)) ++InsertPt;
987 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
990 // Replace a use of the {s|z}ext source with a use of the result.
991 TheUse = InsertedTrunc;
999 // In this pass we look for GEP and cast instructions that are used
1000 // across basic blocks and rewrite them to improve basic-block-at-a-time
1002 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1003 bool MadeChange = false;
1005 // Split all critical edges where the dest block has a PHI and where the phi
1006 // has shared immediate operands.
1007 TerminatorInst *BBTI = BB.getTerminator();
1008 if (BBTI->getNumSuccessors() > 1) {
1009 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1010 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1011 isCriticalEdge(BBTI, i, true))
1012 SplitEdgeNicely(BBTI, i, this);
1016 // Keep track of non-local addresses that have been sunk into this block.
1017 // This allows us to avoid inserting duplicate code for blocks with multiple
1018 // load/stores of the same address.
1019 DenseMap<Value*, Value*> SunkAddrs;
1021 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1022 Instruction *I = BBI++;
1024 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1025 // If the source of the cast is a constant, then this should have
1026 // already been constant folded. The only reason NOT to constant fold
1027 // it is if something (e.g. LSR) was careful to place the constant
1028 // evaluation in a block other than then one that uses it (e.g. to hoist
1029 // the address of globals out of a loop). If this is the case, we don't
1030 // want to forward-subst the cast.
1031 if (isa<Constant>(CI->getOperand(0)))
1034 bool Change = false;
1036 Change = OptimizeNoopCopyExpression(CI, *TLI);
1037 MadeChange |= Change;
1040 if (OptExtUses && !Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1041 MadeChange |= OptimizeExtUses(I);
1042 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1043 MadeChange |= OptimizeCmpExpression(CI);
1044 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1046 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1048 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1050 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1051 SI->getOperand(0)->getType(),
1053 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1054 if (GEPI->hasAllZeroIndices()) {
1055 /// The GEP operand must be a pointer, so must its result -> BitCast
1056 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1057 GEPI->getName(), GEPI);
1058 GEPI->replaceAllUsesWith(NC);
1059 GEPI->eraseFromParent();
1063 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1064 // If we found an inline asm expession, and if the target knows how to
1065 // lower it to normal LLVM code, do so now.
1066 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1067 if (const TargetAsmInfo *TAI =
1068 TLI->getTargetMachine().getTargetAsmInfo()) {
1069 if (TAI->ExpandInlineAsm(CI))