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/Debug.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
38 /// TLI - Keep a pointer of a TargetLowering to consult for determining
39 /// transformation profitability.
40 const TargetLowering *TLI;
42 static char ID; // Pass identification, replacement for typeid
43 CodeGenPrepare(const TargetLowering *tli = 0) : FunctionPass((intptr_t)&ID),
45 bool runOnFunction(Function &F);
48 bool EliminateMostlyEmptyBlocks(Function &F);
49 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
50 void EliminateMostlyEmptyBlock(BasicBlock *BB);
51 bool OptimizeBlock(BasicBlock &BB);
52 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
54 DenseMap<Value*,Value*> &SunkAddrs);
58 char CodeGenPrepare::ID = 0;
59 static RegisterPass<CodeGenPrepare> X("codegenprepare",
60 "Optimize for code generation");
62 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
63 return new CodeGenPrepare(TLI);
67 bool CodeGenPrepare::runOnFunction(Function &F) {
68 bool EverMadeChange = false;
70 // First pass, eliminate blocks that contain only PHI nodes and an
71 // unconditional branch.
72 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
74 bool MadeChange = true;
77 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
78 MadeChange |= OptimizeBlock(*BB);
79 EverMadeChange |= MadeChange;
81 return EverMadeChange;
84 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
85 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
86 /// often split edges in ways that are non-optimal for isel. Start by
87 /// eliminating these blocks so we can split them the way we want them.
88 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
89 bool MadeChange = false;
90 // Note that this intentionally skips the entry block.
91 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
94 // If this block doesn't end with an uncond branch, ignore it.
95 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
96 if (!BI || !BI->isUnconditional())
99 // If the instruction before the branch isn't a phi node, then other stuff
100 // is happening here.
101 BasicBlock::iterator BBI = BI;
102 if (BBI != BB->begin()) {
104 if (!isa<PHINode>(BBI)) continue;
107 // Do not break infinite loops.
108 BasicBlock *DestBB = BI->getSuccessor(0);
112 if (!CanMergeBlocks(BB, DestBB))
115 EliminateMostlyEmptyBlock(BB);
121 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
122 /// single uncond branch between them, and BB contains no other non-phi
124 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
125 const BasicBlock *DestBB) const {
126 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
127 // the successor. If there are more complex condition (e.g. preheaders),
128 // don't mess around with them.
129 BasicBlock::const_iterator BBI = BB->begin();
130 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
131 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
133 const Instruction *User = cast<Instruction>(*UI);
134 if (User->getParent() != DestBB || !isa<PHINode>(User))
136 // If User is inside DestBB block and it is a PHINode then check
137 // incoming value. If incoming value is not from BB then this is
138 // a complex condition (e.g. preheaders) we want to avoid here.
139 if (User->getParent() == DestBB) {
140 if (const PHINode *UPN = dyn_cast<PHINode>(User))
141 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
142 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
143 if (Insn && Insn->getParent() == BB &&
144 Insn->getParent() != UPN->getIncomingBlock(I))
151 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
152 // and DestBB may have conflicting incoming values for the block. If so, we
153 // can't merge the block.
154 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
155 if (!DestBBPN) return true; // no conflict.
157 // Collect the preds of BB.
158 SmallPtrSet<BasicBlock*, 16> BBPreds;
159 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
160 // It is faster to get preds from a PHI than with pred_iterator.
161 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
162 BBPreds.insert(BBPN->getIncomingBlock(i));
164 BBPreds.insert(pred_begin(BB), pred_end(BB));
167 // Walk the preds of DestBB.
168 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
169 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
170 if (BBPreds.count(Pred)) { // Common predecessor?
171 BBI = DestBB->begin();
172 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
173 const Value *V1 = PN->getIncomingValueForBlock(Pred);
174 const Value *V2 = PN->getIncomingValueForBlock(BB);
176 // If V2 is a phi node in BB, look up what the mapped value will be.
177 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
178 if (V2PN->getParent() == BB)
179 V2 = V2PN->getIncomingValueForBlock(Pred);
181 // If there is a conflict, bail out.
182 if (V1 != V2) return false;
191 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
192 /// an unconditional branch in it.
193 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
194 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
195 BasicBlock *DestBB = BI->getSuccessor(0);
197 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
199 // If the destination block has a single pred, then this is a trivial edge,
201 if (DestBB->getSinglePredecessor()) {
202 // If DestBB has single-entry PHI nodes, fold them.
203 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
204 PN->replaceAllUsesWith(PN->getIncomingValue(0));
205 PN->eraseFromParent();
208 // Splice all the PHI nodes from BB over to DestBB.
209 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
212 // Anything that branched to BB now branches to DestBB.
213 BB->replaceAllUsesWith(DestBB);
216 BB->eraseFromParent();
218 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
222 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
223 // to handle the new incoming edges it is about to have.
225 for (BasicBlock::iterator BBI = DestBB->begin();
226 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
227 // Remove the incoming value for BB, and remember it.
228 Value *InVal = PN->removeIncomingValue(BB, false);
230 // Two options: either the InVal is a phi node defined in BB or it is some
231 // value that dominates BB.
232 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
233 if (InValPhi && InValPhi->getParent() == BB) {
234 // Add all of the input values of the input PHI as inputs of this phi.
235 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
236 PN->addIncoming(InValPhi->getIncomingValue(i),
237 InValPhi->getIncomingBlock(i));
239 // Otherwise, add one instance of the dominating value for each edge that
240 // we will be adding.
241 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
242 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
243 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
245 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
246 PN->addIncoming(InVal, *PI);
251 // The PHIs are now updated, change everything that refers to BB to use
252 // DestBB and remove BB.
253 BB->replaceAllUsesWith(DestBB);
254 BB->eraseFromParent();
256 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
260 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
261 /// successor if it will improve codegen. We only do this if the successor has
262 /// phi nodes (otherwise critical edges are ok). If there is already another
263 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
264 /// instead of introducing a new block.
265 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
266 BasicBlock *TIBB = TI->getParent();
267 BasicBlock *Dest = TI->getSuccessor(SuccNum);
268 assert(isa<PHINode>(Dest->begin()) &&
269 "This should only be called if Dest has a PHI!");
271 /// TIPHIValues - This array is lazily computed to determine the values of
272 /// PHIs in Dest that TI would provide.
273 std::vector<Value*> TIPHIValues;
275 // Check to see if Dest has any blocks that can be used as a split edge for
277 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
278 BasicBlock *Pred = *PI;
279 // To be usable, the pred has to end with an uncond branch to the dest.
280 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
281 if (!PredBr || !PredBr->isUnconditional() ||
282 // Must be empty other than the branch.
283 &Pred->front() != PredBr ||
284 // Cannot be the entry block; its label does not get emitted.
285 Pred == &(Dest->getParent()->getEntryBlock()))
288 // Finally, since we know that Dest has phi nodes in it, we have to make
289 // sure that jumping to Pred will have the same affect as going to Dest in
290 // terms of PHI values.
293 bool FoundMatch = true;
294 for (BasicBlock::iterator I = Dest->begin();
295 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
296 if (PHINo == TIPHIValues.size())
297 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
299 // If the PHI entry doesn't work, we can't use this pred.
300 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
306 // If we found a workable predecessor, change TI to branch to Succ.
308 Dest->removePredecessor(TIBB);
309 TI->setSuccessor(SuccNum, Pred);
314 SplitCriticalEdge(TI, SuccNum, P, true);
317 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
318 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
319 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
320 /// registers that must be created and coallesced.
322 /// Return true if any changes are made.
323 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
324 // If this is a noop copy,
325 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
326 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
328 // This is an fp<->int conversion?
329 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
332 // If this is an extension, it will be a zero or sign extension, which
334 if (SrcVT < DstVT) return false;
336 // If these values will be promoted, find out what they will be promoted
337 // to. This helps us consider truncates on PPC as noop copies when they
339 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
340 SrcVT = TLI.getTypeToTransformTo(SrcVT);
341 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
342 DstVT = TLI.getTypeToTransformTo(DstVT);
344 // If, after promotion, these are the same types, this is a noop copy.
348 BasicBlock *DefBB = CI->getParent();
350 /// InsertedCasts - Only insert a cast in each block once.
351 std::map<BasicBlock*, CastInst*> InsertedCasts;
353 bool MadeChange = false;
354 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
356 Use &TheUse = UI.getUse();
357 Instruction *User = cast<Instruction>(*UI);
359 // Figure out which BB this cast is used in. For PHI's this is the
360 // appropriate predecessor block.
361 BasicBlock *UserBB = User->getParent();
362 if (PHINode *PN = dyn_cast<PHINode>(User)) {
363 unsigned OpVal = UI.getOperandNo()/2;
364 UserBB = PN->getIncomingBlock(OpVal);
367 // Preincrement use iterator so we don't invalidate it.
370 // If this user is in the same block as the cast, don't change the cast.
371 if (UserBB == DefBB) continue;
373 // If we have already inserted a cast into this block, use it.
374 CastInst *&InsertedCast = InsertedCasts[UserBB];
377 BasicBlock::iterator InsertPt = UserBB->begin();
378 while (isa<PHINode>(InsertPt)) ++InsertPt;
381 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
386 // Replace a use of the cast with a use of the new casat.
387 TheUse = InsertedCast;
390 // If we removed all uses, nuke the cast.
392 CI->eraseFromParent();
397 /// EraseDeadInstructions - Erase any dead instructions
398 static void EraseDeadInstructions(Value *V) {
399 Instruction *I = dyn_cast<Instruction>(V);
400 if (!I || !I->use_empty()) return;
402 SmallPtrSet<Instruction*, 16> Insts;
405 while (!Insts.empty()) {
408 if (isInstructionTriviallyDead(I)) {
409 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
410 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
412 I->eraseFromParent();
418 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
419 /// holds actual Value*'s for register values.
420 struct ExtAddrMode : public TargetLowering::AddrMode {
423 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
427 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
428 bool NeedPlus = false;
431 OS << (NeedPlus ? " + " : "")
432 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
435 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
438 OS << (NeedPlus ? " + " : "")
439 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
441 OS << (NeedPlus ? " + " : "")
442 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
447 void ExtAddrMode::dump() const {
448 cerr << *this << "\n";
451 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
452 const Type *AccessTy, ExtAddrMode &AddrMode,
453 SmallVector<Instruction*, 16> &AddrModeInsts,
454 const TargetLowering &TLI, unsigned Depth);
456 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
457 /// Addr into the specified addressing mode. If Addr can't be added to AddrMode
458 /// this returns false. This assumes that Addr is either a pointer type or
459 /// intptr_t for the target.
460 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
461 ExtAddrMode &AddrMode,
462 SmallVector<Instruction*, 16> &AddrModeInsts,
463 const TargetLowering &TLI,
466 // If this is a global variable, fold it into the addressing mode if possible.
467 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
468 if (AddrMode.BaseGV == 0) {
469 AddrMode.BaseGV = GV;
470 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
474 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
475 AddrMode.BaseOffs += CI->getSExtValue();
476 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
478 AddrMode.BaseOffs -= CI->getSExtValue();
479 } else if (isa<ConstantPointerNull>(Addr)) {
483 // Look through constant exprs and instructions.
484 unsigned Opcode = ~0U;
486 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
487 Opcode = I->getOpcode();
489 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
490 Opcode = CE->getOpcode();
494 // Limit recursion to avoid exponential behavior.
495 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
497 // If this is really an instruction, add it to our list of related
499 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
500 AddrModeInsts.push_back(I);
503 case Instruction::PtrToInt:
504 // PtrToInt is always a noop, as we know that the int type is pointer sized.
505 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
506 AddrMode, AddrModeInsts, TLI, Depth))
509 case Instruction::IntToPtr:
510 // This inttoptr is a no-op if the integer type is pointer sized.
511 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
512 TLI.getPointerTy()) {
513 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
514 AddrMode, AddrModeInsts, TLI, Depth))
518 case Instruction::Add: {
519 // Check to see if we can merge in the RHS then the LHS. If so, we win.
520 ExtAddrMode BackupAddrMode = AddrMode;
521 unsigned OldSize = AddrModeInsts.size();
522 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
523 AddrMode, AddrModeInsts, TLI, Depth+1) &&
524 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
525 AddrMode, AddrModeInsts, TLI, Depth+1))
528 // Restore the old addr mode info.
529 AddrMode = BackupAddrMode;
530 AddrModeInsts.resize(OldSize);
532 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
533 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
534 AddrMode, AddrModeInsts, TLI, Depth+1) &&
535 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
536 AddrMode, AddrModeInsts, TLI, Depth+1))
539 // Otherwise we definitely can't merge the ADD in.
540 AddrMode = BackupAddrMode;
541 AddrModeInsts.resize(OldSize);
544 case Instruction::Or: {
545 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
547 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
550 case Instruction::Mul:
551 case Instruction::Shl: {
552 // Can only handle X*C and X << C, and can only handle this when the scale
553 // field is available.
554 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
556 int64_t Scale = RHS->getSExtValue();
557 if (Opcode == Instruction::Shl)
560 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
561 AddrMode, AddrModeInsts, TLI, Depth))
565 case Instruction::GetElementPtr: {
566 // Scan the GEP. We check it if it contains constant offsets and at most
567 // one variable offset.
568 int VariableOperand = -1;
569 unsigned VariableScale = 0;
571 int64_t ConstantOffset = 0;
572 const TargetData *TD = TLI.getTargetData();
573 gep_type_iterator GTI = gep_type_begin(AddrInst);
574 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
575 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
576 const StructLayout *SL = TD->getStructLayout(STy);
578 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
579 ConstantOffset += SL->getElementOffset(Idx);
581 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
582 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
583 ConstantOffset += CI->getSExtValue()*TypeSize;
584 } else if (TypeSize) { // Scales of zero don't do anything.
585 // We only allow one variable index at the moment.
586 if (VariableOperand != -1) {
587 VariableOperand = -2;
591 // Remember the variable index.
593 VariableScale = TypeSize;
598 // If the GEP had multiple variable indices, punt.
599 if (VariableOperand == -2)
602 // A common case is for the GEP to only do a constant offset. In this case,
603 // just add it to the disp field and check validity.
604 if (VariableOperand == -1) {
605 AddrMode.BaseOffs += ConstantOffset;
606 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
607 // Check to see if we can fold the base pointer in too.
608 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
609 AddrMode, AddrModeInsts, TLI,
613 AddrMode.BaseOffs -= ConstantOffset;
615 // Check that this has no base reg yet. If so, we won't have a place to
616 // put the base of the GEP (assuming it is not a null ptr).
617 bool SetBaseReg = false;
618 if (AddrMode.HasBaseReg) {
619 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
622 AddrMode.HasBaseReg = true;
623 AddrMode.BaseReg = AddrInst->getOperand(0);
627 // See if the scale amount is valid for this target.
628 AddrMode.BaseOffs += ConstantOffset;
629 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
630 VariableScale, AccessTy, AddrMode,
631 AddrModeInsts, TLI, Depth)) {
632 if (!SetBaseReg) return true;
634 // If this match succeeded, we know that we can form an address with the
635 // GepBase as the basereg. See if we can match *more*.
636 AddrMode.HasBaseReg = false;
637 AddrMode.BaseReg = 0;
638 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
639 AddrMode, AddrModeInsts, TLI,
642 // Strange, shouldn't happen. Restore the base reg and succeed the easy
644 AddrMode.HasBaseReg = true;
645 AddrMode.BaseReg = AddrInst->getOperand(0);
649 AddrMode.BaseOffs -= ConstantOffset;
651 AddrMode.HasBaseReg = false;
652 AddrMode.BaseReg = 0;
659 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
660 assert(AddrModeInsts.back() == I && "Stack imbalance");
661 AddrModeInsts.pop_back();
664 // Worse case, the target should support [reg] addressing modes. :)
665 if (!AddrMode.HasBaseReg) {
666 AddrMode.HasBaseReg = true;
667 // Still check for legality in case the target supports [imm] but not [i+r].
668 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
669 AddrMode.BaseReg = Addr;
672 AddrMode.HasBaseReg = false;
675 // If the base register is already taken, see if we can do [r+r].
676 if (AddrMode.Scale == 0) {
678 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
679 AddrMode.ScaledReg = Addr;
688 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
689 /// addressing mode. Return true if this addr mode is legal for the target,
691 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
692 const Type *AccessTy, ExtAddrMode &AddrMode,
693 SmallVector<Instruction*, 16> &AddrModeInsts,
694 const TargetLowering &TLI, unsigned Depth) {
695 // If we already have a scale of this value, we can add to it, otherwise, we
696 // need an available scale field.
697 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
700 ExtAddrMode InputAddrMode = AddrMode;
702 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
703 // [A+B + A*7] -> [B+A*8].
704 AddrMode.Scale += Scale;
705 AddrMode.ScaledReg = ScaleReg;
707 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
708 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
709 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
710 // X*Scale + C*Scale to addr mode.
711 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
712 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
713 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
715 InputAddrMode.Scale = Scale;
716 InputAddrMode.ScaledReg = BinOp->getOperand(0);
717 InputAddrMode.BaseOffs +=
718 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
719 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
720 AddrModeInsts.push_back(BinOp);
721 AddrMode = InputAddrMode;
726 // Otherwise, not (x+c)*scale, just return what we have.
730 // Otherwise, back this attempt out.
731 AddrMode.Scale -= Scale;
732 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
738 /// IsNonLocalValue - Return true if the specified values are defined in a
739 /// different basic block than BB.
740 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
741 if (Instruction *I = dyn_cast<Instruction>(V))
742 return I->getParent() != BB;
746 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
747 /// addressing modes that can do significant amounts of computation. As such,
748 /// instruction selection will try to get the load or store to do as much
749 /// computation as possible for the program. The problem is that isel can only
750 /// see within a single block. As such, we sink as much legal addressing mode
751 /// stuff into the block as possible.
752 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
753 const Type *AccessTy,
754 DenseMap<Value*,Value*> &SunkAddrs) {
755 // Figure out what addressing mode will be built up for this operation.
756 SmallVector<Instruction*, 16> AddrModeInsts;
757 ExtAddrMode AddrMode;
758 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
759 AddrModeInsts, *TLI, 0);
760 Success = Success; assert(Success && "Couldn't select *anything*?");
762 // Check to see if any of the instructions supersumed by this addr mode are
763 // non-local to I's BB.
764 bool AnyNonLocal = false;
765 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
766 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
772 // If all the instructions matched are already in this BB, don't do anything.
774 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
778 // Insert this computation right after this user. Since our caller is
779 // scanning from the top of the BB to the bottom, reuse of the expr are
780 // guaranteed to happen later.
781 BasicBlock::iterator InsertPt = LdStInst;
783 // Now that we determined the addressing expression we want to use and know
784 // that we have to sink it into this block. Check to see if we have already
785 // done this for some other load/store instr in this block. If so, reuse the
787 Value *&SunkAddr = SunkAddrs[Addr];
789 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
790 if (SunkAddr->getType() != Addr->getType())
791 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
793 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
794 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
797 // Start with the scale value.
798 if (AddrMode.Scale) {
799 Value *V = AddrMode.ScaledReg;
800 if (V->getType() == IntPtrTy) {
802 } else if (isa<PointerType>(V->getType())) {
803 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
804 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
805 cast<IntegerType>(V->getType())->getBitWidth()) {
806 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
808 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
810 if (AddrMode.Scale != 1)
811 V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
813 "sunkaddr", InsertPt);
817 // Add in the base register.
818 if (AddrMode.BaseReg) {
819 Value *V = AddrMode.BaseReg;
820 if (V->getType() != IntPtrTy)
821 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
823 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
828 // Add in the BaseGV if present.
829 if (AddrMode.BaseGV) {
830 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
833 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
838 // Add in the Base Offset if present.
839 if (AddrMode.BaseOffs) {
840 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
842 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
848 SunkAddr = Constant::getNullValue(Addr->getType());
850 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
853 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
855 if (Addr->use_empty())
856 EraseDeadInstructions(Addr);
860 // In this pass we look for GEP and cast instructions that are used
861 // across basic blocks and rewrite them to improve basic-block-at-a-time
863 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
864 bool MadeChange = false;
866 // Split all critical edges where the dest block has a PHI and where the phi
867 // has shared immediate operands.
868 TerminatorInst *BBTI = BB.getTerminator();
869 if (BBTI->getNumSuccessors() > 1) {
870 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
871 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
872 isCriticalEdge(BBTI, i, true))
873 SplitEdgeNicely(BBTI, i, this);
877 // Keep track of non-local addresses that have been sunk into this block.
878 // This allows us to avoid inserting duplicate code for blocks with multiple
879 // load/stores of the same address.
880 DenseMap<Value*, Value*> SunkAddrs;
882 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
883 Instruction *I = BBI++;
885 if (CastInst *CI = dyn_cast<CastInst>(I)) {
886 // If the source of the cast is a constant, then this should have
887 // already been constant folded. The only reason NOT to constant fold
888 // it is if something (e.g. LSR) was careful to place the constant
889 // evaluation in a block other than then one that uses it (e.g. to hoist
890 // the address of globals out of a loop). If this is the case, we don't
891 // want to forward-subst the cast.
892 if (isa<Constant>(CI->getOperand(0)))
896 MadeChange |= OptimizeNoopCopyExpression(CI, *TLI);
897 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
899 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
901 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
903 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
904 SI->getOperand(0)->getType(),
906 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
907 if (GEPI->hasAllZeroIndices()) {
908 /// The GEP operand must be a pointer, so must its result -> BitCast
909 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
910 GEPI->getName(), GEPI);
911 GEPI->replaceAllUsesWith(NC);
912 GEPI->eraseFromParent();
916 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
917 // If we found an inline asm expession, and if the target knows how to
918 // lower it to normal LLVM code, do so now.
919 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
920 if (const TargetAsmInfo *TAI =
921 TLI->getTargetMachine().getTargetAsmInfo()) {
922 if (TAI->ExpandInlineAsm(CI))