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/CodeGen/Passes.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/IR/ValueMap.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/BuildLibCalls.h"
45 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
46 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm::PatternMatch;
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
59 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
64 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
66 static cl::opt<bool> DisableBranchOpts(
67 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
68 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70 static cl::opt<bool> DisableSelectToBranch(
71 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
72 cl::desc("Disable select to branch conversion."));
74 static cl::opt<bool> AddrSinkUsingGEPs(
75 "addr-sink-using-gep", cl::Hidden, cl::init(false),
76 cl::desc("Address sinking in CGP using GEPs."));
78 static cl::opt<bool> EnableAndCmpSinking(
79 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
80 cl::desc("Enable sinkinig and/cmp into branches."));
83 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
84 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
86 class CodeGenPrepare : public FunctionPass {
87 /// TLI - Keep a pointer of a TargetLowering to consult for determining
88 /// transformation profitability.
89 const TargetMachine *TM;
90 const TargetLowering *TLI;
91 const TargetLibraryInfo *TLInfo;
94 /// CurInstIterator - As we scan instructions optimizing them, this is the
95 /// next instruction to optimize. Xforms that can invalidate this should
97 BasicBlock::iterator CurInstIterator;
99 /// Keeps track of non-local addresses that have been sunk into a block.
100 /// This allows us to avoid inserting duplicate code for blocks with
101 /// multiple load/stores of the same address.
102 ValueMap<Value*, Value*> SunkAddrs;
104 /// Keeps track of all truncates inserted for the current function.
105 SetOfInstrs InsertedTruncsSet;
106 /// Keeps track of the type of the related instruction before their
107 /// promotion for the current function.
108 InstrToOrigTy PromotedInsts;
110 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
114 /// OptSize - True if optimizing for size.
118 static char ID; // Pass identification, replacement for typeid
119 explicit CodeGenPrepare(const TargetMachine *TM = 0)
120 : FunctionPass(ID), TM(TM), TLI(0) {
121 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
123 bool runOnFunction(Function &F) override;
125 const char *getPassName() const override { return "CodeGen Prepare"; }
127 void getAnalysisUsage(AnalysisUsage &AU) const override {
128 AU.addPreserved<DominatorTreeWrapperPass>();
129 AU.addRequired<TargetLibraryInfo>();
133 bool EliminateFallThrough(Function &F);
134 bool EliminateMostlyEmptyBlocks(Function &F);
135 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
136 void EliminateMostlyEmptyBlock(BasicBlock *BB);
137 bool OptimizeBlock(BasicBlock &BB);
138 bool OptimizeInst(Instruction *I);
139 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
140 bool OptimizeInlineAsmInst(CallInst *CS);
141 bool OptimizeCallInst(CallInst *CI);
142 bool MoveExtToFormExtLoad(Instruction *I);
143 bool OptimizeExtUses(Instruction *I);
144 bool OptimizeSelectInst(SelectInst *SI);
145 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
146 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
147 bool PlaceDbgValues(Function &F);
148 bool sinkAndCmp(Function &F);
152 char CodeGenPrepare::ID = 0;
153 static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
154 initializeTargetLibraryInfoPass(Registry);
155 PassInfo *PI = new PassInfo(
156 "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
157 PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
158 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
159 Registry.registerPass(*PI, true);
163 void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
164 CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
167 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
168 return new CodeGenPrepare(TM);
171 bool CodeGenPrepare::runOnFunction(Function &F) {
172 if (skipOptnoneFunction(F))
175 bool EverMadeChange = false;
176 // Clear per function information.
177 InsertedTruncsSet.clear();
178 PromotedInsts.clear();
181 if (TM) TLI = TM->getTargetLowering();
182 TLInfo = &getAnalysis<TargetLibraryInfo>();
183 DominatorTreeWrapperPass *DTWP =
184 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
185 DT = DTWP ? &DTWP->getDomTree() : 0;
186 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
187 Attribute::OptimizeForSize);
189 /// This optimization identifies DIV instructions that can be
190 /// profitably bypassed and carried out with a shorter, faster divide.
191 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
192 const DenseMap<unsigned int, unsigned int> &BypassWidths =
193 TLI->getBypassSlowDivWidths();
194 for (Function::iterator I = F.begin(); I != F.end(); I++)
195 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
198 // Eliminate blocks that contain only PHI nodes and an
199 // unconditional branch.
200 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
202 // llvm.dbg.value is far away from the value then iSel may not be able
203 // handle it properly. iSel will drop llvm.dbg.value if it can not
204 // find a node corresponding to the value.
205 EverMadeChange |= PlaceDbgValues(F);
207 // If there is a mask, compare against zero, and branch that can be combined
208 // into a single target instruction, push the mask and compare into branch
209 // users. Do this before OptimizeBlock -> OptimizeInst ->
210 // OptimizeCmpExpression, which perturbs the pattern being searched for.
211 if (!DisableBranchOpts)
212 EverMadeChange |= sinkAndCmp(F);
214 bool MadeChange = true;
217 for (Function::iterator I = F.begin(); I != F.end(); ) {
218 BasicBlock *BB = I++;
219 MadeChange |= OptimizeBlock(*BB);
221 EverMadeChange |= MadeChange;
226 if (!DisableBranchOpts) {
228 SmallPtrSet<BasicBlock*, 8> WorkList;
229 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
230 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
231 MadeChange |= ConstantFoldTerminator(BB, true);
232 if (!MadeChange) continue;
234 for (SmallVectorImpl<BasicBlock*>::iterator
235 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
236 if (pred_begin(*II) == pred_end(*II))
237 WorkList.insert(*II);
240 // Delete the dead blocks and any of their dead successors.
241 MadeChange |= !WorkList.empty();
242 while (!WorkList.empty()) {
243 BasicBlock *BB = *WorkList.begin();
245 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
249 for (SmallVectorImpl<BasicBlock*>::iterator
250 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
251 if (pred_begin(*II) == pred_end(*II))
252 WorkList.insert(*II);
255 // Merge pairs of basic blocks with unconditional branches, connected by
257 if (EverMadeChange || MadeChange)
258 MadeChange |= EliminateFallThrough(F);
262 EverMadeChange |= MadeChange;
265 if (ModifiedDT && DT)
268 return EverMadeChange;
271 /// EliminateFallThrough - Merge basic blocks which are connected
272 /// by a single edge, where one of the basic blocks has a single successor
273 /// pointing to the other basic block, which has a single predecessor.
274 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
275 bool Changed = false;
276 // Scan all of the blocks in the function, except for the entry block.
277 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
278 BasicBlock *BB = I++;
279 // If the destination block has a single pred, then this is a trivial
280 // edge, just collapse it.
281 BasicBlock *SinglePred = BB->getSinglePredecessor();
283 // Don't merge if BB's address is taken.
284 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
286 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
287 if (Term && !Term->isConditional()) {
289 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
290 // Remember if SinglePred was the entry block of the function.
291 // If so, we will need to move BB back to the entry position.
292 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
293 MergeBasicBlockIntoOnlyPred(BB, this);
295 if (isEntry && BB != &BB->getParent()->getEntryBlock())
296 BB->moveBefore(&BB->getParent()->getEntryBlock());
298 // We have erased a block. Update the iterator.
305 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
306 /// debug info directives, and an unconditional branch. Passes before isel
307 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
308 /// isel. Start by eliminating these blocks so we can split them the way we
310 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
311 bool MadeChange = false;
312 // Note that this intentionally skips the entry block.
313 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
314 BasicBlock *BB = I++;
316 // If this block doesn't end with an uncond branch, ignore it.
317 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
318 if (!BI || !BI->isUnconditional())
321 // If the instruction before the branch (skipping debug info) isn't a phi
322 // node, then other stuff is happening here.
323 BasicBlock::iterator BBI = BI;
324 if (BBI != BB->begin()) {
326 while (isa<DbgInfoIntrinsic>(BBI)) {
327 if (BBI == BB->begin())
331 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
335 // Do not break infinite loops.
336 BasicBlock *DestBB = BI->getSuccessor(0);
340 if (!CanMergeBlocks(BB, DestBB))
343 EliminateMostlyEmptyBlock(BB);
349 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
350 /// single uncond branch between them, and BB contains no other non-phi
352 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
353 const BasicBlock *DestBB) const {
354 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
355 // the successor. If there are more complex condition (e.g. preheaders),
356 // don't mess around with them.
357 BasicBlock::const_iterator BBI = BB->begin();
358 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
359 for (const User *U : PN->users()) {
360 const Instruction *UI = cast<Instruction>(U);
361 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
363 // If User is inside DestBB block and it is a PHINode then check
364 // incoming value. If incoming value is not from BB then this is
365 // a complex condition (e.g. preheaders) we want to avoid here.
366 if (UI->getParent() == DestBB) {
367 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
368 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
369 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
370 if (Insn && Insn->getParent() == BB &&
371 Insn->getParent() != UPN->getIncomingBlock(I))
378 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
379 // and DestBB may have conflicting incoming values for the block. If so, we
380 // can't merge the block.
381 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
382 if (!DestBBPN) return true; // no conflict.
384 // Collect the preds of BB.
385 SmallPtrSet<const BasicBlock*, 16> BBPreds;
386 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
387 // It is faster to get preds from a PHI than with pred_iterator.
388 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
389 BBPreds.insert(BBPN->getIncomingBlock(i));
391 BBPreds.insert(pred_begin(BB), pred_end(BB));
394 // Walk the preds of DestBB.
395 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
396 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
397 if (BBPreds.count(Pred)) { // Common predecessor?
398 BBI = DestBB->begin();
399 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
400 const Value *V1 = PN->getIncomingValueForBlock(Pred);
401 const Value *V2 = PN->getIncomingValueForBlock(BB);
403 // If V2 is a phi node in BB, look up what the mapped value will be.
404 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
405 if (V2PN->getParent() == BB)
406 V2 = V2PN->getIncomingValueForBlock(Pred);
408 // If there is a conflict, bail out.
409 if (V1 != V2) return false;
418 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
419 /// an unconditional branch in it.
420 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
421 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
422 BasicBlock *DestBB = BI->getSuccessor(0);
424 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
426 // If the destination block has a single pred, then this is a trivial edge,
428 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
429 if (SinglePred != DestBB) {
430 // Remember if SinglePred was the entry block of the function. If so, we
431 // will need to move BB back to the entry position.
432 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
433 MergeBasicBlockIntoOnlyPred(DestBB, this);
435 if (isEntry && BB != &BB->getParent()->getEntryBlock())
436 BB->moveBefore(&BB->getParent()->getEntryBlock());
438 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
443 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
444 // to handle the new incoming edges it is about to have.
446 for (BasicBlock::iterator BBI = DestBB->begin();
447 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
448 // Remove the incoming value for BB, and remember it.
449 Value *InVal = PN->removeIncomingValue(BB, false);
451 // Two options: either the InVal is a phi node defined in BB or it is some
452 // value that dominates BB.
453 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
454 if (InValPhi && InValPhi->getParent() == BB) {
455 // Add all of the input values of the input PHI as inputs of this phi.
456 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
457 PN->addIncoming(InValPhi->getIncomingValue(i),
458 InValPhi->getIncomingBlock(i));
460 // Otherwise, add one instance of the dominating value for each edge that
461 // we will be adding.
462 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
463 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
464 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
466 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
467 PN->addIncoming(InVal, *PI);
472 // The PHIs are now updated, change everything that refers to BB to use
473 // DestBB and remove BB.
474 BB->replaceAllUsesWith(DestBB);
475 if (DT && !ModifiedDT) {
476 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
477 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
478 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
479 DT->changeImmediateDominator(DestBB, NewIDom);
482 BB->eraseFromParent();
485 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
488 /// SinkCast - Sink the specified cast instruction into its user blocks
489 static bool SinkCast(CastInst *CI) {
490 BasicBlock *DefBB = CI->getParent();
492 /// InsertedCasts - Only insert a cast in each block once.
493 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
495 bool MadeChange = false;
496 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
498 Use &TheUse = UI.getUse();
499 Instruction *User = cast<Instruction>(*UI);
501 // Figure out which BB this cast is used in. For PHI's this is the
502 // appropriate predecessor block.
503 BasicBlock *UserBB = User->getParent();
504 if (PHINode *PN = dyn_cast<PHINode>(User)) {
505 UserBB = PN->getIncomingBlock(TheUse);
508 // Preincrement use iterator so we don't invalidate it.
511 // If this user is in the same block as the cast, don't change the cast.
512 if (UserBB == DefBB) continue;
514 // If we have already inserted a cast into this block, use it.
515 CastInst *&InsertedCast = InsertedCasts[UserBB];
518 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
520 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
525 // Replace a use of the cast with a use of the new cast.
526 TheUse = InsertedCast;
530 // If we removed all uses, nuke the cast.
531 if (CI->use_empty()) {
532 CI->eraseFromParent();
539 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
540 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
541 /// sink it into user blocks to reduce the number of virtual
542 /// registers that must be created and coalesced.
544 /// Return true if any changes are made.
546 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
547 // If this is a noop copy,
548 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
549 EVT DstVT = TLI.getValueType(CI->getType());
551 // This is an fp<->int conversion?
552 if (SrcVT.isInteger() != DstVT.isInteger())
555 // If this is an extension, it will be a zero or sign extension, which
557 if (SrcVT.bitsLT(DstVT)) return false;
559 // If these values will be promoted, find out what they will be promoted
560 // to. This helps us consider truncates on PPC as noop copies when they
562 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
563 TargetLowering::TypePromoteInteger)
564 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
565 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
566 TargetLowering::TypePromoteInteger)
567 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
569 // If, after promotion, these are the same types, this is a noop copy.
576 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
577 /// the number of virtual registers that must be created and coalesced. This is
578 /// a clear win except on targets with multiple condition code registers
579 /// (PowerPC), where it might lose; some adjustment may be wanted there.
581 /// Return true if any changes are made.
582 static bool OptimizeCmpExpression(CmpInst *CI) {
583 BasicBlock *DefBB = CI->getParent();
585 /// InsertedCmp - Only insert a cmp in each block once.
586 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
588 bool MadeChange = false;
589 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
591 Use &TheUse = UI.getUse();
592 Instruction *User = cast<Instruction>(*UI);
594 // Preincrement use iterator so we don't invalidate it.
597 // Don't bother for PHI nodes.
598 if (isa<PHINode>(User))
601 // Figure out which BB this cmp is used in.
602 BasicBlock *UserBB = User->getParent();
604 // If this user is in the same block as the cmp, don't change the cmp.
605 if (UserBB == DefBB) continue;
607 // If we have already inserted a cmp into this block, use it.
608 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
611 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
613 CmpInst::Create(CI->getOpcode(),
614 CI->getPredicate(), CI->getOperand(0),
615 CI->getOperand(1), "", InsertPt);
619 // Replace a use of the cmp with a use of the new cmp.
620 TheUse = InsertedCmp;
624 // If we removed all uses, nuke the cmp.
626 CI->eraseFromParent();
632 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
634 void replaceCall(Value *With) override {
635 CI->replaceAllUsesWith(With);
636 CI->eraseFromParent();
638 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
639 if (ConstantInt *SizeCI =
640 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
641 return SizeCI->isAllOnesValue();
645 } // end anonymous namespace
647 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
648 BasicBlock *BB = CI->getParent();
650 // Lower inline assembly if we can.
651 // If we found an inline asm expession, and if the target knows how to
652 // lower it to normal LLVM code, do so now.
653 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
654 if (TLI->ExpandInlineAsm(CI)) {
655 // Avoid invalidating the iterator.
656 CurInstIterator = BB->begin();
657 // Avoid processing instructions out of order, which could cause
658 // reuse before a value is defined.
662 // Sink address computing for memory operands into the block.
663 if (OptimizeInlineAsmInst(CI))
667 // Lower all uses of llvm.objectsize.*
668 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
669 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
670 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
671 Type *ReturnTy = CI->getType();
672 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
674 // Substituting this can cause recursive simplifications, which can
675 // invalidate our iterator. Use a WeakVH to hold onto it in case this
677 WeakVH IterHandle(CurInstIterator);
679 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
680 TLInfo, ModifiedDT ? 0 : DT);
682 // If the iterator instruction was recursively deleted, start over at the
683 // start of the block.
684 if (IterHandle != CurInstIterator) {
685 CurInstIterator = BB->begin();
692 SmallVector<Value*, 2> PtrOps;
694 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
695 while (!PtrOps.empty())
696 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
700 // From here on out we're working with named functions.
701 if (CI->getCalledFunction() == 0) return false;
703 // We'll need DataLayout from here on out.
704 const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
705 if (!TD) return false;
707 // Lower all default uses of _chk calls. This is very similar
708 // to what InstCombineCalls does, but here we are only lowering calls
709 // that have the default "don't know" as the objectsize. Anything else
710 // should be left alone.
711 CodeGenPrepareFortifiedLibCalls Simplifier;
712 return Simplifier.fold(CI, TD, TLInfo);
715 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
716 /// instructions to the predecessor to enable tail call optimizations. The
717 /// case it is currently looking for is:
720 /// %tmp0 = tail call i32 @f0()
723 /// %tmp1 = tail call i32 @f1()
726 /// %tmp2 = tail call i32 @f2()
729 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
737 /// %tmp0 = tail call i32 @f0()
740 /// %tmp1 = tail call i32 @f1()
743 /// %tmp2 = tail call i32 @f2()
746 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
750 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
755 BitCastInst *BCI = 0;
756 Value *V = RI->getReturnValue();
758 BCI = dyn_cast<BitCastInst>(V);
760 V = BCI->getOperand(0);
762 PN = dyn_cast<PHINode>(V);
767 if (PN && PN->getParent() != BB)
770 // It's not safe to eliminate the sign / zero extension of the return value.
771 // See llvm::isInTailCallPosition().
772 const Function *F = BB->getParent();
773 AttributeSet CallerAttrs = F->getAttributes();
774 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
775 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
778 // Make sure there are no instructions between the PHI and return, or that the
779 // return is the first instruction in the block.
781 BasicBlock::iterator BI = BB->begin();
782 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
784 // Also skip over the bitcast.
789 BasicBlock::iterator BI = BB->begin();
790 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
795 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
797 SmallVector<CallInst*, 4> TailCalls;
799 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
800 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
801 // Make sure the phi value is indeed produced by the tail call.
802 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
803 TLI->mayBeEmittedAsTailCall(CI))
804 TailCalls.push_back(CI);
807 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
808 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
809 if (!VisitedBBs.insert(*PI))
812 BasicBlock::InstListType &InstList = (*PI)->getInstList();
813 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
814 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
815 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
819 CallInst *CI = dyn_cast<CallInst>(&*RI);
820 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
821 TailCalls.push_back(CI);
825 bool Changed = false;
826 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
827 CallInst *CI = TailCalls[i];
830 // Conservatively require the attributes of the call to match those of the
831 // return. Ignore noalias because it doesn't affect the call sequence.
832 AttributeSet CalleeAttrs = CS.getAttributes();
833 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
834 removeAttribute(Attribute::NoAlias) !=
835 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
836 removeAttribute(Attribute::NoAlias))
839 // Make sure the call instruction is followed by an unconditional branch to
841 BasicBlock *CallBB = CI->getParent();
842 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
843 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
846 // Duplicate the return into CallBB.
847 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
848 ModifiedDT = Changed = true;
852 // If we eliminated all predecessors of the block, delete the block now.
853 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
854 BB->eraseFromParent();
859 //===----------------------------------------------------------------------===//
860 // Memory Optimization
861 //===----------------------------------------------------------------------===//
865 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
866 /// which holds actual Value*'s for register values.
867 struct ExtAddrMode : public TargetLowering::AddrMode {
870 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
871 void print(raw_ostream &OS) const;
874 bool operator==(const ExtAddrMode& O) const {
875 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
876 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
877 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
882 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
888 void ExtAddrMode::print(raw_ostream &OS) const {
889 bool NeedPlus = false;
892 OS << (NeedPlus ? " + " : "")
894 BaseGV->printAsOperand(OS, /*PrintType=*/false);
899 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
902 OS << (NeedPlus ? " + " : "")
904 BaseReg->printAsOperand(OS, /*PrintType=*/false);
908 OS << (NeedPlus ? " + " : "")
910 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
916 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
917 void ExtAddrMode::dump() const {
923 /// \brief This class provides transaction based operation on the IR.
924 /// Every change made through this class is recorded in the internal state and
925 /// can be undone (rollback) until commit is called.
926 class TypePromotionTransaction {
928 /// \brief This represents the common interface of the individual transaction.
929 /// Each class implements the logic for doing one specific modification on
930 /// the IR via the TypePromotionTransaction.
931 class TypePromotionAction {
933 /// The Instruction modified.
937 /// \brief Constructor of the action.
938 /// The constructor performs the related action on the IR.
939 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
941 virtual ~TypePromotionAction() {}
943 /// \brief Undo the modification done by this action.
944 /// When this method is called, the IR must be in the same state as it was
945 /// before this action was applied.
946 /// \pre Undoing the action works if and only if the IR is in the exact same
947 /// state as it was directly after this action was applied.
948 virtual void undo() = 0;
950 /// \brief Advocate every change made by this action.
951 /// When the results on the IR of the action are to be kept, it is important
952 /// to call this function, otherwise hidden information may be kept forever.
953 virtual void commit() {
954 // Nothing to be done, this action is not doing anything.
958 /// \brief Utility to remember the position of an instruction.
959 class InsertionHandler {
960 /// Position of an instruction.
961 /// Either an instruction:
962 /// - Is the first in a basic block: BB is used.
963 /// - Has a previous instructon: PrevInst is used.
965 Instruction *PrevInst;
968 /// Remember whether or not the instruction had a previous instruction.
969 bool HasPrevInstruction;
972 /// \brief Record the position of \p Inst.
973 InsertionHandler(Instruction *Inst) {
974 BasicBlock::iterator It = Inst;
975 HasPrevInstruction = (It != (Inst->getParent()->begin()));
976 if (HasPrevInstruction)
977 Point.PrevInst = --It;
979 Point.BB = Inst->getParent();
982 /// \brief Insert \p Inst at the recorded position.
983 void insert(Instruction *Inst) {
984 if (HasPrevInstruction) {
985 if (Inst->getParent())
986 Inst->removeFromParent();
987 Inst->insertAfter(Point.PrevInst);
989 Instruction *Position = Point.BB->getFirstInsertionPt();
990 if (Inst->getParent())
991 Inst->moveBefore(Position);
993 Inst->insertBefore(Position);
998 /// \brief Move an instruction before another.
999 class InstructionMoveBefore : public TypePromotionAction {
1000 /// Original position of the instruction.
1001 InsertionHandler Position;
1004 /// \brief Move \p Inst before \p Before.
1005 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1006 : TypePromotionAction(Inst), Position(Inst) {
1007 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1008 Inst->moveBefore(Before);
1011 /// \brief Move the instruction back to its original position.
1012 void undo() override {
1013 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1014 Position.insert(Inst);
1018 /// \brief Set the operand of an instruction with a new value.
1019 class OperandSetter : public TypePromotionAction {
1020 /// Original operand of the instruction.
1022 /// Index of the modified instruction.
1026 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1027 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1028 : TypePromotionAction(Inst), Idx(Idx) {
1029 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1030 << "for:" << *Inst << "\n"
1031 << "with:" << *NewVal << "\n");
1032 Origin = Inst->getOperand(Idx);
1033 Inst->setOperand(Idx, NewVal);
1036 /// \brief Restore the original value of the instruction.
1037 void undo() override {
1038 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1039 << "for: " << *Inst << "\n"
1040 << "with: " << *Origin << "\n");
1041 Inst->setOperand(Idx, Origin);
1045 /// \brief Hide the operands of an instruction.
1046 /// Do as if this instruction was not using any of its operands.
1047 class OperandsHider : public TypePromotionAction {
1048 /// The list of original operands.
1049 SmallVector<Value *, 4> OriginalValues;
1052 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1053 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1054 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1055 unsigned NumOpnds = Inst->getNumOperands();
1056 OriginalValues.reserve(NumOpnds);
1057 for (unsigned It = 0; It < NumOpnds; ++It) {
1058 // Save the current operand.
1059 Value *Val = Inst->getOperand(It);
1060 OriginalValues.push_back(Val);
1062 // We could use OperandSetter here, but that would implied an overhead
1063 // that we are not willing to pay.
1064 Inst->setOperand(It, UndefValue::get(Val->getType()));
1068 /// \brief Restore the original list of uses.
1069 void undo() override {
1070 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1071 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1072 Inst->setOperand(It, OriginalValues[It]);
1076 /// \brief Build a truncate instruction.
1077 class TruncBuilder : public TypePromotionAction {
1079 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1081 /// trunc Opnd to Ty.
1082 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1083 IRBuilder<> Builder(Opnd);
1084 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1085 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1088 /// \brief Get the built instruction.
1089 Instruction *getBuiltInstruction() { return Inst; }
1091 /// \brief Remove the built instruction.
1092 void undo() override {
1093 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1094 Inst->eraseFromParent();
1098 /// \brief Build a sign extension instruction.
1099 class SExtBuilder : public TypePromotionAction {
1101 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1103 /// sext Opnd to Ty.
1104 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1105 : TypePromotionAction(Inst) {
1106 IRBuilder<> Builder(InsertPt);
1107 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1108 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1111 /// \brief Get the built instruction.
1112 Instruction *getBuiltInstruction() { return Inst; }
1114 /// \brief Remove the built instruction.
1115 void undo() override {
1116 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1117 Inst->eraseFromParent();
1121 /// \brief Mutate an instruction to another type.
1122 class TypeMutator : public TypePromotionAction {
1123 /// Record the original type.
1127 /// \brief Mutate the type of \p Inst into \p NewTy.
1128 TypeMutator(Instruction *Inst, Type *NewTy)
1129 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1130 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1132 Inst->mutateType(NewTy);
1135 /// \brief Mutate the instruction back to its original type.
1136 void undo() override {
1137 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1139 Inst->mutateType(OrigTy);
1143 /// \brief Replace the uses of an instruction by another instruction.
1144 class UsesReplacer : public TypePromotionAction {
1145 /// Helper structure to keep track of the replaced uses.
1146 struct InstructionAndIdx {
1147 /// The instruction using the instruction.
1149 /// The index where this instruction is used for Inst.
1151 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1152 : Inst(Inst), Idx(Idx) {}
1155 /// Keep track of the original uses (pair Instruction, Index).
1156 SmallVector<InstructionAndIdx, 4> OriginalUses;
1157 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1160 /// \brief Replace all the use of \p Inst by \p New.
1161 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1162 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1164 // Record the original uses.
1165 for (Use &U : Inst->uses()) {
1166 Instruction *UserI = cast<Instruction>(U.getUser());
1167 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1169 // Now, we can replace the uses.
1170 Inst->replaceAllUsesWith(New);
1173 /// \brief Reassign the original uses of Inst to Inst.
1174 void undo() override {
1175 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1176 for (use_iterator UseIt = OriginalUses.begin(),
1177 EndIt = OriginalUses.end();
1178 UseIt != EndIt; ++UseIt) {
1179 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1184 /// \brief Remove an instruction from the IR.
1185 class InstructionRemover : public TypePromotionAction {
1186 /// Original position of the instruction.
1187 InsertionHandler Inserter;
1188 /// Helper structure to hide all the link to the instruction. In other
1189 /// words, this helps to do as if the instruction was removed.
1190 OperandsHider Hider;
1191 /// Keep track of the uses replaced, if any.
1192 UsesReplacer *Replacer;
1195 /// \brief Remove all reference of \p Inst and optinally replace all its
1197 /// \pre If !Inst->use_empty(), then New != NULL
1198 InstructionRemover(Instruction *Inst, Value *New = NULL)
1199 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1202 Replacer = new UsesReplacer(Inst, New);
1203 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1204 Inst->removeFromParent();
1207 ~InstructionRemover() { delete Replacer; }
1209 /// \brief Really remove the instruction.
1210 void commit() override { delete Inst; }
1212 /// \brief Resurrect the instruction and reassign it to the proper uses if
1213 /// new value was provided when build this action.
1214 void undo() override {
1215 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1216 Inserter.insert(Inst);
1224 /// Restoration point.
1225 /// The restoration point is a pointer to an action instead of an iterator
1226 /// because the iterator may be invalidated but not the pointer.
1227 typedef const TypePromotionAction *ConstRestorationPt;
1228 /// Advocate every changes made in that transaction.
1230 /// Undo all the changes made after the given point.
1231 void rollback(ConstRestorationPt Point);
1232 /// Get the current restoration point.
1233 ConstRestorationPt getRestorationPoint() const;
1235 /// \name API for IR modification with state keeping to support rollback.
1237 /// Same as Instruction::setOperand.
1238 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1239 /// Same as Instruction::eraseFromParent.
1240 void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1241 /// Same as Value::replaceAllUsesWith.
1242 void replaceAllUsesWith(Instruction *Inst, Value *New);
1243 /// Same as Value::mutateType.
1244 void mutateType(Instruction *Inst, Type *NewTy);
1245 /// Same as IRBuilder::createTrunc.
1246 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1247 /// Same as IRBuilder::createSExt.
1248 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1249 /// Same as Instruction::moveBefore.
1250 void moveBefore(Instruction *Inst, Instruction *Before);
1253 ~TypePromotionTransaction();
1256 /// The ordered list of actions made so far.
1257 SmallVector<TypePromotionAction *, 16> Actions;
1258 typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1261 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1264 new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1267 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1270 new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1273 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1275 Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1278 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1279 Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1282 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1284 TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1285 Actions.push_back(TB);
1286 return TB->getBuiltInstruction();
1289 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1290 Value *Opnd, Type *Ty) {
1291 SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1292 Actions.push_back(SB);
1293 return SB->getBuiltInstruction();
1296 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1297 Instruction *Before) {
1299 new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1302 TypePromotionTransaction::ConstRestorationPt
1303 TypePromotionTransaction::getRestorationPoint() const {
1304 return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1307 void TypePromotionTransaction::commit() {
1308 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1316 void TypePromotionTransaction::rollback(
1317 TypePromotionTransaction::ConstRestorationPt Point) {
1318 while (!Actions.empty() && Point != (*Actions.rbegin())) {
1319 TypePromotionAction *Curr = Actions.pop_back_val();
1325 TypePromotionTransaction::~TypePromotionTransaction() {
1326 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1331 /// \brief A helper class for matching addressing modes.
1333 /// This encapsulates the logic for matching the target-legal addressing modes.
1334 class AddressingModeMatcher {
1335 SmallVectorImpl<Instruction*> &AddrModeInsts;
1336 const TargetLowering &TLI;
1338 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1339 /// the memory instruction that we're computing this address for.
1341 Instruction *MemoryInst;
1343 /// AddrMode - This is the addressing mode that we're building up. This is
1344 /// part of the return value of this addressing mode matching stuff.
1345 ExtAddrMode &AddrMode;
1347 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1348 const SetOfInstrs &InsertedTruncs;
1349 /// A map from the instructions to their type before promotion.
1350 InstrToOrigTy &PromotedInsts;
1351 /// The ongoing transaction where every action should be registered.
1352 TypePromotionTransaction &TPT;
1354 /// IgnoreProfitability - This is set to true when we should not do
1355 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1356 /// always returns true.
1357 bool IgnoreProfitability;
1359 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1360 const TargetLowering &T, Type *AT,
1361 Instruction *MI, ExtAddrMode &AM,
1362 const SetOfInstrs &InsertedTruncs,
1363 InstrToOrigTy &PromotedInsts,
1364 TypePromotionTransaction &TPT)
1365 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1366 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1367 IgnoreProfitability = false;
1371 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1372 /// give an access type of AccessTy. This returns a list of involved
1373 /// instructions in AddrModeInsts.
1374 /// \p InsertedTruncs The truncate instruction inserted by other
1377 /// \p PromotedInsts maps the instructions to their type before promotion.
1378 /// \p The ongoing transaction where every action should be registered.
1379 static ExtAddrMode Match(Value *V, Type *AccessTy,
1380 Instruction *MemoryInst,
1381 SmallVectorImpl<Instruction*> &AddrModeInsts,
1382 const TargetLowering &TLI,
1383 const SetOfInstrs &InsertedTruncs,
1384 InstrToOrigTy &PromotedInsts,
1385 TypePromotionTransaction &TPT) {
1388 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1389 MemoryInst, Result, InsertedTruncs,
1390 PromotedInsts, TPT).MatchAddr(V, 0);
1391 (void)Success; assert(Success && "Couldn't select *anything*?");
1395 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1396 bool MatchAddr(Value *V, unsigned Depth);
1397 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1398 bool *MovedAway = NULL);
1399 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1400 ExtAddrMode &AMBefore,
1401 ExtAddrMode &AMAfter);
1402 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1403 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1404 Value *PromotedOperand) const;
1407 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1408 /// Return true and update AddrMode if this addr mode is legal for the target,
1410 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1412 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1413 // mode. Just process that directly.
1415 return MatchAddr(ScaleReg, Depth);
1417 // If the scale is 0, it takes nothing to add this.
1421 // If we already have a scale of this value, we can add to it, otherwise, we
1422 // need an available scale field.
1423 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1426 ExtAddrMode TestAddrMode = AddrMode;
1428 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1429 // [A+B + A*7] -> [B+A*8].
1430 TestAddrMode.Scale += Scale;
1431 TestAddrMode.ScaledReg = ScaleReg;
1433 // If the new address isn't legal, bail out.
1434 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1437 // It was legal, so commit it.
1438 AddrMode = TestAddrMode;
1440 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1441 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1442 // X*Scale + C*Scale to addr mode.
1443 ConstantInt *CI = 0; Value *AddLHS = 0;
1444 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1445 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1446 TestAddrMode.ScaledReg = AddLHS;
1447 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1449 // If this addressing mode is legal, commit it and remember that we folded
1450 // this instruction.
1451 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1452 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1453 AddrMode = TestAddrMode;
1458 // Otherwise, not (x+c)*scale, just return what we have.
1462 /// MightBeFoldableInst - This is a little filter, which returns true if an
1463 /// addressing computation involving I might be folded into a load/store
1464 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1465 /// the set of instructions that MatchOperationAddr can.
1466 static bool MightBeFoldableInst(Instruction *I) {
1467 switch (I->getOpcode()) {
1468 case Instruction::BitCast:
1469 // Don't touch identity bitcasts.
1470 if (I->getType() == I->getOperand(0)->getType())
1472 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1473 case Instruction::PtrToInt:
1474 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1476 case Instruction::IntToPtr:
1477 // We know the input is intptr_t, so this is foldable.
1479 case Instruction::Add:
1481 case Instruction::Mul:
1482 case Instruction::Shl:
1483 // Can only handle X*C and X << C.
1484 return isa<ConstantInt>(I->getOperand(1));
1485 case Instruction::GetElementPtr:
1492 /// \brief Hepler class to perform type promotion.
1493 class TypePromotionHelper {
1494 /// \brief Utility function to check whether or not a sign extension of
1495 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1496 /// using the operands of \p Inst or promoting \p Inst.
1497 /// In other words, check if:
1498 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1499 /// #1 Promotion applies:
1500 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1501 /// #2 Operand reuses:
1502 /// sext opnd1 to ConsideredSExtType.
1503 /// \p PromotedInsts maps the instructions to their type before promotion.
1504 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1505 const InstrToOrigTy &PromotedInsts);
1507 /// \brief Utility function to determine if \p OpIdx should be promoted when
1508 /// promoting \p Inst.
1509 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1510 if (isa<SelectInst>(Inst) && OpIdx == 0)
1515 /// \brief Utility function to promote the operand of \p SExt when this
1516 /// operand is a promotable trunc or sext.
1517 /// \p PromotedInsts maps the instructions to their type before promotion.
1518 /// \p CreatedInsts[out] contains how many non-free instructions have been
1519 /// created to promote the operand of SExt.
1520 /// Should never be called directly.
1521 /// \return The promoted value which is used instead of SExt.
1522 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1523 TypePromotionTransaction &TPT,
1524 InstrToOrigTy &PromotedInsts,
1525 unsigned &CreatedInsts);
1527 /// \brief Utility function to promote the operand of \p SExt when this
1528 /// operand is promotable and is not a supported trunc or sext.
1529 /// \p PromotedInsts maps the instructions to their type before promotion.
1530 /// \p CreatedInsts[out] contains how many non-free instructions have been
1531 /// created to promote the operand of SExt.
1532 /// Should never be called directly.
1533 /// \return The promoted value which is used instead of SExt.
1534 static Value *promoteOperandForOther(Instruction *SExt,
1535 TypePromotionTransaction &TPT,
1536 InstrToOrigTy &PromotedInsts,
1537 unsigned &CreatedInsts);
1540 /// Type for the utility function that promotes the operand of SExt.
1541 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1542 InstrToOrigTy &PromotedInsts,
1543 unsigned &CreatedInsts);
1544 /// \brief Given a sign extend instruction \p SExt, return the approriate
1545 /// action to promote the operand of \p SExt instead of using SExt.
1546 /// \return NULL if no promotable action is possible with the current
1548 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1549 /// the others CodeGenPrepare optimizations. This information is important
1550 /// because we do not want to promote these instructions as CodeGenPrepare
1551 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1552 /// \p PromotedInsts maps the instructions to their type before promotion.
1553 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1554 const TargetLowering &TLI,
1555 const InstrToOrigTy &PromotedInsts);
1558 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1559 Type *ConsideredSExtType,
1560 const InstrToOrigTy &PromotedInsts) {
1561 // We can always get through sext.
1562 if (isa<SExtInst>(Inst))
1565 // We can get through binary operator, if it is legal. In other words, the
1566 // binary operator must have a nuw or nsw flag.
1567 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1568 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1569 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1572 // Check if we can do the following simplification.
1573 // sext(trunc(sext)) --> sext
1574 if (!isa<TruncInst>(Inst))
1577 Value *OpndVal = Inst->getOperand(0);
1578 // Check if we can use this operand in the sext.
1579 // If the type is larger than the result type of the sign extension,
1581 if (OpndVal->getType()->getIntegerBitWidth() >
1582 ConsideredSExtType->getIntegerBitWidth())
1585 // If the operand of the truncate is not an instruction, we will not have
1586 // any information on the dropped bits.
1587 // (Actually we could for constant but it is not worth the extra logic).
1588 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1592 // Check if the source of the type is narrow enough.
1593 // I.e., check that trunc just drops sign extended bits.
1594 // #1 get the type of the operand.
1595 const Type *OpndType;
1596 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1597 if (It != PromotedInsts.end())
1598 OpndType = It->second;
1599 else if (isa<SExtInst>(Opnd))
1600 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1604 // #2 check that the truncate just drop sign extended bits.
1605 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1611 TypePromotionHelper::Action TypePromotionHelper::getAction(
1612 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1613 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1614 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1615 Type *SExtTy = SExt->getType();
1616 // If the operand of the sign extension is not an instruction, we cannot
1618 // If it, check we can get through.
1619 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1622 // Do not promote if the operand has been added by codegenprepare.
1623 // Otherwise, it means we are undoing an optimization that is likely to be
1624 // redone, thus causing potential infinite loop.
1625 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1628 // SExt or Trunc instructions.
1629 // Return the related handler.
1630 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1631 return promoteOperandForTruncAndSExt;
1633 // Regular instruction.
1634 // Abort early if we will have to insert non-free instructions.
1635 if (!SExtOpnd->hasOneUse() &&
1636 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1638 return promoteOperandForOther;
1641 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1642 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1643 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1644 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1645 // get through it and this method should not be called.
1646 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1647 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1649 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1652 // Remove dead code.
1653 if (SExtOpnd->use_empty())
1654 TPT.eraseInstruction(SExtOpnd);
1656 // Check if the sext is still needed.
1657 if (SExt->getType() != SExt->getOperand(0)->getType())
1660 // At this point we have: sext ty opnd to ty.
1661 // Reassign the uses of SExt to the opnd and remove SExt.
1662 Value *NextVal = SExt->getOperand(0);
1663 TPT.eraseInstruction(SExt, NextVal);
1668 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1669 TypePromotionTransaction &TPT,
1670 InstrToOrigTy &PromotedInsts,
1671 unsigned &CreatedInsts) {
1672 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1673 // get through it and this method should not be called.
1674 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1676 if (!SExtOpnd->hasOneUse()) {
1677 // SExtOpnd will be promoted.
1678 // All its uses, but SExt, will need to use a truncated value of the
1679 // promoted version.
1680 // Create the truncate now.
1681 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1682 Trunc->removeFromParent();
1683 // Insert it just after the definition.
1684 Trunc->insertAfter(SExtOpnd);
1686 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1687 // Restore the operand of SExt (which has been replace by the previous call
1688 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1689 TPT.setOperand(SExt, 0, SExtOpnd);
1692 // Get through the Instruction:
1693 // 1. Update its type.
1694 // 2. Replace the uses of SExt by Inst.
1695 // 3. Sign extend each operand that needs to be sign extended.
1697 // Remember the original type of the instruction before promotion.
1698 // This is useful to know that the high bits are sign extended bits.
1699 PromotedInsts.insert(
1700 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1702 TPT.mutateType(SExtOpnd, SExt->getType());
1704 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1706 Instruction *SExtForOpnd = SExt;
1708 DEBUG(dbgs() << "Propagate SExt to operands\n");
1709 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1711 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1712 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1713 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1714 DEBUG(dbgs() << "No need to propagate\n");
1717 // Check if we can statically sign extend the operand.
1718 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1719 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1720 DEBUG(dbgs() << "Statically sign extend\n");
1723 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1726 // UndefValue are typed, so we have to statically sign extend them.
1727 if (isa<UndefValue>(Opnd)) {
1728 DEBUG(dbgs() << "Statically sign extend\n");
1729 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1733 // Otherwise we have to explicity sign extend the operand.
1734 // Check if SExt was reused to sign extend an operand.
1736 // If yes, create a new one.
1737 DEBUG(dbgs() << "More operands to sext\n");
1738 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1742 TPT.setOperand(SExtForOpnd, 0, Opnd);
1744 // Move the sign extension before the insertion point.
1745 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1746 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1747 // If more sext are required, new instructions will have to be created.
1750 if (SExtForOpnd == SExt) {
1751 DEBUG(dbgs() << "Sign extension is useless now\n");
1752 TPT.eraseInstruction(SExt);
1757 /// IsPromotionProfitable - Check whether or not promoting an instruction
1758 /// to a wider type was profitable.
1759 /// \p MatchedSize gives the number of instructions that have been matched
1760 /// in the addressing mode after the promotion was applied.
1761 /// \p SizeWithPromotion gives the number of created instructions for
1762 /// the promotion plus the number of instructions that have been
1763 /// matched in the addressing mode before the promotion.
1764 /// \p PromotedOperand is the value that has been promoted.
1765 /// \return True if the promotion is profitable, false otherwise.
1767 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1768 unsigned SizeWithPromotion,
1769 Value *PromotedOperand) const {
1770 // We folded less instructions than what we created to promote the operand.
1771 // This is not profitable.
1772 if (MatchedSize < SizeWithPromotion)
1774 if (MatchedSize > SizeWithPromotion)
1776 // The promotion is neutral but it may help folding the sign extension in
1777 // loads for instance.
1778 // Check that we did not create an illegal instruction.
1779 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1782 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1783 // If the ISDOpcode is undefined, it was undefined before the promotion.
1786 // Otherwise, check if the promoted instruction is legal or not.
1787 return TLI.isOperationLegalOrCustom(ISDOpcode,
1788 EVT::getEVT(PromotedInst->getType()));
1791 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1792 /// fold the operation into the addressing mode. If so, update the addressing
1793 /// mode and return true, otherwise return false without modifying AddrMode.
1794 /// If \p MovedAway is not NULL, it contains the information of whether or
1795 /// not AddrInst has to be folded into the addressing mode on success.
1796 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1797 /// because it has been moved away.
1798 /// Thus AddrInst must not be added in the matched instructions.
1799 /// This state can happen when AddrInst is a sext, since it may be moved away.
1800 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1801 /// not be referenced anymore.
1802 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1805 // Avoid exponential behavior on extremely deep expression trees.
1806 if (Depth >= 5) return false;
1808 // By default, all matched instructions stay in place.
1813 case Instruction::PtrToInt:
1814 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1815 return MatchAddr(AddrInst->getOperand(0), Depth);
1816 case Instruction::IntToPtr:
1817 // This inttoptr is a no-op if the integer type is pointer sized.
1818 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1819 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1820 return MatchAddr(AddrInst->getOperand(0), Depth);
1822 case Instruction::BitCast:
1823 // BitCast is always a noop, and we can handle it as long as it is
1824 // int->int or pointer->pointer (we don't want int<->fp or something).
1825 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1826 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1827 // Don't touch identity bitcasts. These were probably put here by LSR,
1828 // and we don't want to mess around with them. Assume it knows what it
1830 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1831 return MatchAddr(AddrInst->getOperand(0), Depth);
1833 case Instruction::Add: {
1834 // Check to see if we can merge in the RHS then the LHS. If so, we win.
1835 ExtAddrMode BackupAddrMode = AddrMode;
1836 unsigned OldSize = AddrModeInsts.size();
1837 // Start a transaction at this point.
1838 // The LHS may match but not the RHS.
1839 // Therefore, we need a higher level restoration point to undo partially
1840 // matched operation.
1841 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1842 TPT.getRestorationPoint();
1844 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1845 MatchAddr(AddrInst->getOperand(0), Depth+1))
1848 // Restore the old addr mode info.
1849 AddrMode = BackupAddrMode;
1850 AddrModeInsts.resize(OldSize);
1851 TPT.rollback(LastKnownGood);
1853 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
1854 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1855 MatchAddr(AddrInst->getOperand(1), Depth+1))
1858 // Otherwise we definitely can't merge the ADD in.
1859 AddrMode = BackupAddrMode;
1860 AddrModeInsts.resize(OldSize);
1861 TPT.rollback(LastKnownGood);
1864 //case Instruction::Or:
1865 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1867 case Instruction::Mul:
1868 case Instruction::Shl: {
1869 // Can only handle X*C and X << C.
1870 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1871 if (!RHS) return false;
1872 int64_t Scale = RHS->getSExtValue();
1873 if (Opcode == Instruction::Shl)
1874 Scale = 1LL << Scale;
1876 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1878 case Instruction::GetElementPtr: {
1879 // Scan the GEP. We check it if it contains constant offsets and at most
1880 // one variable offset.
1881 int VariableOperand = -1;
1882 unsigned VariableScale = 0;
1884 int64_t ConstantOffset = 0;
1885 const DataLayout *TD = TLI.getDataLayout();
1886 gep_type_iterator GTI = gep_type_begin(AddrInst);
1887 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1888 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1889 const StructLayout *SL = TD->getStructLayout(STy);
1891 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1892 ConstantOffset += SL->getElementOffset(Idx);
1894 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1895 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1896 ConstantOffset += CI->getSExtValue()*TypeSize;
1897 } else if (TypeSize) { // Scales of zero don't do anything.
1898 // We only allow one variable index at the moment.
1899 if (VariableOperand != -1)
1902 // Remember the variable index.
1903 VariableOperand = i;
1904 VariableScale = TypeSize;
1909 // A common case is for the GEP to only do a constant offset. In this case,
1910 // just add it to the disp field and check validity.
1911 if (VariableOperand == -1) {
1912 AddrMode.BaseOffs += ConstantOffset;
1913 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1914 // Check to see if we can fold the base pointer in too.
1915 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1918 AddrMode.BaseOffs -= ConstantOffset;
1922 // Save the valid addressing mode in case we can't match.
1923 ExtAddrMode BackupAddrMode = AddrMode;
1924 unsigned OldSize = AddrModeInsts.size();
1926 // See if the scale and offset amount is valid for this target.
1927 AddrMode.BaseOffs += ConstantOffset;
1929 // Match the base operand of the GEP.
1930 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1931 // If it couldn't be matched, just stuff the value in a register.
1932 if (AddrMode.HasBaseReg) {
1933 AddrMode = BackupAddrMode;
1934 AddrModeInsts.resize(OldSize);
1937 AddrMode.HasBaseReg = true;
1938 AddrMode.BaseReg = AddrInst->getOperand(0);
1941 // Match the remaining variable portion of the GEP.
1942 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1944 // If it couldn't be matched, try stuffing the base into a register
1945 // instead of matching it, and retrying the match of the scale.
1946 AddrMode = BackupAddrMode;
1947 AddrModeInsts.resize(OldSize);
1948 if (AddrMode.HasBaseReg)
1950 AddrMode.HasBaseReg = true;
1951 AddrMode.BaseReg = AddrInst->getOperand(0);
1952 AddrMode.BaseOffs += ConstantOffset;
1953 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1954 VariableScale, Depth)) {
1955 // If even that didn't work, bail.
1956 AddrMode = BackupAddrMode;
1957 AddrModeInsts.resize(OldSize);
1964 case Instruction::SExt: {
1965 // Try to move this sext out of the way of the addressing mode.
1966 Instruction *SExt = cast<Instruction>(AddrInst);
1967 // Ask for a method for doing so.
1968 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1969 SExt, InsertedTruncs, TLI, PromotedInsts);
1973 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1974 TPT.getRestorationPoint();
1975 unsigned CreatedInsts = 0;
1976 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1977 // SExt has been moved away.
1978 // Thus either it will be rematched later in the recursive calls or it is
1979 // gone. Anyway, we must not fold it into the addressing mode at this point.
1983 // addr = gep base, idx
1985 // promotedOpnd = sext opnd <- no match here
1986 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
1987 // addr = gep base, op <- match
1991 assert(PromotedOperand &&
1992 "TypePromotionHelper should have filtered out those cases");
1994 ExtAddrMode BackupAddrMode = AddrMode;
1995 unsigned OldSize = AddrModeInsts.size();
1997 if (!MatchAddr(PromotedOperand, Depth) ||
1998 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2000 AddrMode = BackupAddrMode;
2001 AddrModeInsts.resize(OldSize);
2002 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2003 TPT.rollback(LastKnownGood);
2012 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2013 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2014 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2015 /// or intptr_t for the target.
2017 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2018 // Start a transaction at this point that we will rollback if the matching
2020 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2021 TPT.getRestorationPoint();
2022 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2023 // Fold in immediates if legal for the target.
2024 AddrMode.BaseOffs += CI->getSExtValue();
2025 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2027 AddrMode.BaseOffs -= CI->getSExtValue();
2028 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2029 // If this is a global variable, try to fold it into the addressing mode.
2030 if (AddrMode.BaseGV == 0) {
2031 AddrMode.BaseGV = GV;
2032 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2034 AddrMode.BaseGV = 0;
2036 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2037 ExtAddrMode BackupAddrMode = AddrMode;
2038 unsigned OldSize = AddrModeInsts.size();
2040 // Check to see if it is possible to fold this operation.
2041 bool MovedAway = false;
2042 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2043 // This instruction may have been move away. If so, there is nothing
2047 // Okay, it's possible to fold this. Check to see if it is actually
2048 // *profitable* to do so. We use a simple cost model to avoid increasing
2049 // register pressure too much.
2050 if (I->hasOneUse() ||
2051 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2052 AddrModeInsts.push_back(I);
2056 // It isn't profitable to do this, roll back.
2057 //cerr << "NOT FOLDING: " << *I;
2058 AddrMode = BackupAddrMode;
2059 AddrModeInsts.resize(OldSize);
2060 TPT.rollback(LastKnownGood);
2062 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2063 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2065 TPT.rollback(LastKnownGood);
2066 } else if (isa<ConstantPointerNull>(Addr)) {
2067 // Null pointer gets folded without affecting the addressing mode.
2071 // Worse case, the target should support [reg] addressing modes. :)
2072 if (!AddrMode.HasBaseReg) {
2073 AddrMode.HasBaseReg = true;
2074 AddrMode.BaseReg = Addr;
2075 // Still check for legality in case the target supports [imm] but not [i+r].
2076 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2078 AddrMode.HasBaseReg = false;
2079 AddrMode.BaseReg = 0;
2082 // If the base register is already taken, see if we can do [r+r].
2083 if (AddrMode.Scale == 0) {
2085 AddrMode.ScaledReg = Addr;
2086 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2089 AddrMode.ScaledReg = 0;
2092 TPT.rollback(LastKnownGood);
2096 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2097 /// inline asm call are due to memory operands. If so, return true, otherwise
2099 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2100 const TargetLowering &TLI) {
2101 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2102 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2103 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2105 // Compute the constraint code and ConstraintType to use.
2106 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2108 // If this asm operand is our Value*, and if it isn't an indirect memory
2109 // operand, we can't fold it!
2110 if (OpInfo.CallOperandVal == OpVal &&
2111 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2112 !OpInfo.isIndirect))
2119 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2120 /// memory use. If we find an obviously non-foldable instruction, return true.
2121 /// Add the ultimately found memory instructions to MemoryUses.
2122 static bool FindAllMemoryUses(Instruction *I,
2123 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2124 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2125 const TargetLowering &TLI) {
2126 // If we already considered this instruction, we're done.
2127 if (!ConsideredInsts.insert(I))
2130 // If this is an obviously unfoldable instruction, bail out.
2131 if (!MightBeFoldableInst(I))
2134 // Loop over all the uses, recursively processing them.
2135 for (Use &U : I->uses()) {
2136 Instruction *UserI = cast<Instruction>(U.getUser());
2138 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2139 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2143 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2144 unsigned opNo = U.getOperandNo();
2145 if (opNo == 0) return true; // Storing addr, not into addr.
2146 MemoryUses.push_back(std::make_pair(SI, opNo));
2150 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2151 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2152 if (!IA) return true;
2154 // If this is a memory operand, we're cool, otherwise bail out.
2155 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2160 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2167 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2168 /// the use site that we're folding it into. If so, there is no cost to
2169 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2170 /// that we know are live at the instruction already.
2171 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2172 Value *KnownLive2) {
2173 // If Val is either of the known-live values, we know it is live!
2174 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2177 // All values other than instructions and arguments (e.g. constants) are live.
2178 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2180 // If Val is a constant sized alloca in the entry block, it is live, this is
2181 // true because it is just a reference to the stack/frame pointer, which is
2182 // live for the whole function.
2183 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2184 if (AI->isStaticAlloca())
2187 // Check to see if this value is already used in the memory instruction's
2188 // block. If so, it's already live into the block at the very least, so we
2189 // can reasonably fold it.
2190 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2193 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2194 /// mode of the machine to fold the specified instruction into a load or store
2195 /// that ultimately uses it. However, the specified instruction has multiple
2196 /// uses. Given this, it may actually increase register pressure to fold it
2197 /// into the load. For example, consider this code:
2201 /// use(Y) -> nonload/store
2205 /// In this case, Y has multiple uses, and can be folded into the load of Z
2206 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2207 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2208 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2209 /// number of computations either.
2211 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2212 /// X was live across 'load Z' for other reasons, we actually *would* want to
2213 /// fold the addressing mode in the Z case. This would make Y die earlier.
2214 bool AddressingModeMatcher::
2215 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2216 ExtAddrMode &AMAfter) {
2217 if (IgnoreProfitability) return true;
2219 // AMBefore is the addressing mode before this instruction was folded into it,
2220 // and AMAfter is the addressing mode after the instruction was folded. Get
2221 // the set of registers referenced by AMAfter and subtract out those
2222 // referenced by AMBefore: this is the set of values which folding in this
2223 // address extends the lifetime of.
2225 // Note that there are only two potential values being referenced here,
2226 // BaseReg and ScaleReg (global addresses are always available, as are any
2227 // folded immediates).
2228 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2230 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2231 // lifetime wasn't extended by adding this instruction.
2232 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2234 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2237 // If folding this instruction (and it's subexprs) didn't extend any live
2238 // ranges, we're ok with it.
2239 if (BaseReg == 0 && ScaledReg == 0)
2242 // If all uses of this instruction are ultimately load/store/inlineasm's,
2243 // check to see if their addressing modes will include this instruction. If
2244 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2246 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2247 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2248 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2249 return false; // Has a non-memory, non-foldable use!
2251 // Now that we know that all uses of this instruction are part of a chain of
2252 // computation involving only operations that could theoretically be folded
2253 // into a memory use, loop over each of these uses and see if they could
2254 // *actually* fold the instruction.
2255 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2256 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2257 Instruction *User = MemoryUses[i].first;
2258 unsigned OpNo = MemoryUses[i].second;
2260 // Get the access type of this use. If the use isn't a pointer, we don't
2261 // know what it accesses.
2262 Value *Address = User->getOperand(OpNo);
2263 if (!Address->getType()->isPointerTy())
2265 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2267 // Do a match against the root of this address, ignoring profitability. This
2268 // will tell us if the addressing mode for the memory operation will
2269 // *actually* cover the shared instruction.
2271 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2272 TPT.getRestorationPoint();
2273 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2274 MemoryInst, Result, InsertedTruncs,
2275 PromotedInsts, TPT);
2276 Matcher.IgnoreProfitability = true;
2277 bool Success = Matcher.MatchAddr(Address, 0);
2278 (void)Success; assert(Success && "Couldn't select *anything*?");
2280 // The match was to check the profitability, the changes made are not
2281 // part of the original matcher. Therefore, they should be dropped
2282 // otherwise the original matcher will not present the right state.
2283 TPT.rollback(LastKnownGood);
2285 // If the match didn't cover I, then it won't be shared by it.
2286 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2287 I) == MatchedAddrModeInsts.end())
2290 MatchedAddrModeInsts.clear();
2296 } // end anonymous namespace
2298 /// IsNonLocalValue - Return true if the specified values are defined in a
2299 /// different basic block than BB.
2300 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2301 if (Instruction *I = dyn_cast<Instruction>(V))
2302 return I->getParent() != BB;
2306 /// OptimizeMemoryInst - Load and Store Instructions often have
2307 /// addressing modes that can do significant amounts of computation. As such,
2308 /// instruction selection will try to get the load or store to do as much
2309 /// computation as possible for the program. The problem is that isel can only
2310 /// see within a single block. As such, we sink as much legal addressing mode
2311 /// stuff into the block as possible.
2313 /// This method is used to optimize both load/store and inline asms with memory
2315 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2319 // Try to collapse single-value PHI nodes. This is necessary to undo
2320 // unprofitable PRE transformations.
2321 SmallVector<Value*, 8> worklist;
2322 SmallPtrSet<Value*, 16> Visited;
2323 worklist.push_back(Addr);
2325 // Use a worklist to iteratively look through PHI nodes, and ensure that
2326 // the addressing mode obtained from the non-PHI roots of the graph
2328 Value *Consensus = 0;
2329 unsigned NumUsesConsensus = 0;
2330 bool IsNumUsesConsensusValid = false;
2331 SmallVector<Instruction*, 16> AddrModeInsts;
2332 ExtAddrMode AddrMode;
2333 TypePromotionTransaction TPT;
2334 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2335 TPT.getRestorationPoint();
2336 while (!worklist.empty()) {
2337 Value *V = worklist.back();
2338 worklist.pop_back();
2340 // Break use-def graph loops.
2341 if (!Visited.insert(V)) {
2346 // For a PHI node, push all of its incoming values.
2347 if (PHINode *P = dyn_cast<PHINode>(V)) {
2348 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2349 worklist.push_back(P->getIncomingValue(i));
2353 // For non-PHIs, determine the addressing mode being computed.
2354 SmallVector<Instruction*, 16> NewAddrModeInsts;
2355 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2356 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2357 PromotedInsts, TPT);
2359 // This check is broken into two cases with very similar code to avoid using
2360 // getNumUses() as much as possible. Some values have a lot of uses, so
2361 // calling getNumUses() unconditionally caused a significant compile-time
2365 AddrMode = NewAddrMode;
2366 AddrModeInsts = NewAddrModeInsts;
2368 } else if (NewAddrMode == AddrMode) {
2369 if (!IsNumUsesConsensusValid) {
2370 NumUsesConsensus = Consensus->getNumUses();
2371 IsNumUsesConsensusValid = true;
2374 // Ensure that the obtained addressing mode is equivalent to that obtained
2375 // for all other roots of the PHI traversal. Also, when choosing one
2376 // such root as representative, select the one with the most uses in order
2377 // to keep the cost modeling heuristics in AddressingModeMatcher
2379 unsigned NumUses = V->getNumUses();
2380 if (NumUses > NumUsesConsensus) {
2382 NumUsesConsensus = NumUses;
2383 AddrModeInsts = NewAddrModeInsts;
2392 // If the addressing mode couldn't be determined, or if multiple different
2393 // ones were determined, bail out now.
2395 TPT.rollback(LastKnownGood);
2400 // Check to see if any of the instructions supersumed by this addr mode are
2401 // non-local to I's BB.
2402 bool AnyNonLocal = false;
2403 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2404 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2410 // If all the instructions matched are already in this BB, don't do anything.
2412 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2416 // Insert this computation right after this user. Since our caller is
2417 // scanning from the top of the BB to the bottom, reuse of the expr are
2418 // guaranteed to happen later.
2419 IRBuilder<> Builder(MemoryInst);
2421 // Now that we determined the addressing expression we want to use and know
2422 // that we have to sink it into this block. Check to see if we have already
2423 // done this for some other load/store instr in this block. If so, reuse the
2425 Value *&SunkAddr = SunkAddrs[Addr];
2427 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2429 if (SunkAddr->getType() != Addr->getType())
2430 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2431 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2432 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2433 // By default, we use the GEP-based method when AA is used later. This
2434 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2435 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2437 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2438 Value *ResultPtr = 0, *ResultIndex = 0;
2440 // First, find the pointer.
2441 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2442 ResultPtr = AddrMode.BaseReg;
2443 AddrMode.BaseReg = 0;
2446 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2447 // We can't add more than one pointer together, nor can we scale a
2448 // pointer (both of which seem meaningless).
2449 if (ResultPtr || AddrMode.Scale != 1)
2452 ResultPtr = AddrMode.ScaledReg;
2456 if (AddrMode.BaseGV) {
2460 ResultPtr = AddrMode.BaseGV;
2463 // If the real base value actually came from an inttoptr, then the matcher
2464 // will look through it and provide only the integer value. In that case,
2466 if (!ResultPtr && AddrMode.BaseReg) {
2468 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2469 AddrMode.BaseReg = 0;
2470 } else if (!ResultPtr && AddrMode.Scale == 1) {
2472 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2477 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2478 SunkAddr = Constant::getNullValue(Addr->getType());
2479 } else if (!ResultPtr) {
2483 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2485 // Start with the base register. Do this first so that subsequent address
2486 // matching finds it last, which will prevent it from trying to match it
2487 // as the scaled value in case it happens to be a mul. That would be
2488 // problematic if we've sunk a different mul for the scale, because then
2489 // we'd end up sinking both muls.
2490 if (AddrMode.BaseReg) {
2491 Value *V = AddrMode.BaseReg;
2492 if (V->getType() != IntPtrTy)
2493 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2498 // Add the scale value.
2499 if (AddrMode.Scale) {
2500 Value *V = AddrMode.ScaledReg;
2501 if (V->getType() == IntPtrTy) {
2503 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2504 cast<IntegerType>(V->getType())->getBitWidth()) {
2505 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2507 // It is only safe to sign extend the BaseReg if we know that the math
2508 // required to create it did not overflow before we extend it. Since
2509 // the original IR value was tossed in favor of a constant back when
2510 // the AddrMode was created we need to bail out gracefully if widths
2511 // do not match instead of extending it.
2512 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2513 if (I && (ResultIndex != AddrMode.BaseReg))
2514 I->eraseFromParent();
2518 if (AddrMode.Scale != 1)
2519 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2522 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2527 // Add in the Base Offset if present.
2528 if (AddrMode.BaseOffs) {
2529 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2531 // We need to add this separately from the scale above to help with
2532 // SDAG consecutive load/store merging.
2533 if (ResultPtr->getType() != I8PtrTy)
2534 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2535 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2542 SunkAddr = ResultPtr;
2544 if (ResultPtr->getType() != I8PtrTy)
2545 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2546 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2549 if (SunkAddr->getType() != Addr->getType())
2550 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2553 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2555 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2558 // Start with the base register. Do this first so that subsequent address
2559 // matching finds it last, which will prevent it from trying to match it
2560 // as the scaled value in case it happens to be a mul. That would be
2561 // problematic if we've sunk a different mul for the scale, because then
2562 // we'd end up sinking both muls.
2563 if (AddrMode.BaseReg) {
2564 Value *V = AddrMode.BaseReg;
2565 if (V->getType()->isPointerTy())
2566 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2567 if (V->getType() != IntPtrTy)
2568 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2572 // Add the scale value.
2573 if (AddrMode.Scale) {
2574 Value *V = AddrMode.ScaledReg;
2575 if (V->getType() == IntPtrTy) {
2577 } else if (V->getType()->isPointerTy()) {
2578 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2579 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2580 cast<IntegerType>(V->getType())->getBitWidth()) {
2581 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2583 // It is only safe to sign extend the BaseReg if we know that the math
2584 // required to create it did not overflow before we extend it. Since
2585 // the original IR value was tossed in favor of a constant back when
2586 // the AddrMode was created we need to bail out gracefully if widths
2587 // do not match instead of extending it.
2588 Instruction *I = dyn_cast<Instruction>(Result);
2589 if (I && (Result != AddrMode.BaseReg))
2590 I->eraseFromParent();
2593 if (AddrMode.Scale != 1)
2594 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2597 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2602 // Add in the BaseGV if present.
2603 if (AddrMode.BaseGV) {
2604 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2606 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2611 // Add in the Base Offset if present.
2612 if (AddrMode.BaseOffs) {
2613 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2615 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2621 SunkAddr = Constant::getNullValue(Addr->getType());
2623 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2626 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2628 // If we have no uses, recursively delete the value and all dead instructions
2630 if (Repl->use_empty()) {
2631 // This can cause recursive deletion, which can invalidate our iterator.
2632 // Use a WeakVH to hold onto it in case this happens.
2633 WeakVH IterHandle(CurInstIterator);
2634 BasicBlock *BB = CurInstIterator->getParent();
2636 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2638 if (IterHandle != CurInstIterator) {
2639 // If the iterator instruction was recursively deleted, start over at the
2640 // start of the block.
2641 CurInstIterator = BB->begin();
2649 /// OptimizeInlineAsmInst - If there are any memory operands, use
2650 /// OptimizeMemoryInst to sink their address computing into the block when
2651 /// possible / profitable.
2652 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2653 bool MadeChange = false;
2655 TargetLowering::AsmOperandInfoVector
2656 TargetConstraints = TLI->ParseConstraints(CS);
2658 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2659 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2661 // Compute the constraint code and ConstraintType to use.
2662 TLI->ComputeConstraintToUse(OpInfo, SDValue());
2664 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2665 OpInfo.isIndirect) {
2666 Value *OpVal = CS->getArgOperand(ArgNo++);
2667 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2668 } else if (OpInfo.Type == InlineAsm::isInput)
2675 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2676 /// basic block as the load, unless conditions are unfavorable. This allows
2677 /// SelectionDAG to fold the extend into the load.
2679 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2680 // Look for a load being extended.
2681 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2682 if (!LI) return false;
2684 // If they're already in the same block, there's nothing to do.
2685 if (LI->getParent() == I->getParent())
2688 // If the load has other users and the truncate is not free, this probably
2689 // isn't worthwhile.
2690 if (!LI->hasOneUse() &&
2691 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2692 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2693 !TLI->isTruncateFree(I->getType(), LI->getType()))
2696 // Check whether the target supports casts folded into loads.
2698 if (isa<ZExtInst>(I))
2699 LType = ISD::ZEXTLOAD;
2701 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2702 LType = ISD::SEXTLOAD;
2704 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2707 // Move the extend into the same block as the load, so that SelectionDAG
2709 I->removeFromParent();
2715 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2716 BasicBlock *DefBB = I->getParent();
2718 // If the result of a {s|z}ext and its source are both live out, rewrite all
2719 // other uses of the source with result of extension.
2720 Value *Src = I->getOperand(0);
2721 if (Src->hasOneUse())
2724 // Only do this xform if truncating is free.
2725 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2728 // Only safe to perform the optimization if the source is also defined in
2730 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2733 bool DefIsLiveOut = false;
2734 for (User *U : I->users()) {
2735 Instruction *UI = cast<Instruction>(U);
2737 // Figure out which BB this ext is used in.
2738 BasicBlock *UserBB = UI->getParent();
2739 if (UserBB == DefBB) continue;
2740 DefIsLiveOut = true;
2746 // Make sure none of the uses are PHI nodes.
2747 for (User *U : Src->users()) {
2748 Instruction *UI = cast<Instruction>(U);
2749 BasicBlock *UserBB = UI->getParent();
2750 if (UserBB == DefBB) continue;
2751 // Be conservative. We don't want this xform to end up introducing
2752 // reloads just before load / store instructions.
2753 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
2757 // InsertedTruncs - Only insert one trunc in each block once.
2758 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2760 bool MadeChange = false;
2761 for (Use &U : Src->uses()) {
2762 Instruction *User = cast<Instruction>(U.getUser());
2764 // Figure out which BB this ext is used in.
2765 BasicBlock *UserBB = User->getParent();
2766 if (UserBB == DefBB) continue;
2768 // Both src and def are live in this block. Rewrite the use.
2769 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2771 if (!InsertedTrunc) {
2772 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2773 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2774 InsertedTruncsSet.insert(InsertedTrunc);
2777 // Replace a use of the {s|z}ext source with a use of the result.
2786 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2787 /// turned into an explicit branch.
2788 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2789 // FIXME: This should use the same heuristics as IfConversion to determine
2790 // whether a select is better represented as a branch. This requires that
2791 // branch probability metadata is preserved for the select, which is not the
2794 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2796 // If the branch is predicted right, an out of order CPU can avoid blocking on
2797 // the compare. Emit cmovs on compares with a memory operand as branches to
2798 // avoid stalls on the load from memory. If the compare has more than one use
2799 // there's probably another cmov or setcc around so it's not worth emitting a
2804 Value *CmpOp0 = Cmp->getOperand(0);
2805 Value *CmpOp1 = Cmp->getOperand(1);
2807 // We check that the memory operand has one use to avoid uses of the loaded
2808 // value directly after the compare, making branches unprofitable.
2809 return Cmp->hasOneUse() &&
2810 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2811 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2815 /// If we have a SelectInst that will likely profit from branch prediction,
2816 /// turn it into a branch.
2817 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2818 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2820 // Can we convert the 'select' to CF ?
2821 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
2824 TargetLowering::SelectSupportKind SelectKind;
2826 SelectKind = TargetLowering::VectorMaskSelect;
2827 else if (SI->getType()->isVectorTy())
2828 SelectKind = TargetLowering::ScalarCondVectorVal;
2830 SelectKind = TargetLowering::ScalarValSelect;
2832 // Do we have efficient codegen support for this kind of 'selects' ?
2833 if (TLI->isSelectSupported(SelectKind)) {
2834 // We have efficient codegen support for the select instruction.
2835 // Check if it is profitable to keep this 'select'.
2836 if (!TLI->isPredictableSelectExpensive() ||
2837 !isFormingBranchFromSelectProfitable(SI))
2843 // First, we split the block containing the select into 2 blocks.
2844 BasicBlock *StartBlock = SI->getParent();
2845 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2846 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2848 // Create a new block serving as the landing pad for the branch.
2849 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2850 NextBlock->getParent(), NextBlock);
2852 // Move the unconditional branch from the block with the select in it into our
2853 // landing pad block.
2854 StartBlock->getTerminator()->eraseFromParent();
2855 BranchInst::Create(NextBlock, SmallBlock);
2857 // Insert the real conditional branch based on the original condition.
2858 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2860 // The select itself is replaced with a PHI Node.
2861 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2863 PN->addIncoming(SI->getTrueValue(), StartBlock);
2864 PN->addIncoming(SI->getFalseValue(), SmallBlock);
2865 SI->replaceAllUsesWith(PN);
2866 SI->eraseFromParent();
2868 // Instruct OptimizeBlock to skip to the next block.
2869 CurInstIterator = StartBlock->end();
2870 ++NumSelectsExpanded;
2874 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
2875 SmallVector<int, 16> Mask(SVI->getShuffleMask());
2877 for (unsigned i = 0; i < Mask.size(); ++i) {
2878 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
2880 SplatElem = Mask[i];
2886 /// Some targets have expensive vector shifts if the lanes aren't all the same
2887 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
2888 /// it's often worth sinking a shufflevector splat down to its use so that
2889 /// codegen can spot all lanes are identical.
2890 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
2891 BasicBlock *DefBB = SVI->getParent();
2893 // Only do this xform if variable vector shifts are particularly expensive.
2894 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
2897 // We only expect better codegen by sinking a shuffle if we can recognise a
2899 if (!isBroadcastShuffle(SVI))
2902 // InsertedShuffles - Only insert a shuffle in each block once.
2903 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
2905 bool MadeChange = false;
2906 for (User *U : SVI->users()) {
2907 Instruction *UI = cast<Instruction>(U);
2909 // Figure out which BB this ext is used in.
2910 BasicBlock *UserBB = UI->getParent();
2911 if (UserBB == DefBB) continue;
2913 // For now only apply this when the splat is used by a shift instruction.
2914 if (!UI->isShift()) continue;
2916 // Everything checks out, sink the shuffle if the user's block doesn't
2917 // already have a copy.
2918 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
2920 if (!InsertedShuffle) {
2921 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2922 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
2924 SVI->getOperand(2), "", InsertPt);
2927 UI->replaceUsesOfWith(SVI, InsertedShuffle);
2931 // If we removed all uses, nuke the shuffle.
2932 if (SVI->use_empty()) {
2933 SVI->eraseFromParent();
2940 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
2941 if (PHINode *P = dyn_cast<PHINode>(I)) {
2942 // It is possible for very late stage optimizations (such as SimplifyCFG)
2943 // to introduce PHI nodes too late to be cleaned up. If we detect such a
2944 // trivial PHI, go ahead and zap it here.
2945 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2947 P->replaceAllUsesWith(V);
2948 P->eraseFromParent();
2955 if (CastInst *CI = dyn_cast<CastInst>(I)) {
2956 // If the source of the cast is a constant, then this should have
2957 // already been constant folded. The only reason NOT to constant fold
2958 // it is if something (e.g. LSR) was careful to place the constant
2959 // evaluation in a block other than then one that uses it (e.g. to hoist
2960 // the address of globals out of a loop). If this is the case, we don't
2961 // want to forward-subst the cast.
2962 if (isa<Constant>(CI->getOperand(0)))
2965 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2968 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
2969 /// Sink a zext or sext into its user blocks if the target type doesn't
2970 /// fit in one register
2971 if (TLI && TLI->getTypeAction(CI->getContext(),
2972 TLI->getValueType(CI->getType())) ==
2973 TargetLowering::TypeExpandInteger) {
2974 return SinkCast(CI);
2976 bool MadeChange = MoveExtToFormExtLoad(I);
2977 return MadeChange | OptimizeExtUses(I);
2983 if (CmpInst *CI = dyn_cast<CmpInst>(I))
2984 if (!TLI || !TLI->hasMultipleConditionRegisters())
2985 return OptimizeCmpExpression(CI);
2987 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2989 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2993 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
2995 return OptimizeMemoryInst(I, SI->getOperand(1),
2996 SI->getOperand(0)->getType());
3000 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3001 if (GEPI->hasAllZeroIndices()) {
3002 /// The GEP operand must be a pointer, so must its result -> BitCast
3003 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3004 GEPI->getName(), GEPI);
3005 GEPI->replaceAllUsesWith(NC);
3006 GEPI->eraseFromParent();
3014 if (CallInst *CI = dyn_cast<CallInst>(I))
3015 return OptimizeCallInst(CI);
3017 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3018 return OptimizeSelectInst(SI);
3020 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3021 return OptimizeShuffleVectorInst(SVI);
3026 // In this pass we look for GEP and cast instructions that are used
3027 // across basic blocks and rewrite them to improve basic-block-at-a-time
3029 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3031 bool MadeChange = false;
3033 CurInstIterator = BB.begin();
3034 while (CurInstIterator != BB.end())
3035 MadeChange |= OptimizeInst(CurInstIterator++);
3037 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3042 // llvm.dbg.value is far away from the value then iSel may not be able
3043 // handle it properly. iSel will drop llvm.dbg.value if it can not
3044 // find a node corresponding to the value.
3045 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3046 bool MadeChange = false;
3047 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3048 Instruction *PrevNonDbgInst = NULL;
3049 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3050 Instruction *Insn = BI; ++BI;
3051 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3053 PrevNonDbgInst = Insn;
3057 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3058 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3059 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3060 DVI->removeFromParent();
3061 if (isa<PHINode>(VI))
3062 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3064 DVI->insertAfter(VI);
3073 // If there is a sequence that branches based on comparing a single bit
3074 // against zero that can be combined into a single instruction, and the
3075 // target supports folding these into a single instruction, sink the
3076 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3077 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3079 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3080 if (!EnableAndCmpSinking)
3082 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3084 bool MadeChange = false;
3085 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3086 BasicBlock *BB = I++;
3088 // Does this BB end with the following?
3089 // %andVal = and %val, #single-bit-set
3090 // %icmpVal = icmp %andResult, 0
3091 // br i1 %cmpVal label %dest1, label %dest2"
3092 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3093 if (!Brcc || !Brcc->isConditional())
3095 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3096 if (!Cmp || Cmp->getParent() != BB)
3098 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3099 if (!Zero || !Zero->isZero())
3101 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3102 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3104 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3105 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3107 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3109 // Push the "and; icmp" for any users that are conditional branches.
3110 // Since there can only be one branch use per BB, we don't need to keep
3111 // track of which BBs we insert into.
3112 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3116 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3118 if (!BrccUser || !BrccUser->isConditional())
3120 BasicBlock *UserBB = BrccUser->getParent();
3121 if (UserBB == BB) continue;
3122 DEBUG(dbgs() << "found Brcc use\n");
3124 // Sink the "and; icmp" to use.
3126 BinaryOperator *NewAnd =
3127 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3130 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3134 DEBUG(BrccUser->getParent()->dump());