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/Pass.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 cl::opt<bool> OptExtUses("optimize-ext-uses",
41 cl::init(true), cl::Hidden);
45 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
46 /// TLI - Keep a pointer of a TargetLowering to consult for determining
47 /// transformation profitability.
48 const TargetLowering *TLI;
50 static char ID; // Pass identification, replacement for typeid
51 explicit CodeGenPrepare(const TargetLowering *tli = 0)
52 : FunctionPass((intptr_t)&ID), TLI(tli) {}
53 bool runOnFunction(Function &F);
56 bool EliminateMostlyEmptyBlocks(Function &F);
57 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
58 void EliminateMostlyEmptyBlock(BasicBlock *BB);
59 bool OptimizeBlock(BasicBlock &BB);
60 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
62 DenseMap<Value*,Value*> &SunkAddrs);
63 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
64 DenseMap<Value*,Value*> &SunkAddrs);
65 bool OptimizeExtUses(Instruction *I);
69 char CodeGenPrepare::ID = 0;
70 static RegisterPass<CodeGenPrepare> X("codegenprepare",
71 "Optimize for code generation");
73 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
74 return new CodeGenPrepare(TLI);
78 bool CodeGenPrepare::runOnFunction(Function &F) {
79 bool EverMadeChange = false;
81 // First pass, eliminate blocks that contain only PHI nodes and an
82 // unconditional branch.
83 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
85 bool MadeChange = true;
88 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
89 MadeChange |= OptimizeBlock(*BB);
90 EverMadeChange |= MadeChange;
92 return EverMadeChange;
95 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
96 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
97 /// often split edges in ways that are non-optimal for isel. Start by
98 /// eliminating these blocks so we can split them the way we want them.
99 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
100 bool MadeChange = false;
101 // Note that this intentionally skips the entry block.
102 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
103 BasicBlock *BB = I++;
105 // If this block doesn't end with an uncond branch, ignore it.
106 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
107 if (!BI || !BI->isUnconditional())
110 // If the instruction before the branch isn't a phi node, then other stuff
111 // is happening here.
112 BasicBlock::iterator BBI = BI;
113 if (BBI != BB->begin()) {
115 if (!isa<PHINode>(BBI)) continue;
118 // Do not break infinite loops.
119 BasicBlock *DestBB = BI->getSuccessor(0);
123 if (!CanMergeBlocks(BB, DestBB))
126 EliminateMostlyEmptyBlock(BB);
132 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
133 /// single uncond branch between them, and BB contains no other non-phi
135 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
136 const BasicBlock *DestBB) const {
137 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
138 // the successor. If there are more complex condition (e.g. preheaders),
139 // don't mess around with them.
140 BasicBlock::const_iterator BBI = BB->begin();
141 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
142 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
144 const Instruction *User = cast<Instruction>(*UI);
145 if (User->getParent() != DestBB || !isa<PHINode>(User))
147 // If User is inside DestBB block and it is a PHINode then check
148 // incoming value. If incoming value is not from BB then this is
149 // a complex condition (e.g. preheaders) we want to avoid here.
150 if (User->getParent() == DestBB) {
151 if (const PHINode *UPN = dyn_cast<PHINode>(User))
152 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
153 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
154 if (Insn && Insn->getParent() == BB &&
155 Insn->getParent() != UPN->getIncomingBlock(I))
162 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
163 // and DestBB may have conflicting incoming values for the block. If so, we
164 // can't merge the block.
165 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
166 if (!DestBBPN) return true; // no conflict.
168 // Collect the preds of BB.
169 SmallPtrSet<const BasicBlock*, 16> BBPreds;
170 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
171 // It is faster to get preds from a PHI than with pred_iterator.
172 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
173 BBPreds.insert(BBPN->getIncomingBlock(i));
175 BBPreds.insert(pred_begin(BB), pred_end(BB));
178 // Walk the preds of DestBB.
179 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
180 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
181 if (BBPreds.count(Pred)) { // Common predecessor?
182 BBI = DestBB->begin();
183 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
184 const Value *V1 = PN->getIncomingValueForBlock(Pred);
185 const Value *V2 = PN->getIncomingValueForBlock(BB);
187 // If V2 is a phi node in BB, look up what the mapped value will be.
188 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
189 if (V2PN->getParent() == BB)
190 V2 = V2PN->getIncomingValueForBlock(Pred);
192 // If there is a conflict, bail out.
193 if (V1 != V2) return false;
202 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
203 /// an unconditional branch in it.
204 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
205 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
206 BasicBlock *DestBB = BI->getSuccessor(0);
208 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
210 // If the destination block has a single pred, then this is a trivial edge,
212 if (DestBB->getSinglePredecessor()) {
213 // If DestBB has single-entry PHI nodes, fold them.
214 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
215 PN->replaceAllUsesWith(PN->getIncomingValue(0));
216 PN->eraseFromParent();
219 // Splice all the PHI nodes from BB over to DestBB.
220 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
223 // Anything that branched to BB now branches to DestBB.
224 BB->replaceAllUsesWith(DestBB);
227 BB->eraseFromParent();
229 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
233 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
234 // to handle the new incoming edges it is about to have.
236 for (BasicBlock::iterator BBI = DestBB->begin();
237 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
238 // Remove the incoming value for BB, and remember it.
239 Value *InVal = PN->removeIncomingValue(BB, false);
241 // Two options: either the InVal is a phi node defined in BB or it is some
242 // value that dominates BB.
243 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
244 if (InValPhi && InValPhi->getParent() == BB) {
245 // Add all of the input values of the input PHI as inputs of this phi.
246 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
247 PN->addIncoming(InValPhi->getIncomingValue(i),
248 InValPhi->getIncomingBlock(i));
250 // Otherwise, add one instance of the dominating value for each edge that
251 // we will be adding.
252 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
253 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
254 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
256 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
257 PN->addIncoming(InVal, *PI);
262 // The PHIs are now updated, change everything that refers to BB to use
263 // DestBB and remove BB.
264 BB->replaceAllUsesWith(DestBB);
265 BB->eraseFromParent();
267 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
271 /// SplitEdgeNicely - Split the critical edge from TI to its specified
272 /// successor if it will improve codegen. We only do this if the successor has
273 /// phi nodes (otherwise critical edges are ok). If there is already another
274 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
275 /// instead of introducing a new block.
276 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
277 BasicBlock *TIBB = TI->getParent();
278 BasicBlock *Dest = TI->getSuccessor(SuccNum);
279 assert(isa<PHINode>(Dest->begin()) &&
280 "This should only be called if Dest has a PHI!");
282 // As a hack, never split backedges of loops. Even though the copy for any
283 // PHIs inserted on the backedge would be dead for exits from the loop, we
284 // assume that the cost of *splitting* the backedge would be too high.
288 /// TIPHIValues - This array is lazily computed to determine the values of
289 /// PHIs in Dest that TI would provide.
290 SmallVector<Value*, 32> TIPHIValues;
292 // Check to see if Dest has any blocks that can be used as a split edge for
294 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
295 BasicBlock *Pred = *PI;
296 // To be usable, the pred has to end with an uncond branch to the dest.
297 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
298 if (!PredBr || !PredBr->isUnconditional() ||
299 // Must be empty other than the branch.
300 &Pred->front() != PredBr ||
301 // Cannot be the entry block; its label does not get emitted.
302 Pred == &(Dest->getParent()->getEntryBlock()))
305 // Finally, since we know that Dest has phi nodes in it, we have to make
306 // sure that jumping to Pred will have the same affect as going to Dest in
307 // terms of PHI values.
310 bool FoundMatch = true;
311 for (BasicBlock::iterator I = Dest->begin();
312 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
313 if (PHINo == TIPHIValues.size())
314 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
316 // If the PHI entry doesn't work, we can't use this pred.
317 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
323 // If we found a workable predecessor, change TI to branch to Succ.
325 Dest->removePredecessor(TIBB);
326 TI->setSuccessor(SuccNum, Pred);
331 SplitCriticalEdge(TI, SuccNum, P, true);
334 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
335 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
336 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
337 /// registers that must be created and coalesced.
339 /// Return true if any changes are made.
340 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
341 // If this is a noop copy,
342 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
343 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
345 // This is an fp<->int conversion?
346 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
349 // If this is an extension, it will be a zero or sign extension, which
351 if (SrcVT < DstVT) return false;
353 // If these values will be promoted, find out what they will be promoted
354 // to. This helps us consider truncates on PPC as noop copies when they
356 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
357 SrcVT = TLI.getTypeToTransformTo(SrcVT);
358 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
359 DstVT = TLI.getTypeToTransformTo(DstVT);
361 // If, after promotion, these are the same types, this is a noop copy.
365 BasicBlock *DefBB = CI->getParent();
367 /// InsertedCasts - Only insert a cast in each block once.
368 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
370 bool MadeChange = false;
371 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
373 Use &TheUse = UI.getUse();
374 Instruction *User = cast<Instruction>(*UI);
376 // Figure out which BB this cast is used in. For PHI's this is the
377 // appropriate predecessor block.
378 BasicBlock *UserBB = User->getParent();
379 if (PHINode *PN = dyn_cast<PHINode>(User)) {
380 unsigned OpVal = UI.getOperandNo()/2;
381 UserBB = PN->getIncomingBlock(OpVal);
384 // Preincrement use iterator so we don't invalidate it.
387 // If this user is in the same block as the cast, don't change the cast.
388 if (UserBB == DefBB) continue;
390 // If we have already inserted a cast into this block, use it.
391 CastInst *&InsertedCast = InsertedCasts[UserBB];
394 BasicBlock::iterator InsertPt = UserBB->begin();
395 while (isa<PHINode>(InsertPt)) ++InsertPt;
398 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
403 // Replace a use of the cast with a use of the new cast.
404 TheUse = InsertedCast;
407 // If we removed all uses, nuke the cast.
408 if (CI->use_empty()) {
409 CI->eraseFromParent();
416 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
417 /// the number of virtual registers that must be created and coalesced. This is
418 /// a clear win except on targets with multiple condition code registers
419 /// (PowerPC), where it might lose; some adjustment may be wanted there.
421 /// Return true if any changes are made.
422 static bool OptimizeCmpExpression(CmpInst *CI){
424 BasicBlock *DefBB = CI->getParent();
426 /// InsertedCmp - Only insert a cmp in each block once.
427 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
429 bool MadeChange = false;
430 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
432 Use &TheUse = UI.getUse();
433 Instruction *User = cast<Instruction>(*UI);
435 // Preincrement use iterator so we don't invalidate it.
438 // Don't bother for PHI nodes.
439 if (isa<PHINode>(User))
442 // Figure out which BB this cmp is used in.
443 BasicBlock *UserBB = User->getParent();
445 // If this user is in the same block as the cmp, don't change the cmp.
446 if (UserBB == DefBB) continue;
448 // If we have already inserted a cmp into this block, use it.
449 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
452 BasicBlock::iterator InsertPt = UserBB->begin();
453 while (isa<PHINode>(InsertPt)) ++InsertPt;
456 CmpInst::create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
457 CI->getOperand(1), "", InsertPt);
461 // Replace a use of the cmp with a use of the new cmp.
462 TheUse = InsertedCmp;
465 // If we removed all uses, nuke the cmp.
467 CI->eraseFromParent();
472 /// EraseDeadInstructions - Erase any dead instructions
473 static void EraseDeadInstructions(Value *V) {
474 Instruction *I = dyn_cast<Instruction>(V);
475 if (!I || !I->use_empty()) return;
477 SmallPtrSet<Instruction*, 16> Insts;
480 while (!Insts.empty()) {
483 if (isInstructionTriviallyDead(I)) {
484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
485 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
487 I->eraseFromParent();
493 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
494 /// holds actual Value*'s for register values.
495 struct ExtAddrMode : public TargetLowering::AddrMode {
498 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
502 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
503 bool NeedPlus = false;
506 OS << (NeedPlus ? " + " : "")
507 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
510 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
513 OS << (NeedPlus ? " + " : "")
514 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
516 OS << (NeedPlus ? " + " : "")
517 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
522 void ExtAddrMode::dump() const {
523 cerr << *this << "\n";
526 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
527 const Type *AccessTy, ExtAddrMode &AddrMode,
528 SmallVector<Instruction*, 16> &AddrModeInsts,
529 const TargetLowering &TLI, unsigned Depth);
531 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
532 /// Addr into the specified addressing mode. If Addr can't be added to AddrMode
533 /// this returns false. This assumes that Addr is either a pointer type or
534 /// intptr_t for the target.
535 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
536 ExtAddrMode &AddrMode,
537 SmallVector<Instruction*, 16> &AddrModeInsts,
538 const TargetLowering &TLI,
541 // If this is a global variable, fold it into the addressing mode if possible.
542 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
543 if (AddrMode.BaseGV == 0) {
544 AddrMode.BaseGV = GV;
545 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
549 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
550 AddrMode.BaseOffs += CI->getSExtValue();
551 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
553 AddrMode.BaseOffs -= CI->getSExtValue();
554 } else if (isa<ConstantPointerNull>(Addr)) {
558 // Look through constant exprs and instructions.
559 unsigned Opcode = ~0U;
561 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
562 Opcode = I->getOpcode();
564 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
565 Opcode = CE->getOpcode();
569 // Limit recursion to avoid exponential behavior.
570 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
572 // If this is really an instruction, add it to our list of related
574 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
575 AddrModeInsts.push_back(I);
578 case Instruction::PtrToInt:
579 // PtrToInt is always a noop, as we know that the int type is pointer sized.
580 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
581 AddrMode, AddrModeInsts, TLI, Depth))
584 case Instruction::IntToPtr:
585 // This inttoptr is a no-op if the integer type is pointer sized.
586 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
587 TLI.getPointerTy()) {
588 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
589 AddrMode, AddrModeInsts, TLI, Depth))
593 case Instruction::Add: {
594 // Check to see if we can merge in the RHS then the LHS. If so, we win.
595 ExtAddrMode BackupAddrMode = AddrMode;
596 unsigned OldSize = AddrModeInsts.size();
597 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
598 AddrMode, AddrModeInsts, TLI, Depth+1) &&
599 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
600 AddrMode, AddrModeInsts, TLI, Depth+1))
603 // Restore the old addr mode info.
604 AddrMode = BackupAddrMode;
605 AddrModeInsts.resize(OldSize);
607 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
608 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
609 AddrMode, AddrModeInsts, TLI, Depth+1) &&
610 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
611 AddrMode, AddrModeInsts, TLI, Depth+1))
614 // Otherwise we definitely can't merge the ADD in.
615 AddrMode = BackupAddrMode;
616 AddrModeInsts.resize(OldSize);
619 case Instruction::Or: {
620 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
622 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
625 case Instruction::Mul:
626 case Instruction::Shl: {
627 // Can only handle X*C and X << C, and can only handle this when the scale
628 // field is available.
629 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
631 int64_t Scale = RHS->getSExtValue();
632 if (Opcode == Instruction::Shl)
635 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
636 AddrMode, AddrModeInsts, TLI, Depth))
640 case Instruction::GetElementPtr: {
641 // Scan the GEP. We check it if it contains constant offsets and at most
642 // one variable offset.
643 int VariableOperand = -1;
644 unsigned VariableScale = 0;
646 int64_t ConstantOffset = 0;
647 const TargetData *TD = TLI.getTargetData();
648 gep_type_iterator GTI = gep_type_begin(AddrInst);
649 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
650 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
651 const StructLayout *SL = TD->getStructLayout(STy);
653 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
654 ConstantOffset += SL->getElementOffset(Idx);
656 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
657 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
658 ConstantOffset += CI->getSExtValue()*TypeSize;
659 } else if (TypeSize) { // Scales of zero don't do anything.
660 // We only allow one variable index at the moment.
661 if (VariableOperand != -1) {
662 VariableOperand = -2;
666 // Remember the variable index.
668 VariableScale = TypeSize;
673 // If the GEP had multiple variable indices, punt.
674 if (VariableOperand == -2)
677 // A common case is for the GEP to only do a constant offset. In this case,
678 // just add it to the disp field and check validity.
679 if (VariableOperand == -1) {
680 AddrMode.BaseOffs += ConstantOffset;
681 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
682 // Check to see if we can fold the base pointer in too.
683 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
684 AddrMode, AddrModeInsts, TLI,
688 AddrMode.BaseOffs -= ConstantOffset;
690 // Check that this has no base reg yet. If so, we won't have a place to
691 // put the base of the GEP (assuming it is not a null ptr).
692 bool SetBaseReg = false;
693 if (AddrMode.HasBaseReg) {
694 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
697 AddrMode.HasBaseReg = true;
698 AddrMode.BaseReg = AddrInst->getOperand(0);
702 // See if the scale amount is valid for this target.
703 AddrMode.BaseOffs += ConstantOffset;
704 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
705 VariableScale, AccessTy, AddrMode,
706 AddrModeInsts, TLI, Depth)) {
707 if (!SetBaseReg) return true;
709 // If this match succeeded, we know that we can form an address with the
710 // GepBase as the basereg. See if we can match *more*.
711 AddrMode.HasBaseReg = false;
712 AddrMode.BaseReg = 0;
713 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
714 AddrMode, AddrModeInsts, TLI,
717 // Strange, shouldn't happen. Restore the base reg and succeed the easy
719 AddrMode.HasBaseReg = true;
720 AddrMode.BaseReg = AddrInst->getOperand(0);
724 AddrMode.BaseOffs -= ConstantOffset;
726 AddrMode.HasBaseReg = false;
727 AddrMode.BaseReg = 0;
734 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
735 assert(AddrModeInsts.back() == I && "Stack imbalance");
736 AddrModeInsts.pop_back();
739 // Worse case, the target should support [reg] addressing modes. :)
740 if (!AddrMode.HasBaseReg) {
741 AddrMode.HasBaseReg = true;
742 // Still check for legality in case the target supports [imm] but not [i+r].
743 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
744 AddrMode.BaseReg = Addr;
747 AddrMode.HasBaseReg = false;
750 // If the base register is already taken, see if we can do [r+r].
751 if (AddrMode.Scale == 0) {
753 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
754 AddrMode.ScaledReg = Addr;
763 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
764 /// addressing mode. Return true if this addr mode is legal for the target,
766 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
767 const Type *AccessTy, ExtAddrMode &AddrMode,
768 SmallVector<Instruction*, 16> &AddrModeInsts,
769 const TargetLowering &TLI, unsigned Depth) {
770 // If we already have a scale of this value, we can add to it, otherwise, we
771 // need an available scale field.
772 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
775 ExtAddrMode InputAddrMode = AddrMode;
777 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
778 // [A+B + A*7] -> [B+A*8].
779 AddrMode.Scale += Scale;
780 AddrMode.ScaledReg = ScaleReg;
782 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
783 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
784 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
785 // X*Scale + C*Scale to addr mode.
786 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
787 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
788 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
790 InputAddrMode.Scale = Scale;
791 InputAddrMode.ScaledReg = BinOp->getOperand(0);
792 InputAddrMode.BaseOffs +=
793 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
794 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
795 AddrModeInsts.push_back(BinOp);
796 AddrMode = InputAddrMode;
801 // Otherwise, not (x+c)*scale, just return what we have.
805 // Otherwise, back this attempt out.
806 AddrMode.Scale -= Scale;
807 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
813 /// IsNonLocalValue - Return true if the specified values are defined in a
814 /// different basic block than BB.
815 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
816 if (Instruction *I = dyn_cast<Instruction>(V))
817 return I->getParent() != BB;
821 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
822 /// addressing modes that can do significant amounts of computation. As such,
823 /// instruction selection will try to get the load or store to do as much
824 /// computation as possible for the program. The problem is that isel can only
825 /// see within a single block. As such, we sink as much legal addressing mode
826 /// stuff into the block as possible.
827 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
828 const Type *AccessTy,
829 DenseMap<Value*,Value*> &SunkAddrs) {
830 // Figure out what addressing mode will be built up for this operation.
831 SmallVector<Instruction*, 16> AddrModeInsts;
832 ExtAddrMode AddrMode;
833 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
834 AddrModeInsts, *TLI, 0);
835 Success = Success; assert(Success && "Couldn't select *anything*?");
837 // Check to see if any of the instructions supersumed by this addr mode are
838 // non-local to I's BB.
839 bool AnyNonLocal = false;
840 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
841 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
847 // If all the instructions matched are already in this BB, don't do anything.
849 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
853 // Insert this computation right after this user. Since our caller is
854 // scanning from the top of the BB to the bottom, reuse of the expr are
855 // guaranteed to happen later.
856 BasicBlock::iterator InsertPt = LdStInst;
858 // Now that we determined the addressing expression we want to use and know
859 // that we have to sink it into this block. Check to see if we have already
860 // done this for some other load/store instr in this block. If so, reuse the
862 Value *&SunkAddr = SunkAddrs[Addr];
864 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
865 if (SunkAddr->getType() != Addr->getType())
866 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
868 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
869 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
872 // Start with the scale value.
873 if (AddrMode.Scale) {
874 Value *V = AddrMode.ScaledReg;
875 if (V->getType() == IntPtrTy) {
877 } else if (isa<PointerType>(V->getType())) {
878 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
879 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
880 cast<IntegerType>(V->getType())->getBitWidth()) {
881 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
883 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
885 if (AddrMode.Scale != 1)
886 V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
888 "sunkaddr", InsertPt);
892 // Add in the base register.
893 if (AddrMode.BaseReg) {
894 Value *V = AddrMode.BaseReg;
895 if (V->getType() != IntPtrTy)
896 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
898 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
903 // Add in the BaseGV if present.
904 if (AddrMode.BaseGV) {
905 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
908 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
913 // Add in the Base Offset if present.
914 if (AddrMode.BaseOffs) {
915 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
917 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
923 SunkAddr = Constant::getNullValue(Addr->getType());
925 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
928 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
930 if (Addr->use_empty())
931 EraseDeadInstructions(Addr);
935 /// OptimizeInlineAsmInst - If there are any memory operands, use
936 /// OptimizeLoadStoreInt to sink their address computing into the block when
937 /// possible / profitable.
938 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
939 DenseMap<Value*,Value*> &SunkAddrs) {
940 bool MadeChange = false;
941 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
943 // Do a prepass over the constraints, canonicalizing them, and building up the
944 // ConstraintOperands list.
945 std::vector<InlineAsm::ConstraintInfo>
946 ConstraintInfos = IA->ParseConstraints();
948 /// ConstraintOperands - Information about all of the constraints.
949 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
950 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
951 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
953 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
954 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
956 // Compute the value type for each operand.
957 switch (OpInfo.Type) {
958 case InlineAsm::isOutput:
959 if (OpInfo.isIndirect)
960 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
962 case InlineAsm::isInput:
963 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
965 case InlineAsm::isClobber:
970 // Compute the constraint code and ConstraintType to use.
971 OpInfo.ComputeConstraintToUse(*TLI);
973 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
974 Value *OpVal = OpInfo.CallOperandVal;
975 MadeChange |= OptimizeLoadStoreInst(I, OpVal, OpVal->getType(),
983 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
984 BasicBlock *DefBB = I->getParent();
986 // If both result of the {s|z}xt and its source are live out, rewrite all
987 // other uses of the source with result of extension.
988 Value *Src = I->getOperand(0);
989 if (Src->hasOneUse())
992 // Only do this xform if truncating is free.
993 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
996 // Only safe to perform the optimization if the source is also defined in
998 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1001 bool DefIsLiveOut = false;
1002 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1004 Instruction *User = cast<Instruction>(*UI);
1006 // Figure out which BB this ext is used in.
1007 BasicBlock *UserBB = User->getParent();
1008 if (UserBB == DefBB) continue;
1009 DefIsLiveOut = true;
1015 // Make sure non of the uses are PHI nodes.
1016 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1018 Instruction *User = cast<Instruction>(*UI);
1019 BasicBlock *UserBB = User->getParent();
1020 if (UserBB == DefBB) continue;
1021 // Be conservative. We don't want this xform to end up introducing
1022 // reloads just before load / store instructions.
1023 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1027 // InsertedTruncs - Only insert one trunc in each block once.
1028 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1030 bool MadeChange = false;
1031 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1033 Use &TheUse = UI.getUse();
1034 Instruction *User = cast<Instruction>(*UI);
1036 // Figure out which BB this ext is used in.
1037 BasicBlock *UserBB = User->getParent();
1038 if (UserBB == DefBB) continue;
1040 // Both src and def are live in this block. Rewrite the use.
1041 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1043 if (!InsertedTrunc) {
1044 BasicBlock::iterator InsertPt = UserBB->begin();
1045 while (isa<PHINode>(InsertPt)) ++InsertPt;
1047 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1050 // Replace a use of the {s|z}ext source with a use of the result.
1051 TheUse = InsertedTrunc;
1059 // In this pass we look for GEP and cast instructions that are used
1060 // across basic blocks and rewrite them to improve basic-block-at-a-time
1062 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1063 bool MadeChange = false;
1065 // Split all critical edges where the dest block has a PHI and where the phi
1066 // has shared immediate operands.
1067 TerminatorInst *BBTI = BB.getTerminator();
1068 if (BBTI->getNumSuccessors() > 1) {
1069 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1070 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1071 isCriticalEdge(BBTI, i, true))
1072 SplitEdgeNicely(BBTI, i, this);
1076 // Keep track of non-local addresses that have been sunk into this block.
1077 // This allows us to avoid inserting duplicate code for blocks with multiple
1078 // load/stores of the same address.
1079 DenseMap<Value*, Value*> SunkAddrs;
1081 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1082 Instruction *I = BBI++;
1084 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1085 // If the source of the cast is a constant, then this should have
1086 // already been constant folded. The only reason NOT to constant fold
1087 // it is if something (e.g. LSR) was careful to place the constant
1088 // evaluation in a block other than then one that uses it (e.g. to hoist
1089 // the address of globals out of a loop). If this is the case, we don't
1090 // want to forward-subst the cast.
1091 if (isa<Constant>(CI->getOperand(0)))
1094 bool Change = false;
1096 Change = OptimizeNoopCopyExpression(CI, *TLI);
1097 MadeChange |= Change;
1100 if (OptExtUses && !Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1101 MadeChange |= OptimizeExtUses(I);
1102 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1103 MadeChange |= OptimizeCmpExpression(CI);
1104 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1106 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1108 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1110 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1111 SI->getOperand(0)->getType(),
1113 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1114 if (GEPI->hasAllZeroIndices()) {
1115 /// The GEP operand must be a pointer, so must its result -> BitCast
1116 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1117 GEPI->getName(), GEPI);
1118 GEPI->replaceAllUsesWith(NC);
1119 GEPI->eraseFromParent();
1123 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1124 // If we found an inline asm expession, and if the target knows how to
1125 // lower it to normal LLVM code, do so now.
1126 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1127 if (const TargetAsmInfo *TAI =
1128 TLI->getTargetMachine().getTargetAsmInfo()) {
1129 if (TAI->ExpandInlineAsm(CI))
1132 // Sink address computing for memory operands into the block.
1133 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);