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 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetTransformInfo.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/MDBuilder.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/IR/ValueMap.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
47 #include "llvm/Transforms/Utils/Local.h"
49 using namespace llvm::PatternMatch;
51 #define DEBUG_TYPE "codegenprepare"
53 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
54 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
55 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
56 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
58 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
60 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
61 "computations were sunk");
62 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
63 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
64 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
65 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
66 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
67 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
68 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
70 static cl::opt<bool> DisableBranchOpts(
71 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
72 cl::desc("Disable branch optimizations in CodeGenPrepare"));
74 static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
78 static cl::opt<bool> AddrSinkUsingGEPs(
79 "addr-sink-using-gep", cl::Hidden, cl::init(false),
80 cl::desc("Address sinking in CGP using GEPs."));
82 static cl::opt<bool> EnableAndCmpSinking(
83 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
84 cl::desc("Enable sinkinig and/cmp into branches."));
86 static cl::opt<bool> DisableStoreExtract(
87 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
88 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
90 static cl::opt<bool> StressStoreExtract(
91 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
92 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
94 static cl::opt<bool> DisableExtLdPromotion(
95 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
96 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
99 static cl::opt<bool> StressExtLdPromotion(
100 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
101 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
102 "optimization in CodeGenPrepare"));
105 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
109 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
111 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
112 class TypePromotionTransaction;
114 class CodeGenPrepare : public FunctionPass {
115 /// TLI - Keep a pointer of a TargetLowering to consult for determining
116 /// transformation profitability.
117 const TargetMachine *TM;
118 const TargetLowering *TLI;
119 const TargetTransformInfo *TTI;
120 const TargetLibraryInfo *TLInfo;
123 /// CurInstIterator - As we scan instructions optimizing them, this is the
124 /// next instruction to optimize. Xforms that can invalidate this should
126 BasicBlock::iterator CurInstIterator;
128 /// Keeps track of non-local addresses that have been sunk into a block.
129 /// This allows us to avoid inserting duplicate code for blocks with
130 /// multiple load/stores of the same address.
131 ValueMap<Value*, Value*> SunkAddrs;
133 /// Keeps track of all truncates inserted for the current function.
134 SetOfInstrs InsertedTruncsSet;
135 /// Keeps track of the type of the related instruction before their
136 /// promotion for the current function.
137 InstrToOrigTy PromotedInsts;
139 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
143 /// OptSize - True if optimizing for size.
147 static char ID; // Pass identification, replacement for typeid
148 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
149 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
150 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
152 bool runOnFunction(Function &F) override;
154 const char *getPassName() const override { return "CodeGen Prepare"; }
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
157 AU.addPreserved<DominatorTreeWrapperPass>();
158 AU.addRequired<TargetLibraryInfo>();
159 AU.addRequired<TargetTransformInfo>();
163 bool EliminateFallThrough(Function &F);
164 bool EliminateMostlyEmptyBlocks(Function &F);
165 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
166 void EliminateMostlyEmptyBlock(BasicBlock *BB);
167 bool OptimizeBlock(BasicBlock &BB);
168 bool OptimizeInst(Instruction *I);
169 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
170 bool OptimizeInlineAsmInst(CallInst *CS);
171 bool OptimizeCallInst(CallInst *CI);
172 bool MoveExtToFormExtLoad(Instruction *&I);
173 bool OptimizeExtUses(Instruction *I);
174 bool OptimizeSelectInst(SelectInst *SI);
175 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
176 bool OptimizeExtractElementInst(Instruction *Inst);
177 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
178 bool PlaceDbgValues(Function &F);
179 bool sinkAndCmp(Function &F);
180 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
182 const SmallVectorImpl<Instruction *> &Exts,
183 unsigned CreatedInst);
184 bool splitBranchCondition(Function &F);
188 char CodeGenPrepare::ID = 0;
189 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
190 "Optimize for code generation", false, false)
192 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
193 return new CodeGenPrepare(TM);
196 bool CodeGenPrepare::runOnFunction(Function &F) {
197 if (skipOptnoneFunction(F))
200 bool EverMadeChange = false;
201 // Clear per function information.
202 InsertedTruncsSet.clear();
203 PromotedInsts.clear();
207 TLI = TM->getSubtargetImpl()->getTargetLowering();
208 TLInfo = &getAnalysis<TargetLibraryInfo>();
209 TTI = &getAnalysis<TargetTransformInfo>();
210 DominatorTreeWrapperPass *DTWP =
211 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
212 DT = DTWP ? &DTWP->getDomTree() : nullptr;
213 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
214 Attribute::OptimizeForSize);
216 /// This optimization identifies DIV instructions that can be
217 /// profitably bypassed and carried out with a shorter, faster divide.
218 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
219 const DenseMap<unsigned int, unsigned int> &BypassWidths =
220 TLI->getBypassSlowDivWidths();
221 for (Function::iterator I = F.begin(); I != F.end(); I++)
222 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
225 // Eliminate blocks that contain only PHI nodes and an
226 // unconditional branch.
227 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
229 // llvm.dbg.value is far away from the value then iSel may not be able
230 // handle it properly. iSel will drop llvm.dbg.value if it can not
231 // find a node corresponding to the value.
232 EverMadeChange |= PlaceDbgValues(F);
234 // If there is a mask, compare against zero, and branch that can be combined
235 // into a single target instruction, push the mask and compare into branch
236 // users. Do this before OptimizeBlock -> OptimizeInst ->
237 // OptimizeCmpExpression, which perturbs the pattern being searched for.
238 if (!DisableBranchOpts) {
239 EverMadeChange |= sinkAndCmp(F);
240 EverMadeChange |= splitBranchCondition(F);
243 bool MadeChange = true;
246 for (Function::iterator I = F.begin(); I != F.end(); ) {
247 BasicBlock *BB = I++;
248 MadeChange |= OptimizeBlock(*BB);
250 EverMadeChange |= MadeChange;
255 if (!DisableBranchOpts) {
257 SmallPtrSet<BasicBlock*, 8> WorkList;
258 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
259 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
260 MadeChange |= ConstantFoldTerminator(BB, true);
261 if (!MadeChange) continue;
263 for (SmallVectorImpl<BasicBlock*>::iterator
264 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
265 if (pred_begin(*II) == pred_end(*II))
266 WorkList.insert(*II);
269 // Delete the dead blocks and any of their dead successors.
270 MadeChange |= !WorkList.empty();
271 while (!WorkList.empty()) {
272 BasicBlock *BB = *WorkList.begin();
274 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
278 for (SmallVectorImpl<BasicBlock*>::iterator
279 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
280 if (pred_begin(*II) == pred_end(*II))
281 WorkList.insert(*II);
284 // Merge pairs of basic blocks with unconditional branches, connected by
286 if (EverMadeChange || MadeChange)
287 MadeChange |= EliminateFallThrough(F);
291 EverMadeChange |= MadeChange;
294 if (ModifiedDT && DT)
297 return EverMadeChange;
300 /// EliminateFallThrough - Merge basic blocks which are connected
301 /// by a single edge, where one of the basic blocks has a single successor
302 /// pointing to the other basic block, which has a single predecessor.
303 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
304 bool Changed = false;
305 // Scan all of the blocks in the function, except for the entry block.
306 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
307 BasicBlock *BB = I++;
308 // If the destination block has a single pred, then this is a trivial
309 // edge, just collapse it.
310 BasicBlock *SinglePred = BB->getSinglePredecessor();
312 // Don't merge if BB's address is taken.
313 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
315 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
316 if (Term && !Term->isConditional()) {
318 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
319 // Remember if SinglePred was the entry block of the function.
320 // If so, we will need to move BB back to the entry position.
321 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
322 MergeBasicBlockIntoOnlyPred(BB, this);
324 if (isEntry && BB != &BB->getParent()->getEntryBlock())
325 BB->moveBefore(&BB->getParent()->getEntryBlock());
327 // We have erased a block. Update the iterator.
334 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
335 /// debug info directives, and an unconditional branch. Passes before isel
336 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
337 /// isel. Start by eliminating these blocks so we can split them the way we
339 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
340 bool MadeChange = false;
341 // Note that this intentionally skips the entry block.
342 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
343 BasicBlock *BB = I++;
345 // If this block doesn't end with an uncond branch, ignore it.
346 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
347 if (!BI || !BI->isUnconditional())
350 // If the instruction before the branch (skipping debug info) isn't a phi
351 // node, then other stuff is happening here.
352 BasicBlock::iterator BBI = BI;
353 if (BBI != BB->begin()) {
355 while (isa<DbgInfoIntrinsic>(BBI)) {
356 if (BBI == BB->begin())
360 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
364 // Do not break infinite loops.
365 BasicBlock *DestBB = BI->getSuccessor(0);
369 if (!CanMergeBlocks(BB, DestBB))
372 EliminateMostlyEmptyBlock(BB);
378 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
379 /// single uncond branch between them, and BB contains no other non-phi
381 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
382 const BasicBlock *DestBB) const {
383 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
384 // the successor. If there are more complex condition (e.g. preheaders),
385 // don't mess around with them.
386 BasicBlock::const_iterator BBI = BB->begin();
387 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
388 for (const User *U : PN->users()) {
389 const Instruction *UI = cast<Instruction>(U);
390 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
392 // If User is inside DestBB block and it is a PHINode then check
393 // incoming value. If incoming value is not from BB then this is
394 // a complex condition (e.g. preheaders) we want to avoid here.
395 if (UI->getParent() == DestBB) {
396 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
397 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
398 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
399 if (Insn && Insn->getParent() == BB &&
400 Insn->getParent() != UPN->getIncomingBlock(I))
407 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
408 // and DestBB may have conflicting incoming values for the block. If so, we
409 // can't merge the block.
410 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
411 if (!DestBBPN) return true; // no conflict.
413 // Collect the preds of BB.
414 SmallPtrSet<const BasicBlock*, 16> BBPreds;
415 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
416 // It is faster to get preds from a PHI than with pred_iterator.
417 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
418 BBPreds.insert(BBPN->getIncomingBlock(i));
420 BBPreds.insert(pred_begin(BB), pred_end(BB));
423 // Walk the preds of DestBB.
424 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
425 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
426 if (BBPreds.count(Pred)) { // Common predecessor?
427 BBI = DestBB->begin();
428 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
429 const Value *V1 = PN->getIncomingValueForBlock(Pred);
430 const Value *V2 = PN->getIncomingValueForBlock(BB);
432 // If V2 is a phi node in BB, look up what the mapped value will be.
433 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
434 if (V2PN->getParent() == BB)
435 V2 = V2PN->getIncomingValueForBlock(Pred);
437 // If there is a conflict, bail out.
438 if (V1 != V2) return false;
447 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
448 /// an unconditional branch in it.
449 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
450 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
451 BasicBlock *DestBB = BI->getSuccessor(0);
453 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
455 // If the destination block has a single pred, then this is a trivial edge,
457 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
458 if (SinglePred != DestBB) {
459 // Remember if SinglePred was the entry block of the function. If so, we
460 // will need to move BB back to the entry position.
461 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
462 MergeBasicBlockIntoOnlyPred(DestBB, this);
464 if (isEntry && BB != &BB->getParent()->getEntryBlock())
465 BB->moveBefore(&BB->getParent()->getEntryBlock());
467 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
472 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
473 // to handle the new incoming edges it is about to have.
475 for (BasicBlock::iterator BBI = DestBB->begin();
476 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
477 // Remove the incoming value for BB, and remember it.
478 Value *InVal = PN->removeIncomingValue(BB, false);
480 // Two options: either the InVal is a phi node defined in BB or it is some
481 // value that dominates BB.
482 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
483 if (InValPhi && InValPhi->getParent() == BB) {
484 // Add all of the input values of the input PHI as inputs of this phi.
485 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
486 PN->addIncoming(InValPhi->getIncomingValue(i),
487 InValPhi->getIncomingBlock(i));
489 // Otherwise, add one instance of the dominating value for each edge that
490 // we will be adding.
491 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
492 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
493 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
495 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
496 PN->addIncoming(InVal, *PI);
501 // The PHIs are now updated, change everything that refers to BB to use
502 // DestBB and remove BB.
503 BB->replaceAllUsesWith(DestBB);
504 if (DT && !ModifiedDT) {
505 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
506 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
507 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
508 DT->changeImmediateDominator(DestBB, NewIDom);
511 BB->eraseFromParent();
514 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
517 /// SinkCast - Sink the specified cast instruction into its user blocks
518 static bool SinkCast(CastInst *CI) {
519 BasicBlock *DefBB = CI->getParent();
521 /// InsertedCasts - Only insert a cast in each block once.
522 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
524 bool MadeChange = false;
525 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
527 Use &TheUse = UI.getUse();
528 Instruction *User = cast<Instruction>(*UI);
530 // Figure out which BB this cast is used in. For PHI's this is the
531 // appropriate predecessor block.
532 BasicBlock *UserBB = User->getParent();
533 if (PHINode *PN = dyn_cast<PHINode>(User)) {
534 UserBB = PN->getIncomingBlock(TheUse);
537 // Preincrement use iterator so we don't invalidate it.
540 // If this user is in the same block as the cast, don't change the cast.
541 if (UserBB == DefBB) continue;
543 // If we have already inserted a cast into this block, use it.
544 CastInst *&InsertedCast = InsertedCasts[UserBB];
547 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
549 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
554 // Replace a use of the cast with a use of the new cast.
555 TheUse = InsertedCast;
559 // If we removed all uses, nuke the cast.
560 if (CI->use_empty()) {
561 CI->eraseFromParent();
568 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
569 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
570 /// sink it into user blocks to reduce the number of virtual
571 /// registers that must be created and coalesced.
573 /// Return true if any changes are made.
575 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
576 // If this is a noop copy,
577 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
578 EVT DstVT = TLI.getValueType(CI->getType());
580 // This is an fp<->int conversion?
581 if (SrcVT.isInteger() != DstVT.isInteger())
584 // If this is an extension, it will be a zero or sign extension, which
586 if (SrcVT.bitsLT(DstVT)) return false;
588 // If these values will be promoted, find out what they will be promoted
589 // to. This helps us consider truncates on PPC as noop copies when they
591 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
592 TargetLowering::TypePromoteInteger)
593 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
594 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
595 TargetLowering::TypePromoteInteger)
596 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
598 // If, after promotion, these are the same types, this is a noop copy.
605 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
606 /// the number of virtual registers that must be created and coalesced. This is
607 /// a clear win except on targets with multiple condition code registers
608 /// (PowerPC), where it might lose; some adjustment may be wanted there.
610 /// Return true if any changes are made.
611 static bool OptimizeCmpExpression(CmpInst *CI) {
612 BasicBlock *DefBB = CI->getParent();
614 /// InsertedCmp - Only insert a cmp in each block once.
615 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
617 bool MadeChange = false;
618 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
620 Use &TheUse = UI.getUse();
621 Instruction *User = cast<Instruction>(*UI);
623 // Preincrement use iterator so we don't invalidate it.
626 // Don't bother for PHI nodes.
627 if (isa<PHINode>(User))
630 // Figure out which BB this cmp is used in.
631 BasicBlock *UserBB = User->getParent();
633 // If this user is in the same block as the cmp, don't change the cmp.
634 if (UserBB == DefBB) continue;
636 // If we have already inserted a cmp into this block, use it.
637 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
640 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
642 CmpInst::Create(CI->getOpcode(),
643 CI->getPredicate(), CI->getOperand(0),
644 CI->getOperand(1), "", InsertPt);
648 // Replace a use of the cmp with a use of the new cmp.
649 TheUse = InsertedCmp;
653 // If we removed all uses, nuke the cmp.
655 CI->eraseFromParent();
660 /// isExtractBitsCandidateUse - Check if the candidates could
661 /// be combined with shift instruction, which includes:
662 /// 1. Truncate instruction
663 /// 2. And instruction and the imm is a mask of the low bits:
664 /// imm & (imm+1) == 0
665 static bool isExtractBitsCandidateUse(Instruction *User) {
666 if (!isa<TruncInst>(User)) {
667 if (User->getOpcode() != Instruction::And ||
668 !isa<ConstantInt>(User->getOperand(1)))
671 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
673 if ((Cimm & (Cimm + 1)).getBoolValue())
679 /// SinkShiftAndTruncate - sink both shift and truncate instruction
680 /// to the use of truncate's BB.
682 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
683 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
684 const TargetLowering &TLI) {
685 BasicBlock *UserBB = User->getParent();
686 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
687 TruncInst *TruncI = dyn_cast<TruncInst>(User);
688 bool MadeChange = false;
690 for (Value::user_iterator TruncUI = TruncI->user_begin(),
691 TruncE = TruncI->user_end();
692 TruncUI != TruncE;) {
694 Use &TruncTheUse = TruncUI.getUse();
695 Instruction *TruncUser = cast<Instruction>(*TruncUI);
696 // Preincrement use iterator so we don't invalidate it.
700 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
704 // If the use is actually a legal node, there will not be an
705 // implicit truncate.
706 // FIXME: always querying the result type is just an
707 // approximation; some nodes' legality is determined by the
708 // operand or other means. There's no good way to find out though.
709 if (TLI.isOperationLegalOrCustom(
710 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
713 // Don't bother for PHI nodes.
714 if (isa<PHINode>(TruncUser))
717 BasicBlock *TruncUserBB = TruncUser->getParent();
719 if (UserBB == TruncUserBB)
722 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
723 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
725 if (!InsertedShift && !InsertedTrunc) {
726 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
728 if (ShiftI->getOpcode() == Instruction::AShr)
730 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
733 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
736 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
739 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
740 TruncI->getType(), "", TruncInsertPt);
744 TruncTheUse = InsertedTrunc;
750 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
751 /// the uses could potentially be combined with this shift instruction and
752 /// generate BitExtract instruction. It will only be applied if the architecture
753 /// supports BitExtract instruction. Here is an example:
755 /// %x.extract.shift = lshr i64 %arg1, 32
757 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
761 /// %x.extract.shift.1 = lshr i64 %arg1, 32
762 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
764 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
766 /// Return true if any changes are made.
767 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
768 const TargetLowering &TLI) {
769 BasicBlock *DefBB = ShiftI->getParent();
771 /// Only insert instructions in each block once.
772 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
774 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
776 bool MadeChange = false;
777 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
779 Use &TheUse = UI.getUse();
780 Instruction *User = cast<Instruction>(*UI);
781 // Preincrement use iterator so we don't invalidate it.
784 // Don't bother for PHI nodes.
785 if (isa<PHINode>(User))
788 if (!isExtractBitsCandidateUse(User))
791 BasicBlock *UserBB = User->getParent();
793 if (UserBB == DefBB) {
794 // If the shift and truncate instruction are in the same BB. The use of
795 // the truncate(TruncUse) may still introduce another truncate if not
796 // legal. In this case, we would like to sink both shift and truncate
797 // instruction to the BB of TruncUse.
800 // i64 shift.result = lshr i64 opnd, imm
801 // trunc.result = trunc shift.result to i16
804 // ----> We will have an implicit truncate here if the architecture does
805 // not have i16 compare.
806 // cmp i16 trunc.result, opnd2
808 if (isa<TruncInst>(User) && shiftIsLegal
809 // If the type of the truncate is legal, no trucate will be
810 // introduced in other basic blocks.
811 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
813 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
817 // If we have already inserted a shift into this block, use it.
818 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
820 if (!InsertedShift) {
821 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
823 if (ShiftI->getOpcode() == Instruction::AShr)
825 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
828 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
833 // Replace a use of the shift with a use of the new shift.
834 TheUse = InsertedShift;
837 // If we removed all uses, nuke the shift.
838 if (ShiftI->use_empty())
839 ShiftI->eraseFromParent();
845 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
847 void replaceCall(Value *With) override {
848 CI->replaceAllUsesWith(With);
849 CI->eraseFromParent();
851 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
852 if (ConstantInt *SizeCI =
853 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
854 return SizeCI->isAllOnesValue();
858 } // end anonymous namespace
860 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
861 BasicBlock *BB = CI->getParent();
863 // Lower inline assembly if we can.
864 // If we found an inline asm expession, and if the target knows how to
865 // lower it to normal LLVM code, do so now.
866 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
867 if (TLI->ExpandInlineAsm(CI)) {
868 // Avoid invalidating the iterator.
869 CurInstIterator = BB->begin();
870 // Avoid processing instructions out of order, which could cause
871 // reuse before a value is defined.
875 // Sink address computing for memory operands into the block.
876 if (OptimizeInlineAsmInst(CI))
880 // Lower all uses of llvm.objectsize.*
881 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
882 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
883 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
884 Type *ReturnTy = CI->getType();
885 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
887 // Substituting this can cause recursive simplifications, which can
888 // invalidate our iterator. Use a WeakVH to hold onto it in case this
890 WeakVH IterHandle(CurInstIterator);
892 replaceAndRecursivelySimplify(CI, RetVal,
893 TLI ? TLI->getDataLayout() : nullptr,
894 TLInfo, ModifiedDT ? nullptr : DT);
896 // If the iterator instruction was recursively deleted, start over at the
897 // start of the block.
898 if (IterHandle != CurInstIterator) {
899 CurInstIterator = BB->begin();
906 SmallVector<Value*, 2> PtrOps;
908 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
909 while (!PtrOps.empty())
910 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
914 // From here on out we're working with named functions.
915 if (!CI->getCalledFunction()) return false;
917 // We'll need DataLayout from here on out.
918 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
919 if (!TD) return false;
921 // Lower all default uses of _chk calls. This is very similar
922 // to what InstCombineCalls does, but here we are only lowering calls
923 // that have the default "don't know" as the objectsize. Anything else
924 // should be left alone.
925 CodeGenPrepareFortifiedLibCalls Simplifier;
926 return Simplifier.fold(CI, TD, TLInfo);
929 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
930 /// instructions to the predecessor to enable tail call optimizations. The
931 /// case it is currently looking for is:
934 /// %tmp0 = tail call i32 @f0()
937 /// %tmp1 = tail call i32 @f1()
940 /// %tmp2 = tail call i32 @f2()
943 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
951 /// %tmp0 = tail call i32 @f0()
954 /// %tmp1 = tail call i32 @f1()
957 /// %tmp2 = tail call i32 @f2()
960 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
964 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
968 PHINode *PN = nullptr;
969 BitCastInst *BCI = nullptr;
970 Value *V = RI->getReturnValue();
972 BCI = dyn_cast<BitCastInst>(V);
974 V = BCI->getOperand(0);
976 PN = dyn_cast<PHINode>(V);
981 if (PN && PN->getParent() != BB)
984 // It's not safe to eliminate the sign / zero extension of the return value.
985 // See llvm::isInTailCallPosition().
986 const Function *F = BB->getParent();
987 AttributeSet CallerAttrs = F->getAttributes();
988 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
989 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
992 // Make sure there are no instructions between the PHI and return, or that the
993 // return is the first instruction in the block.
995 BasicBlock::iterator BI = BB->begin();
996 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
998 // Also skip over the bitcast.
1003 BasicBlock::iterator BI = BB->begin();
1004 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1009 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1011 SmallVector<CallInst*, 4> TailCalls;
1013 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1014 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1015 // Make sure the phi value is indeed produced by the tail call.
1016 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1017 TLI->mayBeEmittedAsTailCall(CI))
1018 TailCalls.push_back(CI);
1021 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1022 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1023 if (!VisitedBBs.insert(*PI).second)
1026 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1027 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1028 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1029 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1033 CallInst *CI = dyn_cast<CallInst>(&*RI);
1034 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1035 TailCalls.push_back(CI);
1039 bool Changed = false;
1040 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1041 CallInst *CI = TailCalls[i];
1044 // Conservatively require the attributes of the call to match those of the
1045 // return. Ignore noalias because it doesn't affect the call sequence.
1046 AttributeSet CalleeAttrs = CS.getAttributes();
1047 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1048 removeAttribute(Attribute::NoAlias) !=
1049 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1050 removeAttribute(Attribute::NoAlias))
1053 // Make sure the call instruction is followed by an unconditional branch to
1054 // the return block.
1055 BasicBlock *CallBB = CI->getParent();
1056 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1057 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1060 // Duplicate the return into CallBB.
1061 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1062 ModifiedDT = Changed = true;
1066 // If we eliminated all predecessors of the block, delete the block now.
1067 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1068 BB->eraseFromParent();
1073 //===----------------------------------------------------------------------===//
1074 // Memory Optimization
1075 //===----------------------------------------------------------------------===//
1079 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1080 /// which holds actual Value*'s for register values.
1081 struct ExtAddrMode : public TargetLowering::AddrMode {
1084 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1085 void print(raw_ostream &OS) const;
1088 bool operator==(const ExtAddrMode& O) const {
1089 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1090 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1091 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1096 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1102 void ExtAddrMode::print(raw_ostream &OS) const {
1103 bool NeedPlus = false;
1106 OS << (NeedPlus ? " + " : "")
1108 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1113 OS << (NeedPlus ? " + " : "")
1119 OS << (NeedPlus ? " + " : "")
1121 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1125 OS << (NeedPlus ? " + " : "")
1127 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1134 void ExtAddrMode::dump() const {
1140 /// \brief This class provides transaction based operation on the IR.
1141 /// Every change made through this class is recorded in the internal state and
1142 /// can be undone (rollback) until commit is called.
1143 class TypePromotionTransaction {
1145 /// \brief This represents the common interface of the individual transaction.
1146 /// Each class implements the logic for doing one specific modification on
1147 /// the IR via the TypePromotionTransaction.
1148 class TypePromotionAction {
1150 /// The Instruction modified.
1154 /// \brief Constructor of the action.
1155 /// The constructor performs the related action on the IR.
1156 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1158 virtual ~TypePromotionAction() {}
1160 /// \brief Undo the modification done by this action.
1161 /// When this method is called, the IR must be in the same state as it was
1162 /// before this action was applied.
1163 /// \pre Undoing the action works if and only if the IR is in the exact same
1164 /// state as it was directly after this action was applied.
1165 virtual void undo() = 0;
1167 /// \brief Advocate every change made by this action.
1168 /// When the results on the IR of the action are to be kept, it is important
1169 /// to call this function, otherwise hidden information may be kept forever.
1170 virtual void commit() {
1171 // Nothing to be done, this action is not doing anything.
1175 /// \brief Utility to remember the position of an instruction.
1176 class InsertionHandler {
1177 /// Position of an instruction.
1178 /// Either an instruction:
1179 /// - Is the first in a basic block: BB is used.
1180 /// - Has a previous instructon: PrevInst is used.
1182 Instruction *PrevInst;
1185 /// Remember whether or not the instruction had a previous instruction.
1186 bool HasPrevInstruction;
1189 /// \brief Record the position of \p Inst.
1190 InsertionHandler(Instruction *Inst) {
1191 BasicBlock::iterator It = Inst;
1192 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1193 if (HasPrevInstruction)
1194 Point.PrevInst = --It;
1196 Point.BB = Inst->getParent();
1199 /// \brief Insert \p Inst at the recorded position.
1200 void insert(Instruction *Inst) {
1201 if (HasPrevInstruction) {
1202 if (Inst->getParent())
1203 Inst->removeFromParent();
1204 Inst->insertAfter(Point.PrevInst);
1206 Instruction *Position = Point.BB->getFirstInsertionPt();
1207 if (Inst->getParent())
1208 Inst->moveBefore(Position);
1210 Inst->insertBefore(Position);
1215 /// \brief Move an instruction before another.
1216 class InstructionMoveBefore : public TypePromotionAction {
1217 /// Original position of the instruction.
1218 InsertionHandler Position;
1221 /// \brief Move \p Inst before \p Before.
1222 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1223 : TypePromotionAction(Inst), Position(Inst) {
1224 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1225 Inst->moveBefore(Before);
1228 /// \brief Move the instruction back to its original position.
1229 void undo() override {
1230 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1231 Position.insert(Inst);
1235 /// \brief Set the operand of an instruction with a new value.
1236 class OperandSetter : public TypePromotionAction {
1237 /// Original operand of the instruction.
1239 /// Index of the modified instruction.
1243 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1244 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1245 : TypePromotionAction(Inst), Idx(Idx) {
1246 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1247 << "for:" << *Inst << "\n"
1248 << "with:" << *NewVal << "\n");
1249 Origin = Inst->getOperand(Idx);
1250 Inst->setOperand(Idx, NewVal);
1253 /// \brief Restore the original value of the instruction.
1254 void undo() override {
1255 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1256 << "for: " << *Inst << "\n"
1257 << "with: " << *Origin << "\n");
1258 Inst->setOperand(Idx, Origin);
1262 /// \brief Hide the operands of an instruction.
1263 /// Do as if this instruction was not using any of its operands.
1264 class OperandsHider : public TypePromotionAction {
1265 /// The list of original operands.
1266 SmallVector<Value *, 4> OriginalValues;
1269 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1270 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1271 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1272 unsigned NumOpnds = Inst->getNumOperands();
1273 OriginalValues.reserve(NumOpnds);
1274 for (unsigned It = 0; It < NumOpnds; ++It) {
1275 // Save the current operand.
1276 Value *Val = Inst->getOperand(It);
1277 OriginalValues.push_back(Val);
1279 // We could use OperandSetter here, but that would implied an overhead
1280 // that we are not willing to pay.
1281 Inst->setOperand(It, UndefValue::get(Val->getType()));
1285 /// \brief Restore the original list of uses.
1286 void undo() override {
1287 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1288 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1289 Inst->setOperand(It, OriginalValues[It]);
1293 /// \brief Build a truncate instruction.
1294 class TruncBuilder : public TypePromotionAction {
1297 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1299 /// trunc Opnd to Ty.
1300 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1301 IRBuilder<> Builder(Opnd);
1302 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1303 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1306 /// \brief Get the built value.
1307 Value *getBuiltValue() { return Val; }
1309 /// \brief Remove the built instruction.
1310 void undo() override {
1311 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1312 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1313 IVal->eraseFromParent();
1317 /// \brief Build a sign extension instruction.
1318 class SExtBuilder : public TypePromotionAction {
1321 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1323 /// sext Opnd to Ty.
1324 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1325 : TypePromotionAction(InsertPt) {
1326 IRBuilder<> Builder(InsertPt);
1327 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1328 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1331 /// \brief Get the built value.
1332 Value *getBuiltValue() { return Val; }
1334 /// \brief Remove the built instruction.
1335 void undo() override {
1336 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1337 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1338 IVal->eraseFromParent();
1342 /// \brief Build a zero extension instruction.
1343 class ZExtBuilder : public TypePromotionAction {
1346 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1348 /// zext Opnd to Ty.
1349 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1350 : TypePromotionAction(InsertPt) {
1351 IRBuilder<> Builder(InsertPt);
1352 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1353 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1356 /// \brief Get the built value.
1357 Value *getBuiltValue() { return Val; }
1359 /// \brief Remove the built instruction.
1360 void undo() override {
1361 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1362 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1363 IVal->eraseFromParent();
1367 /// \brief Mutate an instruction to another type.
1368 class TypeMutator : public TypePromotionAction {
1369 /// Record the original type.
1373 /// \brief Mutate the type of \p Inst into \p NewTy.
1374 TypeMutator(Instruction *Inst, Type *NewTy)
1375 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1376 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1378 Inst->mutateType(NewTy);
1381 /// \brief Mutate the instruction back to its original type.
1382 void undo() override {
1383 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1385 Inst->mutateType(OrigTy);
1389 /// \brief Replace the uses of an instruction by another instruction.
1390 class UsesReplacer : public TypePromotionAction {
1391 /// Helper structure to keep track of the replaced uses.
1392 struct InstructionAndIdx {
1393 /// The instruction using the instruction.
1395 /// The index where this instruction is used for Inst.
1397 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1398 : Inst(Inst), Idx(Idx) {}
1401 /// Keep track of the original uses (pair Instruction, Index).
1402 SmallVector<InstructionAndIdx, 4> OriginalUses;
1403 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1406 /// \brief Replace all the use of \p Inst by \p New.
1407 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1408 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1410 // Record the original uses.
1411 for (Use &U : Inst->uses()) {
1412 Instruction *UserI = cast<Instruction>(U.getUser());
1413 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1415 // Now, we can replace the uses.
1416 Inst->replaceAllUsesWith(New);
1419 /// \brief Reassign the original uses of Inst to Inst.
1420 void undo() override {
1421 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1422 for (use_iterator UseIt = OriginalUses.begin(),
1423 EndIt = OriginalUses.end();
1424 UseIt != EndIt; ++UseIt) {
1425 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1430 /// \brief Remove an instruction from the IR.
1431 class InstructionRemover : public TypePromotionAction {
1432 /// Original position of the instruction.
1433 InsertionHandler Inserter;
1434 /// Helper structure to hide all the link to the instruction. In other
1435 /// words, this helps to do as if the instruction was removed.
1436 OperandsHider Hider;
1437 /// Keep track of the uses replaced, if any.
1438 UsesReplacer *Replacer;
1441 /// \brief Remove all reference of \p Inst and optinally replace all its
1443 /// \pre If !Inst->use_empty(), then New != nullptr
1444 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1445 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1448 Replacer = new UsesReplacer(Inst, New);
1449 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1450 Inst->removeFromParent();
1453 ~InstructionRemover() { delete Replacer; }
1455 /// \brief Really remove the instruction.
1456 void commit() override { delete Inst; }
1458 /// \brief Resurrect the instruction and reassign it to the proper uses if
1459 /// new value was provided when build this action.
1460 void undo() override {
1461 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1462 Inserter.insert(Inst);
1470 /// Restoration point.
1471 /// The restoration point is a pointer to an action instead of an iterator
1472 /// because the iterator may be invalidated but not the pointer.
1473 typedef const TypePromotionAction *ConstRestorationPt;
1474 /// Advocate every changes made in that transaction.
1476 /// Undo all the changes made after the given point.
1477 void rollback(ConstRestorationPt Point);
1478 /// Get the current restoration point.
1479 ConstRestorationPt getRestorationPoint() const;
1481 /// \name API for IR modification with state keeping to support rollback.
1483 /// Same as Instruction::setOperand.
1484 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1485 /// Same as Instruction::eraseFromParent.
1486 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1487 /// Same as Value::replaceAllUsesWith.
1488 void replaceAllUsesWith(Instruction *Inst, Value *New);
1489 /// Same as Value::mutateType.
1490 void mutateType(Instruction *Inst, Type *NewTy);
1491 /// Same as IRBuilder::createTrunc.
1492 Value *createTrunc(Instruction *Opnd, Type *Ty);
1493 /// Same as IRBuilder::createSExt.
1494 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1495 /// Same as IRBuilder::createZExt.
1496 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1497 /// Same as Instruction::moveBefore.
1498 void moveBefore(Instruction *Inst, Instruction *Before);
1502 /// The ordered list of actions made so far.
1503 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1504 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1507 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1510 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1513 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1516 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1519 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1521 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1524 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1525 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1528 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1530 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1531 Value *Val = Ptr->getBuiltValue();
1532 Actions.push_back(std::move(Ptr));
1536 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1537 Value *Opnd, Type *Ty) {
1538 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1539 Value *Val = Ptr->getBuiltValue();
1540 Actions.push_back(std::move(Ptr));
1544 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1545 Value *Opnd, Type *Ty) {
1546 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1547 Value *Val = Ptr->getBuiltValue();
1548 Actions.push_back(std::move(Ptr));
1552 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1553 Instruction *Before) {
1555 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1558 TypePromotionTransaction::ConstRestorationPt
1559 TypePromotionTransaction::getRestorationPoint() const {
1560 return !Actions.empty() ? Actions.back().get() : nullptr;
1563 void TypePromotionTransaction::commit() {
1564 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1570 void TypePromotionTransaction::rollback(
1571 TypePromotionTransaction::ConstRestorationPt Point) {
1572 while (!Actions.empty() && Point != Actions.back().get()) {
1573 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1578 /// \brief A helper class for matching addressing modes.
1580 /// This encapsulates the logic for matching the target-legal addressing modes.
1581 class AddressingModeMatcher {
1582 SmallVectorImpl<Instruction*> &AddrModeInsts;
1583 const TargetLowering &TLI;
1585 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1586 /// the memory instruction that we're computing this address for.
1588 Instruction *MemoryInst;
1590 /// AddrMode - This is the addressing mode that we're building up. This is
1591 /// part of the return value of this addressing mode matching stuff.
1592 ExtAddrMode &AddrMode;
1594 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1595 const SetOfInstrs &InsertedTruncs;
1596 /// A map from the instructions to their type before promotion.
1597 InstrToOrigTy &PromotedInsts;
1598 /// The ongoing transaction where every action should be registered.
1599 TypePromotionTransaction &TPT;
1601 /// IgnoreProfitability - This is set to true when we should not do
1602 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1603 /// always returns true.
1604 bool IgnoreProfitability;
1606 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1607 const TargetLowering &T, Type *AT,
1608 Instruction *MI, ExtAddrMode &AM,
1609 const SetOfInstrs &InsertedTruncs,
1610 InstrToOrigTy &PromotedInsts,
1611 TypePromotionTransaction &TPT)
1612 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1613 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1614 IgnoreProfitability = false;
1618 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1619 /// give an access type of AccessTy. This returns a list of involved
1620 /// instructions in AddrModeInsts.
1621 /// \p InsertedTruncs The truncate instruction inserted by other
1624 /// \p PromotedInsts maps the instructions to their type before promotion.
1625 /// \p The ongoing transaction where every action should be registered.
1626 static ExtAddrMode Match(Value *V, Type *AccessTy,
1627 Instruction *MemoryInst,
1628 SmallVectorImpl<Instruction*> &AddrModeInsts,
1629 const TargetLowering &TLI,
1630 const SetOfInstrs &InsertedTruncs,
1631 InstrToOrigTy &PromotedInsts,
1632 TypePromotionTransaction &TPT) {
1635 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1636 MemoryInst, Result, InsertedTruncs,
1637 PromotedInsts, TPT).MatchAddr(V, 0);
1638 (void)Success; assert(Success && "Couldn't select *anything*?");
1642 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1643 bool MatchAddr(Value *V, unsigned Depth);
1644 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1645 bool *MovedAway = nullptr);
1646 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1647 ExtAddrMode &AMBefore,
1648 ExtAddrMode &AMAfter);
1649 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1650 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1651 Value *PromotedOperand) const;
1654 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1655 /// Return true and update AddrMode if this addr mode is legal for the target,
1657 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1659 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1660 // mode. Just process that directly.
1662 return MatchAddr(ScaleReg, Depth);
1664 // If the scale is 0, it takes nothing to add this.
1668 // If we already have a scale of this value, we can add to it, otherwise, we
1669 // need an available scale field.
1670 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1673 ExtAddrMode TestAddrMode = AddrMode;
1675 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1676 // [A+B + A*7] -> [B+A*8].
1677 TestAddrMode.Scale += Scale;
1678 TestAddrMode.ScaledReg = ScaleReg;
1680 // If the new address isn't legal, bail out.
1681 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1684 // It was legal, so commit it.
1685 AddrMode = TestAddrMode;
1687 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1688 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1689 // X*Scale + C*Scale to addr mode.
1690 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1691 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1692 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1693 TestAddrMode.ScaledReg = AddLHS;
1694 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1696 // If this addressing mode is legal, commit it and remember that we folded
1697 // this instruction.
1698 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1699 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1700 AddrMode = TestAddrMode;
1705 // Otherwise, not (x+c)*scale, just return what we have.
1709 /// MightBeFoldableInst - This is a little filter, which returns true if an
1710 /// addressing computation involving I might be folded into a load/store
1711 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1712 /// the set of instructions that MatchOperationAddr can.
1713 static bool MightBeFoldableInst(Instruction *I) {
1714 switch (I->getOpcode()) {
1715 case Instruction::BitCast:
1716 case Instruction::AddrSpaceCast:
1717 // Don't touch identity bitcasts.
1718 if (I->getType() == I->getOperand(0)->getType())
1720 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1721 case Instruction::PtrToInt:
1722 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1724 case Instruction::IntToPtr:
1725 // We know the input is intptr_t, so this is foldable.
1727 case Instruction::Add:
1729 case Instruction::Mul:
1730 case Instruction::Shl:
1731 // Can only handle X*C and X << C.
1732 return isa<ConstantInt>(I->getOperand(1));
1733 case Instruction::GetElementPtr:
1740 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
1741 /// \note \p Val is assumed to be the product of some type promotion.
1742 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
1743 /// to be legal, as the non-promoted value would have had the same state.
1744 static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
1745 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
1748 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1749 // If the ISDOpcode is undefined, it was undefined before the promotion.
1752 // Otherwise, check if the promoted instruction is legal or not.
1753 return TLI.isOperationLegalOrCustom(
1754 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
1757 /// \brief Hepler class to perform type promotion.
1758 class TypePromotionHelper {
1759 /// \brief Utility function to check whether or not a sign or zero extension
1760 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1761 /// either using the operands of \p Inst or promoting \p Inst.
1762 /// The type of the extension is defined by \p IsSExt.
1763 /// In other words, check if:
1764 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
1765 /// #1 Promotion applies:
1766 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
1767 /// #2 Operand reuses:
1768 /// ext opnd1 to ConsideredExtType.
1769 /// \p PromotedInsts maps the instructions to their type before promotion.
1770 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1771 const InstrToOrigTy &PromotedInsts, bool IsSExt);
1773 /// \brief Utility function to determine if \p OpIdx should be promoted when
1774 /// promoting \p Inst.
1775 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
1776 if (isa<SelectInst>(Inst) && OpIdx == 0)
1781 /// \brief Utility function to promote the operand of \p Ext when this
1782 /// operand is a promotable trunc or sext or zext.
1783 /// \p PromotedInsts maps the instructions to their type before promotion.
1784 /// \p CreatedInsts[out] contains how many non-free instructions have been
1785 /// created to promote the operand of Ext.
1786 /// Newly added extensions are inserted in \p Exts.
1787 /// Newly added truncates are inserted in \p Truncs.
1788 /// Should never be called directly.
1789 /// \return The promoted value which is used instead of Ext.
1790 static Value *promoteOperandForTruncAndAnyExt(
1791 Instruction *Ext, TypePromotionTransaction &TPT,
1792 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
1793 SmallVectorImpl<Instruction *> *Exts,
1794 SmallVectorImpl<Instruction *> *Truncs);
1796 /// \brief Utility function to promote the operand of \p Ext when this
1797 /// operand is promotable and is not a supported trunc or sext.
1798 /// \p PromotedInsts maps the instructions to their type before promotion.
1799 /// \p CreatedInsts[out] contains how many non-free instructions have been
1800 /// created to promote the operand of Ext.
1801 /// Newly added extensions are inserted in \p Exts.
1802 /// Newly added truncates are inserted in \p Truncs.
1803 /// Should never be called directly.
1804 /// \return The promoted value which is used instead of Ext.
1806 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
1807 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
1808 SmallVectorImpl<Instruction *> *Exts,
1809 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
1811 /// \see promoteOperandForOther.
1813 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
1814 InstrToOrigTy &PromotedInsts,
1815 unsigned &CreatedInsts,
1816 SmallVectorImpl<Instruction *> *Exts,
1817 SmallVectorImpl<Instruction *> *Truncs) {
1818 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
1822 /// \see promoteOperandForOther.
1824 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
1825 InstrToOrigTy &PromotedInsts,
1826 unsigned &CreatedInsts,
1827 SmallVectorImpl<Instruction *> *Exts,
1828 SmallVectorImpl<Instruction *> *Truncs) {
1829 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
1834 /// Type for the utility function that promotes the operand of Ext.
1835 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
1836 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
1837 SmallVectorImpl<Instruction *> *Exts,
1838 SmallVectorImpl<Instruction *> *Truncs);
1839 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1840 /// action to promote the operand of \p Ext instead of using Ext.
1841 /// \return NULL if no promotable action is possible with the current
1843 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1844 /// the others CodeGenPrepare optimizations. This information is important
1845 /// because we do not want to promote these instructions as CodeGenPrepare
1846 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1847 /// \p PromotedInsts maps the instructions to their type before promotion.
1848 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1849 const TargetLowering &TLI,
1850 const InstrToOrigTy &PromotedInsts);
1853 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1854 Type *ConsideredExtType,
1855 const InstrToOrigTy &PromotedInsts,
1857 // We can always get through zext.
1858 if (isa<ZExtInst>(Inst))
1861 // sext(sext) is ok too.
1862 if (IsSExt && isa<SExtInst>(Inst))
1865 // We can get through binary operator, if it is legal. In other words, the
1866 // binary operator must have a nuw or nsw flag.
1867 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1868 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1869 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1870 (IsSExt && BinOp->hasNoSignedWrap())))
1873 // Check if we can do the following simplification.
1874 // ext(trunc(opnd)) --> ext(opnd)
1875 if (!isa<TruncInst>(Inst))
1878 Value *OpndVal = Inst->getOperand(0);
1879 // Check if we can use this operand in the extension.
1880 // If the type is larger than the result type of the extension,
1882 if (!OpndVal->getType()->isIntegerTy() ||
1883 OpndVal->getType()->getIntegerBitWidth() >
1884 ConsideredExtType->getIntegerBitWidth())
1887 // If the operand of the truncate is not an instruction, we will not have
1888 // any information on the dropped bits.
1889 // (Actually we could for constant but it is not worth the extra logic).
1890 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1894 // Check if the source of the type is narrow enough.
1895 // I.e., check that trunc just drops extended bits of the same kind of
1897 // #1 get the type of the operand and check the kind of the extended bits.
1898 const Type *OpndType;
1899 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1900 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1901 OpndType = It->second.Ty;
1902 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1903 OpndType = Opnd->getOperand(0)->getType();
1907 // #2 check that the truncate just drop extended bits.
1908 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1914 TypePromotionHelper::Action TypePromotionHelper::getAction(
1915 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1916 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1917 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1918 "Unexpected instruction type");
1919 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1920 Type *ExtTy = Ext->getType();
1921 bool IsSExt = isa<SExtInst>(Ext);
1922 // If the operand of the extension is not an instruction, we cannot
1924 // If it, check we can get through.
1925 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
1928 // Do not promote if the operand has been added by codegenprepare.
1929 // Otherwise, it means we are undoing an optimization that is likely to be
1930 // redone, thus causing potential infinite loop.
1931 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
1934 // SExt or Trunc instructions.
1935 // Return the related handler.
1936 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1937 isa<ZExtInst>(ExtOpnd))
1938 return promoteOperandForTruncAndAnyExt;
1940 // Regular instruction.
1941 // Abort early if we will have to insert non-free instructions.
1942 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
1944 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
1947 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
1948 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1949 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
1950 SmallVectorImpl<Instruction *> *Exts,
1951 SmallVectorImpl<Instruction *> *Truncs) {
1952 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1953 // get through it and this method should not be called.
1954 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1955 Value *ExtVal = SExt;
1956 if (isa<ZExtInst>(SExtOpnd)) {
1957 // Replace s|zext(zext(opnd))
1960 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1961 TPT.replaceAllUsesWith(SExt, ZExt);
1962 TPT.eraseInstruction(SExt);
1965 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1967 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1971 // Remove dead code.
1972 if (SExtOpnd->use_empty())
1973 TPT.eraseInstruction(SExtOpnd);
1975 // Check if the extension is still needed.
1976 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1977 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
1978 if (ExtInst && Exts)
1979 Exts->push_back(ExtInst);
1983 // At this point we have: ext ty opnd to ty.
1984 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1985 Value *NextVal = ExtInst->getOperand(0);
1986 TPT.eraseInstruction(ExtInst, NextVal);
1990 Value *TypePromotionHelper::promoteOperandForOther(
1991 Instruction *Ext, TypePromotionTransaction &TPT,
1992 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
1993 SmallVectorImpl<Instruction *> *Exts,
1994 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
1995 // By construction, the operand of Ext is an instruction. Otherwise we cannot
1996 // get through it and this method should not be called.
1997 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
1999 if (!ExtOpnd->hasOneUse()) {
2000 // ExtOpnd will be promoted.
2001 // All its uses, but Ext, will need to use a truncated value of the
2002 // promoted version.
2003 // Create the truncate now.
2004 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2005 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2006 ITrunc->removeFromParent();
2007 // Insert it just after the definition.
2008 ITrunc->insertAfter(ExtOpnd);
2010 Truncs->push_back(ITrunc);
2013 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2014 // Restore the operand of Ext (which has been replace by the previous call
2015 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2016 TPT.setOperand(Ext, 0, ExtOpnd);
2019 // Get through the Instruction:
2020 // 1. Update its type.
2021 // 2. Replace the uses of Ext by Inst.
2022 // 3. Extend each operand that needs to be extended.
2024 // Remember the original type of the instruction before promotion.
2025 // This is useful to know that the high bits are sign extended bits.
2026 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2027 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2029 TPT.mutateType(ExtOpnd, Ext->getType());
2031 TPT.replaceAllUsesWith(Ext, ExtOpnd);
2033 Instruction *ExtForOpnd = Ext;
2035 DEBUG(dbgs() << "Propagate Ext to operands\n");
2036 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2038 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2039 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2040 !shouldExtOperand(ExtOpnd, OpIdx)) {
2041 DEBUG(dbgs() << "No need to propagate\n");
2044 // Check if we can statically extend the operand.
2045 Value *Opnd = ExtOpnd->getOperand(OpIdx);
2046 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2047 DEBUG(dbgs() << "Statically extend\n");
2048 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2049 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2050 : Cst->getValue().zext(BitWidth);
2051 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2054 // UndefValue are typed, so we have to statically sign extend them.
2055 if (isa<UndefValue>(Opnd)) {
2056 DEBUG(dbgs() << "Statically extend\n");
2057 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2061 // Otherwise we have to explicity sign extend the operand.
2062 // Check if Ext was reused to extend an operand.
2064 // If yes, create a new one.
2065 DEBUG(dbgs() << "More operands to ext\n");
2067 cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2068 : TPT.createZExt(Ext, Opnd, Ext->getType()));
2072 Exts->push_back(ExtForOpnd);
2073 TPT.setOperand(ExtForOpnd, 0, Opnd);
2075 // Move the sign extension before the insertion point.
2076 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2077 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2078 // If more sext are required, new instructions will have to be created.
2079 ExtForOpnd = nullptr;
2081 if (ExtForOpnd == Ext) {
2082 DEBUG(dbgs() << "Extension is useless now\n");
2083 TPT.eraseInstruction(Ext);
2088 /// IsPromotionProfitable - Check whether or not promoting an instruction
2089 /// to a wider type was profitable.
2090 /// \p MatchedSize gives the number of instructions that have been matched
2091 /// in the addressing mode after the promotion was applied.
2092 /// \p SizeWithPromotion gives the number of created instructions for
2093 /// the promotion plus the number of instructions that have been
2094 /// matched in the addressing mode before the promotion.
2095 /// \p PromotedOperand is the value that has been promoted.
2096 /// \return True if the promotion is profitable, false otherwise.
2098 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2099 unsigned SizeWithPromotion,
2100 Value *PromotedOperand) const {
2101 // We folded less instructions than what we created to promote the operand.
2102 // This is not profitable.
2103 if (MatchedSize < SizeWithPromotion)
2105 if (MatchedSize > SizeWithPromotion)
2107 // The promotion is neutral but it may help folding the sign extension in
2108 // loads for instance.
2109 // Check that we did not create an illegal instruction.
2110 return isPromotedInstructionLegal(TLI, PromotedOperand);
2113 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2114 /// fold the operation into the addressing mode. If so, update the addressing
2115 /// mode and return true, otherwise return false without modifying AddrMode.
2116 /// If \p MovedAway is not NULL, it contains the information of whether or
2117 /// not AddrInst has to be folded into the addressing mode on success.
2118 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2119 /// because it has been moved away.
2120 /// Thus AddrInst must not be added in the matched instructions.
2121 /// This state can happen when AddrInst is a sext, since it may be moved away.
2122 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2123 /// not be referenced anymore.
2124 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2127 // Avoid exponential behavior on extremely deep expression trees.
2128 if (Depth >= 5) return false;
2130 // By default, all matched instructions stay in place.
2135 case Instruction::PtrToInt:
2136 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2137 return MatchAddr(AddrInst->getOperand(0), Depth);
2138 case Instruction::IntToPtr:
2139 // This inttoptr is a no-op if the integer type is pointer sized.
2140 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2141 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2142 return MatchAddr(AddrInst->getOperand(0), Depth);
2144 case Instruction::BitCast:
2145 case Instruction::AddrSpaceCast:
2146 // BitCast is always a noop, and we can handle it as long as it is
2147 // int->int or pointer->pointer (we don't want int<->fp or something).
2148 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2149 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2150 // Don't touch identity bitcasts. These were probably put here by LSR,
2151 // and we don't want to mess around with them. Assume it knows what it
2153 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2154 return MatchAddr(AddrInst->getOperand(0), Depth);
2156 case Instruction::Add: {
2157 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2158 ExtAddrMode BackupAddrMode = AddrMode;
2159 unsigned OldSize = AddrModeInsts.size();
2160 // Start a transaction at this point.
2161 // The LHS may match but not the RHS.
2162 // Therefore, we need a higher level restoration point to undo partially
2163 // matched operation.
2164 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2165 TPT.getRestorationPoint();
2167 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2168 MatchAddr(AddrInst->getOperand(0), Depth+1))
2171 // Restore the old addr mode info.
2172 AddrMode = BackupAddrMode;
2173 AddrModeInsts.resize(OldSize);
2174 TPT.rollback(LastKnownGood);
2176 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2177 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2178 MatchAddr(AddrInst->getOperand(1), Depth+1))
2181 // Otherwise we definitely can't merge the ADD in.
2182 AddrMode = BackupAddrMode;
2183 AddrModeInsts.resize(OldSize);
2184 TPT.rollback(LastKnownGood);
2187 //case Instruction::Or:
2188 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2190 case Instruction::Mul:
2191 case Instruction::Shl: {
2192 // Can only handle X*C and X << C.
2193 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2196 int64_t Scale = RHS->getSExtValue();
2197 if (Opcode == Instruction::Shl)
2198 Scale = 1LL << Scale;
2200 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2202 case Instruction::GetElementPtr: {
2203 // Scan the GEP. We check it if it contains constant offsets and at most
2204 // one variable offset.
2205 int VariableOperand = -1;
2206 unsigned VariableScale = 0;
2208 int64_t ConstantOffset = 0;
2209 const DataLayout *TD = TLI.getDataLayout();
2210 gep_type_iterator GTI = gep_type_begin(AddrInst);
2211 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2212 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2213 const StructLayout *SL = TD->getStructLayout(STy);
2215 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2216 ConstantOffset += SL->getElementOffset(Idx);
2218 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2219 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2220 ConstantOffset += CI->getSExtValue()*TypeSize;
2221 } else if (TypeSize) { // Scales of zero don't do anything.
2222 // We only allow one variable index at the moment.
2223 if (VariableOperand != -1)
2226 // Remember the variable index.
2227 VariableOperand = i;
2228 VariableScale = TypeSize;
2233 // A common case is for the GEP to only do a constant offset. In this case,
2234 // just add it to the disp field and check validity.
2235 if (VariableOperand == -1) {
2236 AddrMode.BaseOffs += ConstantOffset;
2237 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2238 // Check to see if we can fold the base pointer in too.
2239 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2242 AddrMode.BaseOffs -= ConstantOffset;
2246 // Save the valid addressing mode in case we can't match.
2247 ExtAddrMode BackupAddrMode = AddrMode;
2248 unsigned OldSize = AddrModeInsts.size();
2250 // See if the scale and offset amount is valid for this target.
2251 AddrMode.BaseOffs += ConstantOffset;
2253 // Match the base operand of the GEP.
2254 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2255 // If it couldn't be matched, just stuff the value in a register.
2256 if (AddrMode.HasBaseReg) {
2257 AddrMode = BackupAddrMode;
2258 AddrModeInsts.resize(OldSize);
2261 AddrMode.HasBaseReg = true;
2262 AddrMode.BaseReg = AddrInst->getOperand(0);
2265 // Match the remaining variable portion of the GEP.
2266 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2268 // If it couldn't be matched, try stuffing the base into a register
2269 // instead of matching it, and retrying the match of the scale.
2270 AddrMode = BackupAddrMode;
2271 AddrModeInsts.resize(OldSize);
2272 if (AddrMode.HasBaseReg)
2274 AddrMode.HasBaseReg = true;
2275 AddrMode.BaseReg = AddrInst->getOperand(0);
2276 AddrMode.BaseOffs += ConstantOffset;
2277 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2278 VariableScale, Depth)) {
2279 // If even that didn't work, bail.
2280 AddrMode = BackupAddrMode;
2281 AddrModeInsts.resize(OldSize);
2288 case Instruction::SExt:
2289 case Instruction::ZExt: {
2290 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2294 // Try to move this ext out of the way of the addressing mode.
2295 // Ask for a method for doing so.
2296 TypePromotionHelper::Action TPH =
2297 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2301 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2302 TPT.getRestorationPoint();
2303 unsigned CreatedInsts = 0;
2304 Value *PromotedOperand =
2305 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
2306 // SExt has been moved away.
2307 // Thus either it will be rematched later in the recursive calls or it is
2308 // gone. Anyway, we must not fold it into the addressing mode at this point.
2312 // addr = gep base, idx
2314 // promotedOpnd = ext opnd <- no match here
2315 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2316 // addr = gep base, op <- match
2320 assert(PromotedOperand &&
2321 "TypePromotionHelper should have filtered out those cases");
2323 ExtAddrMode BackupAddrMode = AddrMode;
2324 unsigned OldSize = AddrModeInsts.size();
2326 if (!MatchAddr(PromotedOperand, Depth) ||
2327 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2329 AddrMode = BackupAddrMode;
2330 AddrModeInsts.resize(OldSize);
2331 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2332 TPT.rollback(LastKnownGood);
2341 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2342 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2343 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2344 /// or intptr_t for the target.
2346 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2347 // Start a transaction at this point that we will rollback if the matching
2349 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2350 TPT.getRestorationPoint();
2351 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2352 // Fold in immediates if legal for the target.
2353 AddrMode.BaseOffs += CI->getSExtValue();
2354 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2356 AddrMode.BaseOffs -= CI->getSExtValue();
2357 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2358 // If this is a global variable, try to fold it into the addressing mode.
2359 if (!AddrMode.BaseGV) {
2360 AddrMode.BaseGV = GV;
2361 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2363 AddrMode.BaseGV = nullptr;
2365 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2366 ExtAddrMode BackupAddrMode = AddrMode;
2367 unsigned OldSize = AddrModeInsts.size();
2369 // Check to see if it is possible to fold this operation.
2370 bool MovedAway = false;
2371 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2372 // This instruction may have been move away. If so, there is nothing
2376 // Okay, it's possible to fold this. Check to see if it is actually
2377 // *profitable* to do so. We use a simple cost model to avoid increasing
2378 // register pressure too much.
2379 if (I->hasOneUse() ||
2380 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2381 AddrModeInsts.push_back(I);
2385 // It isn't profitable to do this, roll back.
2386 //cerr << "NOT FOLDING: " << *I;
2387 AddrMode = BackupAddrMode;
2388 AddrModeInsts.resize(OldSize);
2389 TPT.rollback(LastKnownGood);
2391 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2392 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2394 TPT.rollback(LastKnownGood);
2395 } else if (isa<ConstantPointerNull>(Addr)) {
2396 // Null pointer gets folded without affecting the addressing mode.
2400 // Worse case, the target should support [reg] addressing modes. :)
2401 if (!AddrMode.HasBaseReg) {
2402 AddrMode.HasBaseReg = true;
2403 AddrMode.BaseReg = Addr;
2404 // Still check for legality in case the target supports [imm] but not [i+r].
2405 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2407 AddrMode.HasBaseReg = false;
2408 AddrMode.BaseReg = nullptr;
2411 // If the base register is already taken, see if we can do [r+r].
2412 if (AddrMode.Scale == 0) {
2414 AddrMode.ScaledReg = Addr;
2415 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2418 AddrMode.ScaledReg = nullptr;
2421 TPT.rollback(LastKnownGood);
2425 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2426 /// inline asm call are due to memory operands. If so, return true, otherwise
2428 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2429 const TargetLowering &TLI) {
2430 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2431 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2432 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2434 // Compute the constraint code and ConstraintType to use.
2435 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2437 // If this asm operand is our Value*, and if it isn't an indirect memory
2438 // operand, we can't fold it!
2439 if (OpInfo.CallOperandVal == OpVal &&
2440 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2441 !OpInfo.isIndirect))
2448 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2449 /// memory use. If we find an obviously non-foldable instruction, return true.
2450 /// Add the ultimately found memory instructions to MemoryUses.
2451 static bool FindAllMemoryUses(Instruction *I,
2452 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2453 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2454 const TargetLowering &TLI) {
2455 // If we already considered this instruction, we're done.
2456 if (!ConsideredInsts.insert(I).second)
2459 // If this is an obviously unfoldable instruction, bail out.
2460 if (!MightBeFoldableInst(I))
2463 // Loop over all the uses, recursively processing them.
2464 for (Use &U : I->uses()) {
2465 Instruction *UserI = cast<Instruction>(U.getUser());
2467 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2468 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2472 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2473 unsigned opNo = U.getOperandNo();
2474 if (opNo == 0) return true; // Storing addr, not into addr.
2475 MemoryUses.push_back(std::make_pair(SI, opNo));
2479 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2480 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2481 if (!IA) return true;
2483 // If this is a memory operand, we're cool, otherwise bail out.
2484 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2489 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2496 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2497 /// the use site that we're folding it into. If so, there is no cost to
2498 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2499 /// that we know are live at the instruction already.
2500 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2501 Value *KnownLive2) {
2502 // If Val is either of the known-live values, we know it is live!
2503 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2506 // All values other than instructions and arguments (e.g. constants) are live.
2507 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2509 // If Val is a constant sized alloca in the entry block, it is live, this is
2510 // true because it is just a reference to the stack/frame pointer, which is
2511 // live for the whole function.
2512 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2513 if (AI->isStaticAlloca())
2516 // Check to see if this value is already used in the memory instruction's
2517 // block. If so, it's already live into the block at the very least, so we
2518 // can reasonably fold it.
2519 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2522 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2523 /// mode of the machine to fold the specified instruction into a load or store
2524 /// that ultimately uses it. However, the specified instruction has multiple
2525 /// uses. Given this, it may actually increase register pressure to fold it
2526 /// into the load. For example, consider this code:
2530 /// use(Y) -> nonload/store
2534 /// In this case, Y has multiple uses, and can be folded into the load of Z
2535 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2536 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2537 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2538 /// number of computations either.
2540 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2541 /// X was live across 'load Z' for other reasons, we actually *would* want to
2542 /// fold the addressing mode in the Z case. This would make Y die earlier.
2543 bool AddressingModeMatcher::
2544 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2545 ExtAddrMode &AMAfter) {
2546 if (IgnoreProfitability) return true;
2548 // AMBefore is the addressing mode before this instruction was folded into it,
2549 // and AMAfter is the addressing mode after the instruction was folded. Get
2550 // the set of registers referenced by AMAfter and subtract out those
2551 // referenced by AMBefore: this is the set of values which folding in this
2552 // address extends the lifetime of.
2554 // Note that there are only two potential values being referenced here,
2555 // BaseReg and ScaleReg (global addresses are always available, as are any
2556 // folded immediates).
2557 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2559 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2560 // lifetime wasn't extended by adding this instruction.
2561 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2563 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2564 ScaledReg = nullptr;
2566 // If folding this instruction (and it's subexprs) didn't extend any live
2567 // ranges, we're ok with it.
2568 if (!BaseReg && !ScaledReg)
2571 // If all uses of this instruction are ultimately load/store/inlineasm's,
2572 // check to see if their addressing modes will include this instruction. If
2573 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2575 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2576 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2577 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2578 return false; // Has a non-memory, non-foldable use!
2580 // Now that we know that all uses of this instruction are part of a chain of
2581 // computation involving only operations that could theoretically be folded
2582 // into a memory use, loop over each of these uses and see if they could
2583 // *actually* fold the instruction.
2584 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2585 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2586 Instruction *User = MemoryUses[i].first;
2587 unsigned OpNo = MemoryUses[i].second;
2589 // Get the access type of this use. If the use isn't a pointer, we don't
2590 // know what it accesses.
2591 Value *Address = User->getOperand(OpNo);
2592 if (!Address->getType()->isPointerTy())
2594 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2596 // Do a match against the root of this address, ignoring profitability. This
2597 // will tell us if the addressing mode for the memory operation will
2598 // *actually* cover the shared instruction.
2600 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2601 TPT.getRestorationPoint();
2602 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2603 MemoryInst, Result, InsertedTruncs,
2604 PromotedInsts, TPT);
2605 Matcher.IgnoreProfitability = true;
2606 bool Success = Matcher.MatchAddr(Address, 0);
2607 (void)Success; assert(Success && "Couldn't select *anything*?");
2609 // The match was to check the profitability, the changes made are not
2610 // part of the original matcher. Therefore, they should be dropped
2611 // otherwise the original matcher will not present the right state.
2612 TPT.rollback(LastKnownGood);
2614 // If the match didn't cover I, then it won't be shared by it.
2615 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2616 I) == MatchedAddrModeInsts.end())
2619 MatchedAddrModeInsts.clear();
2625 } // end anonymous namespace
2627 /// IsNonLocalValue - Return true if the specified values are defined in a
2628 /// different basic block than BB.
2629 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2630 if (Instruction *I = dyn_cast<Instruction>(V))
2631 return I->getParent() != BB;
2635 /// OptimizeMemoryInst - Load and Store Instructions often have
2636 /// addressing modes that can do significant amounts of computation. As such,
2637 /// instruction selection will try to get the load or store to do as much
2638 /// computation as possible for the program. The problem is that isel can only
2639 /// see within a single block. As such, we sink as much legal addressing mode
2640 /// stuff into the block as possible.
2642 /// This method is used to optimize both load/store and inline asms with memory
2644 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2648 // Try to collapse single-value PHI nodes. This is necessary to undo
2649 // unprofitable PRE transformations.
2650 SmallVector<Value*, 8> worklist;
2651 SmallPtrSet<Value*, 16> Visited;
2652 worklist.push_back(Addr);
2654 // Use a worklist to iteratively look through PHI nodes, and ensure that
2655 // the addressing mode obtained from the non-PHI roots of the graph
2657 Value *Consensus = nullptr;
2658 unsigned NumUsesConsensus = 0;
2659 bool IsNumUsesConsensusValid = false;
2660 SmallVector<Instruction*, 16> AddrModeInsts;
2661 ExtAddrMode AddrMode;
2662 TypePromotionTransaction TPT;
2663 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2664 TPT.getRestorationPoint();
2665 while (!worklist.empty()) {
2666 Value *V = worklist.back();
2667 worklist.pop_back();
2669 // Break use-def graph loops.
2670 if (!Visited.insert(V).second) {
2671 Consensus = nullptr;
2675 // For a PHI node, push all of its incoming values.
2676 if (PHINode *P = dyn_cast<PHINode>(V)) {
2677 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2678 worklist.push_back(P->getIncomingValue(i));
2682 // For non-PHIs, determine the addressing mode being computed.
2683 SmallVector<Instruction*, 16> NewAddrModeInsts;
2684 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2685 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2686 PromotedInsts, TPT);
2688 // This check is broken into two cases with very similar code to avoid using
2689 // getNumUses() as much as possible. Some values have a lot of uses, so
2690 // calling getNumUses() unconditionally caused a significant compile-time
2694 AddrMode = NewAddrMode;
2695 AddrModeInsts = NewAddrModeInsts;
2697 } else if (NewAddrMode == AddrMode) {
2698 if (!IsNumUsesConsensusValid) {
2699 NumUsesConsensus = Consensus->getNumUses();
2700 IsNumUsesConsensusValid = true;
2703 // Ensure that the obtained addressing mode is equivalent to that obtained
2704 // for all other roots of the PHI traversal. Also, when choosing one
2705 // such root as representative, select the one with the most uses in order
2706 // to keep the cost modeling heuristics in AddressingModeMatcher
2708 unsigned NumUses = V->getNumUses();
2709 if (NumUses > NumUsesConsensus) {
2711 NumUsesConsensus = NumUses;
2712 AddrModeInsts = NewAddrModeInsts;
2717 Consensus = nullptr;
2721 // If the addressing mode couldn't be determined, or if multiple different
2722 // ones were determined, bail out now.
2724 TPT.rollback(LastKnownGood);
2729 // Check to see if any of the instructions supersumed by this addr mode are
2730 // non-local to I's BB.
2731 bool AnyNonLocal = false;
2732 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2733 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2739 // If all the instructions matched are already in this BB, don't do anything.
2741 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2745 // Insert this computation right after this user. Since our caller is
2746 // scanning from the top of the BB to the bottom, reuse of the expr are
2747 // guaranteed to happen later.
2748 IRBuilder<> Builder(MemoryInst);
2750 // Now that we determined the addressing expression we want to use and know
2751 // that we have to sink it into this block. Check to see if we have already
2752 // done this for some other load/store instr in this block. If so, reuse the
2754 Value *&SunkAddr = SunkAddrs[Addr];
2756 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2757 << *MemoryInst << "\n");
2758 if (SunkAddr->getType() != Addr->getType())
2759 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2760 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2761 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2762 // By default, we use the GEP-based method when AA is used later. This
2763 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2764 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2765 << *MemoryInst << "\n");
2766 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2767 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2769 // First, find the pointer.
2770 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2771 ResultPtr = AddrMode.BaseReg;
2772 AddrMode.BaseReg = nullptr;
2775 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2776 // We can't add more than one pointer together, nor can we scale a
2777 // pointer (both of which seem meaningless).
2778 if (ResultPtr || AddrMode.Scale != 1)
2781 ResultPtr = AddrMode.ScaledReg;
2785 if (AddrMode.BaseGV) {
2789 ResultPtr = AddrMode.BaseGV;
2792 // If the real base value actually came from an inttoptr, then the matcher
2793 // will look through it and provide only the integer value. In that case,
2795 if (!ResultPtr && AddrMode.BaseReg) {
2797 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2798 AddrMode.BaseReg = nullptr;
2799 } else if (!ResultPtr && AddrMode.Scale == 1) {
2801 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2806 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2807 SunkAddr = Constant::getNullValue(Addr->getType());
2808 } else if (!ResultPtr) {
2812 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2814 // Start with the base register. Do this first so that subsequent address
2815 // matching finds it last, which will prevent it from trying to match it
2816 // as the scaled value in case it happens to be a mul. That would be
2817 // problematic if we've sunk a different mul for the scale, because then
2818 // we'd end up sinking both muls.
2819 if (AddrMode.BaseReg) {
2820 Value *V = AddrMode.BaseReg;
2821 if (V->getType() != IntPtrTy)
2822 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2827 // Add the scale value.
2828 if (AddrMode.Scale) {
2829 Value *V = AddrMode.ScaledReg;
2830 if (V->getType() == IntPtrTy) {
2832 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2833 cast<IntegerType>(V->getType())->getBitWidth()) {
2834 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2836 // It is only safe to sign extend the BaseReg if we know that the math
2837 // required to create it did not overflow before we extend it. Since
2838 // the original IR value was tossed in favor of a constant back when
2839 // the AddrMode was created we need to bail out gracefully if widths
2840 // do not match instead of extending it.
2841 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2842 if (I && (ResultIndex != AddrMode.BaseReg))
2843 I->eraseFromParent();
2847 if (AddrMode.Scale != 1)
2848 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2851 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2856 // Add in the Base Offset if present.
2857 if (AddrMode.BaseOffs) {
2858 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2860 // We need to add this separately from the scale above to help with
2861 // SDAG consecutive load/store merging.
2862 if (ResultPtr->getType() != I8PtrTy)
2863 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2864 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2871 SunkAddr = ResultPtr;
2873 if (ResultPtr->getType() != I8PtrTy)
2874 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2875 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2878 if (SunkAddr->getType() != Addr->getType())
2879 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2882 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2883 << *MemoryInst << "\n");
2884 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2885 Value *Result = nullptr;
2887 // Start with the base register. Do this first so that subsequent address
2888 // matching finds it last, which will prevent it from trying to match it
2889 // as the scaled value in case it happens to be a mul. That would be
2890 // problematic if we've sunk a different mul for the scale, because then
2891 // we'd end up sinking both muls.
2892 if (AddrMode.BaseReg) {
2893 Value *V = AddrMode.BaseReg;
2894 if (V->getType()->isPointerTy())
2895 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2896 if (V->getType() != IntPtrTy)
2897 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2901 // Add the scale value.
2902 if (AddrMode.Scale) {
2903 Value *V = AddrMode.ScaledReg;
2904 if (V->getType() == IntPtrTy) {
2906 } else if (V->getType()->isPointerTy()) {
2907 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2908 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2909 cast<IntegerType>(V->getType())->getBitWidth()) {
2910 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2912 // It is only safe to sign extend the BaseReg if we know that the math
2913 // required to create it did not overflow before we extend it. Since
2914 // the original IR value was tossed in favor of a constant back when
2915 // the AddrMode was created we need to bail out gracefully if widths
2916 // do not match instead of extending it.
2917 Instruction *I = dyn_cast_or_null<Instruction>(Result);
2918 if (I && (Result != AddrMode.BaseReg))
2919 I->eraseFromParent();
2922 if (AddrMode.Scale != 1)
2923 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2926 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2931 // Add in the BaseGV if present.
2932 if (AddrMode.BaseGV) {
2933 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2935 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2940 // Add in the Base Offset if present.
2941 if (AddrMode.BaseOffs) {
2942 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2944 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2950 SunkAddr = Constant::getNullValue(Addr->getType());
2952 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2955 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2957 // If we have no uses, recursively delete the value and all dead instructions
2959 if (Repl->use_empty()) {
2960 // This can cause recursive deletion, which can invalidate our iterator.
2961 // Use a WeakVH to hold onto it in case this happens.
2962 WeakVH IterHandle(CurInstIterator);
2963 BasicBlock *BB = CurInstIterator->getParent();
2965 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2967 if (IterHandle != CurInstIterator) {
2968 // If the iterator instruction was recursively deleted, start over at the
2969 // start of the block.
2970 CurInstIterator = BB->begin();
2978 /// OptimizeInlineAsmInst - If there are any memory operands, use
2979 /// OptimizeMemoryInst to sink their address computing into the block when
2980 /// possible / profitable.
2981 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2982 bool MadeChange = false;
2984 TargetLowering::AsmOperandInfoVector
2985 TargetConstraints = TLI->ParseConstraints(CS);
2987 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2988 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2990 // Compute the constraint code and ConstraintType to use.
2991 TLI->ComputeConstraintToUse(OpInfo, SDValue());
2993 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2994 OpInfo.isIndirect) {
2995 Value *OpVal = CS->getArgOperand(ArgNo++);
2996 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2997 } else if (OpInfo.Type == InlineAsm::isInput)
3004 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3005 /// sign extensions.
3006 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3007 assert(!Inst->use_empty() && "Input must have at least one use");
3008 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3009 bool IsSExt = isa<SExtInst>(FirstUser);
3010 Type *ExtTy = FirstUser->getType();
3011 for (const User *U : Inst->users()) {
3012 const Instruction *UI = cast<Instruction>(U);
3013 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3015 Type *CurTy = UI->getType();
3016 // Same input and output types: Same instruction after CSE.
3020 // If IsSExt is true, we are in this situation:
3022 // b = sext ty1 a to ty2
3023 // c = sext ty1 a to ty3
3024 // Assuming ty2 is shorter than ty3, this could be turned into:
3026 // b = sext ty1 a to ty2
3027 // c = sext ty2 b to ty3
3028 // However, the last sext is not free.
3032 // This is a ZExt, maybe this is free to extend from one type to another.
3033 // In that case, we would not account for a different use.
3036 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3037 CurTy->getScalarType()->getIntegerBitWidth()) {
3045 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3048 // All uses are the same or can be derived from one another for free.
3052 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3053 /// load instruction.
3054 /// If an ext(load) can be formed, it is returned via \p LI for the load
3055 /// and \p Inst for the extension.
3056 /// Otherwise LI == nullptr and Inst == nullptr.
3057 /// When some promotion happened, \p TPT contains the proper state to
3060 /// \return true when promoting was necessary to expose the ext(load)
3061 /// opportunity, false otherwise.
3065 /// %ld = load i32* %addr
3066 /// %add = add nuw i32 %ld, 4
3067 /// %zext = zext i32 %add to i64
3071 /// %ld = load i32* %addr
3072 /// %zext = zext i32 %ld to i64
3073 /// %add = add nuw i64 %zext, 4
3075 /// Thanks to the promotion, we can match zext(load i32*) to i64.
3076 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3077 LoadInst *&LI, Instruction *&Inst,
3078 const SmallVectorImpl<Instruction *> &Exts,
3079 unsigned CreatedInsts = 0) {
3080 // Iterate over all the extensions to see if one form an ext(load).
3081 for (auto I : Exts) {
3082 // Check if we directly have ext(load).
3083 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3085 // No promotion happened here.
3088 // Check whether or not we want to do any promotion.
3089 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3091 // Get the action to perform the promotion.
3092 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3093 I, InsertedTruncsSet, *TLI, PromotedInsts);
3094 // Check if we can promote.
3097 // Save the current state.
3098 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3099 TPT.getRestorationPoint();
3100 SmallVector<Instruction *, 4> NewExts;
3101 unsigned NewCreatedInsts = 0;
3103 Value *PromotedVal =
3104 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3105 assert(PromotedVal &&
3106 "TypePromotionHelper should have filtered out those cases");
3108 // We would be able to merge only one extension in a load.
3109 // Therefore, if we have more than 1 new extension we heuristically
3110 // cut this search path, because it means we degrade the code quality.
3111 // With exactly 2, the transformation is neutral, because we will merge
3112 // one extension but leave one. However, we optimistically keep going,
3113 // because the new extension may be removed too.
3114 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3115 if (!StressExtLdPromotion &&
3116 (TotalCreatedInsts > 1 ||
3117 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3118 // The promotion is not profitable, rollback to the previous state.
3119 TPT.rollback(LastKnownGood);
3122 // The promotion is profitable.
3123 // Check if it exposes an ext(load).
3124 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3125 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3126 // If we have created a new extension, i.e., now we have two
3127 // extensions. We must make sure one of them is merged with
3128 // the load, otherwise we may degrade the code quality.
3129 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3130 // Promotion happened.
3132 // If this does not help to expose an ext(load) then, rollback.
3133 TPT.rollback(LastKnownGood);
3135 // None of the extension can form an ext(load).
3141 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3142 /// basic block as the load, unless conditions are unfavorable. This allows
3143 /// SelectionDAG to fold the extend into the load.
3144 /// \p I[in/out] the extension may be modified during the process if some
3145 /// promotions apply.
3147 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3148 // Try to promote a chain of computation if it allows to form
3149 // an extended load.
3150 TypePromotionTransaction TPT;
3151 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3152 TPT.getRestorationPoint();
3153 SmallVector<Instruction *, 1> Exts;
3155 // Look for a load being extended.
3156 LoadInst *LI = nullptr;
3157 Instruction *OldExt = I;
3158 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3160 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3161 "the code must remain the same");
3166 // If they're already in the same block, there's nothing to do.
3167 // Make the cheap checks first if we did not promote.
3168 // If we promoted, we need to check if it is indeed profitable.
3169 if (!HasPromoted && LI->getParent() == I->getParent())
3172 EVT VT = TLI->getValueType(I->getType());
3173 EVT LoadVT = TLI->getValueType(LI->getType());
3175 // If the load has other users and the truncate is not free, this probably
3176 // isn't worthwhile.
3177 if (!LI->hasOneUse() && TLI &&
3178 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3179 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3181 TPT.rollback(LastKnownGood);
3185 // Check whether the target supports casts folded into loads.
3187 if (isa<ZExtInst>(I))
3188 LType = ISD::ZEXTLOAD;
3190 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3191 LType = ISD::SEXTLOAD;
3193 if (TLI && !TLI->isLoadExtLegal(LType, LoadVT)) {
3195 TPT.rollback(LastKnownGood);
3199 // Move the extend into the same block as the load, so that SelectionDAG
3202 I->removeFromParent();
3208 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3209 BasicBlock *DefBB = I->getParent();
3211 // If the result of a {s|z}ext and its source are both live out, rewrite all
3212 // other uses of the source with result of extension.
3213 Value *Src = I->getOperand(0);
3214 if (Src->hasOneUse())
3217 // Only do this xform if truncating is free.
3218 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3221 // Only safe to perform the optimization if the source is also defined in
3223 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3226 bool DefIsLiveOut = false;
3227 for (User *U : I->users()) {
3228 Instruction *UI = cast<Instruction>(U);
3230 // Figure out which BB this ext is used in.
3231 BasicBlock *UserBB = UI->getParent();
3232 if (UserBB == DefBB) continue;
3233 DefIsLiveOut = true;
3239 // Make sure none of the uses are PHI nodes.
3240 for (User *U : Src->users()) {
3241 Instruction *UI = cast<Instruction>(U);
3242 BasicBlock *UserBB = UI->getParent();
3243 if (UserBB == DefBB) continue;
3244 // Be conservative. We don't want this xform to end up introducing
3245 // reloads just before load / store instructions.
3246 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3250 // InsertedTruncs - Only insert one trunc in each block once.
3251 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3253 bool MadeChange = false;
3254 for (Use &U : Src->uses()) {
3255 Instruction *User = cast<Instruction>(U.getUser());
3257 // Figure out which BB this ext is used in.
3258 BasicBlock *UserBB = User->getParent();
3259 if (UserBB == DefBB) continue;
3261 // Both src and def are live in this block. Rewrite the use.
3262 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3264 if (!InsertedTrunc) {
3265 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3266 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3267 InsertedTruncsSet.insert(InsertedTrunc);
3270 // Replace a use of the {s|z}ext source with a use of the result.
3279 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3280 /// turned into an explicit branch.
3281 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3282 // FIXME: This should use the same heuristics as IfConversion to determine
3283 // whether a select is better represented as a branch. This requires that
3284 // branch probability metadata is preserved for the select, which is not the
3287 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3289 // If the branch is predicted right, an out of order CPU can avoid blocking on
3290 // the compare. Emit cmovs on compares with a memory operand as branches to
3291 // avoid stalls on the load from memory. If the compare has more than one use
3292 // there's probably another cmov or setcc around so it's not worth emitting a
3297 Value *CmpOp0 = Cmp->getOperand(0);
3298 Value *CmpOp1 = Cmp->getOperand(1);
3300 // We check that the memory operand has one use to avoid uses of the loaded
3301 // value directly after the compare, making branches unprofitable.
3302 return Cmp->hasOneUse() &&
3303 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3304 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3308 /// If we have a SelectInst that will likely profit from branch prediction,
3309 /// turn it into a branch.
3310 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3311 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3313 // Can we convert the 'select' to CF ?
3314 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3317 TargetLowering::SelectSupportKind SelectKind;
3319 SelectKind = TargetLowering::VectorMaskSelect;
3320 else if (SI->getType()->isVectorTy())
3321 SelectKind = TargetLowering::ScalarCondVectorVal;
3323 SelectKind = TargetLowering::ScalarValSelect;
3325 // Do we have efficient codegen support for this kind of 'selects' ?
3326 if (TLI->isSelectSupported(SelectKind)) {
3327 // We have efficient codegen support for the select instruction.
3328 // Check if it is profitable to keep this 'select'.
3329 if (!TLI->isPredictableSelectExpensive() ||
3330 !isFormingBranchFromSelectProfitable(SI))
3336 // First, we split the block containing the select into 2 blocks.
3337 BasicBlock *StartBlock = SI->getParent();
3338 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3339 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3341 // Create a new block serving as the landing pad for the branch.
3342 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3343 NextBlock->getParent(), NextBlock);
3345 // Move the unconditional branch from the block with the select in it into our
3346 // landing pad block.
3347 StartBlock->getTerminator()->eraseFromParent();
3348 BranchInst::Create(NextBlock, SmallBlock);
3350 // Insert the real conditional branch based on the original condition.
3351 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3353 // The select itself is replaced with a PHI Node.
3354 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3356 PN->addIncoming(SI->getTrueValue(), StartBlock);
3357 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3358 SI->replaceAllUsesWith(PN);
3359 SI->eraseFromParent();
3361 // Instruct OptimizeBlock to skip to the next block.
3362 CurInstIterator = StartBlock->end();
3363 ++NumSelectsExpanded;
3367 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3368 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3370 for (unsigned i = 0; i < Mask.size(); ++i) {
3371 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3373 SplatElem = Mask[i];
3379 /// Some targets have expensive vector shifts if the lanes aren't all the same
3380 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3381 /// it's often worth sinking a shufflevector splat down to its use so that
3382 /// codegen can spot all lanes are identical.
3383 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3384 BasicBlock *DefBB = SVI->getParent();
3386 // Only do this xform if variable vector shifts are particularly expensive.
3387 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3390 // We only expect better codegen by sinking a shuffle if we can recognise a
3392 if (!isBroadcastShuffle(SVI))
3395 // InsertedShuffles - Only insert a shuffle in each block once.
3396 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3398 bool MadeChange = false;
3399 for (User *U : SVI->users()) {
3400 Instruction *UI = cast<Instruction>(U);
3402 // Figure out which BB this ext is used in.
3403 BasicBlock *UserBB = UI->getParent();
3404 if (UserBB == DefBB) continue;
3406 // For now only apply this when the splat is used by a shift instruction.
3407 if (!UI->isShift()) continue;
3409 // Everything checks out, sink the shuffle if the user's block doesn't
3410 // already have a copy.
3411 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3413 if (!InsertedShuffle) {
3414 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3415 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3417 SVI->getOperand(2), "", InsertPt);
3420 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3424 // If we removed all uses, nuke the shuffle.
3425 if (SVI->use_empty()) {
3426 SVI->eraseFromParent();
3434 /// \brief Helper class to promote a scalar operation to a vector one.
3435 /// This class is used to move downward extractelement transition.
3437 /// a = vector_op <2 x i32>
3438 /// b = extractelement <2 x i32> a, i32 0
3443 /// a = vector_op <2 x i32>
3444 /// c = vector_op a (equivalent to scalar_op on the related lane)
3445 /// * d = extractelement <2 x i32> c, i32 0
3447 /// Assuming both extractelement and store can be combine, we get rid of the
3449 class VectorPromoteHelper {
3450 /// Used to perform some checks on the legality of vector operations.
3451 const TargetLowering &TLI;
3453 /// Used to estimated the cost of the promoted chain.
3454 const TargetTransformInfo &TTI;
3456 /// The transition being moved downwards.
3457 Instruction *Transition;
3458 /// The sequence of instructions to be promoted.
3459 SmallVector<Instruction *, 4> InstsToBePromoted;
3460 /// Cost of combining a store and an extract.
3461 unsigned StoreExtractCombineCost;
3462 /// Instruction that will be combined with the transition.
3463 Instruction *CombineInst;
3465 /// \brief The instruction that represents the current end of the transition.
3466 /// Since we are faking the promotion until we reach the end of the chain
3467 /// of computation, we need a way to get the current end of the transition.
3468 Instruction *getEndOfTransition() const {
3469 if (InstsToBePromoted.empty())
3471 return InstsToBePromoted.back();
3474 /// \brief Return the index of the original value in the transition.
3475 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3476 /// c, is at index 0.
3477 unsigned getTransitionOriginalValueIdx() const {
3478 assert(isa<ExtractElementInst>(Transition) &&
3479 "Other kind of transitions are not supported yet");
3483 /// \brief Return the index of the index in the transition.
3484 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3486 unsigned getTransitionIdx() const {
3487 assert(isa<ExtractElementInst>(Transition) &&
3488 "Other kind of transitions are not supported yet");
3492 /// \brief Get the type of the transition.
3493 /// This is the type of the original value.
3494 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3495 /// transition is <2 x i32>.
3496 Type *getTransitionType() const {
3497 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3500 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3501 /// I.e., we have the following sequence:
3502 /// Def = Transition <ty1> a to <ty2>
3503 /// b = ToBePromoted <ty2> Def, ...
3505 /// b = ToBePromoted <ty1> a, ...
3506 /// Def = Transition <ty1> ToBePromoted to <ty2>
3507 void promoteImpl(Instruction *ToBePromoted);
3509 /// \brief Check whether or not it is profitable to promote all the
3510 /// instructions enqueued to be promoted.
3511 bool isProfitableToPromote() {
3512 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3513 unsigned Index = isa<ConstantInt>(ValIdx)
3514 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3516 Type *PromotedType = getTransitionType();
3518 StoreInst *ST = cast<StoreInst>(CombineInst);
3519 unsigned AS = ST->getPointerAddressSpace();
3520 unsigned Align = ST->getAlignment();
3521 // Check if this store is supported.
3522 if (!TLI.allowsMisalignedMemoryAccesses(
3523 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3524 // If this is not supported, there is no way we can combine
3525 // the extract with the store.
3529 // The scalar chain of computation has to pay for the transition
3530 // scalar to vector.
3531 // The vector chain has to account for the combining cost.
3532 uint64_t ScalarCost =
3533 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3534 uint64_t VectorCost = StoreExtractCombineCost;
3535 for (const auto &Inst : InstsToBePromoted) {
3536 // Compute the cost.
3537 // By construction, all instructions being promoted are arithmetic ones.
3538 // Moreover, one argument is a constant that can be viewed as a splat
3540 Value *Arg0 = Inst->getOperand(0);
3541 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3542 isa<ConstantFP>(Arg0);
3543 TargetTransformInfo::OperandValueKind Arg0OVK =
3544 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3545 : TargetTransformInfo::OK_AnyValue;
3546 TargetTransformInfo::OperandValueKind Arg1OVK =
3547 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3548 : TargetTransformInfo::OK_AnyValue;
3549 ScalarCost += TTI.getArithmeticInstrCost(
3550 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3551 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3554 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3555 << ScalarCost << "\nVector: " << VectorCost << '\n');
3556 return ScalarCost > VectorCost;
3559 /// \brief Generate a constant vector with \p Val with the same
3560 /// number of elements as the transition.
3561 /// \p UseSplat defines whether or not \p Val should be replicated
3562 /// accross the whole vector.
3563 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3564 /// otherwise we generate a vector with as many undef as possible:
3565 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3566 /// used at the index of the extract.
3567 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3568 unsigned ExtractIdx = UINT_MAX;
3570 // If we cannot determine where the constant must be, we have to
3571 // use a splat constant.
3572 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3573 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3574 ExtractIdx = CstVal->getSExtValue();
3579 unsigned End = getTransitionType()->getVectorNumElements();
3581 return ConstantVector::getSplat(End, Val);
3583 SmallVector<Constant *, 4> ConstVec;
3584 UndefValue *UndefVal = UndefValue::get(Val->getType());
3585 for (unsigned Idx = 0; Idx != End; ++Idx) {
3586 if (Idx == ExtractIdx)
3587 ConstVec.push_back(Val);
3589 ConstVec.push_back(UndefVal);
3591 return ConstantVector::get(ConstVec);
3594 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3595 /// in \p Use can trigger undefined behavior.
3596 static bool canCauseUndefinedBehavior(const Instruction *Use,
3597 unsigned OperandIdx) {
3598 // This is not safe to introduce undef when the operand is on
3599 // the right hand side of a division-like instruction.
3600 if (OperandIdx != 1)
3602 switch (Use->getOpcode()) {
3605 case Instruction::SDiv:
3606 case Instruction::UDiv:
3607 case Instruction::SRem:
3608 case Instruction::URem:
3610 case Instruction::FDiv:
3611 case Instruction::FRem:
3612 return !Use->hasNoNaNs();
3614 llvm_unreachable(nullptr);
3618 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3619 Instruction *Transition, unsigned CombineCost)
3620 : TLI(TLI), TTI(TTI), Transition(Transition),
3621 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3622 assert(Transition && "Do not know how to promote null");
3625 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3626 bool canPromote(const Instruction *ToBePromoted) const {
3627 // We could support CastInst too.
3628 return isa<BinaryOperator>(ToBePromoted);
3631 /// \brief Check if it is profitable to promote \p ToBePromoted
3632 /// by moving downward the transition through.
3633 bool shouldPromote(const Instruction *ToBePromoted) const {
3634 // Promote only if all the operands can be statically expanded.
3635 // Indeed, we do not want to introduce any new kind of transitions.
3636 for (const Use &U : ToBePromoted->operands()) {
3637 const Value *Val = U.get();
3638 if (Val == getEndOfTransition()) {
3639 // If the use is a division and the transition is on the rhs,
3640 // we cannot promote the operation, otherwise we may create a
3641 // division by zero.
3642 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3646 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3647 !isa<ConstantFP>(Val))
3650 // Check that the resulting operation is legal.
3651 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3654 return StressStoreExtract ||
3655 TLI.isOperationLegalOrCustom(
3656 ISDOpcode, TLI.getValueType(getTransitionType(), true));
3659 /// \brief Check whether or not \p Use can be combined
3660 /// with the transition.
3661 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3662 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3664 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3665 void enqueueForPromotion(Instruction *ToBePromoted) {
3666 InstsToBePromoted.push_back(ToBePromoted);
3669 /// \brief Set the instruction that will be combined with the transition.
3670 void recordCombineInstruction(Instruction *ToBeCombined) {
3671 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3672 CombineInst = ToBeCombined;
3675 /// \brief Promote all the instructions enqueued for promotion if it is
3677 /// \return True if the promotion happened, false otherwise.
3679 // Check if there is something to promote.
3680 // Right now, if we do not have anything to combine with,
3681 // we assume the promotion is not profitable.
3682 if (InstsToBePromoted.empty() || !CombineInst)
3686 if (!StressStoreExtract && !isProfitableToPromote())
3690 for (auto &ToBePromoted : InstsToBePromoted)
3691 promoteImpl(ToBePromoted);
3692 InstsToBePromoted.clear();
3696 } // End of anonymous namespace.
3698 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3699 // At this point, we know that all the operands of ToBePromoted but Def
3700 // can be statically promoted.
3701 // For Def, we need to use its parameter in ToBePromoted:
3702 // b = ToBePromoted ty1 a
3703 // Def = Transition ty1 b to ty2
3704 // Move the transition down.
3705 // 1. Replace all uses of the promoted operation by the transition.
3706 // = ... b => = ... Def.
3707 assert(ToBePromoted->getType() == Transition->getType() &&
3708 "The type of the result of the transition does not match "
3710 ToBePromoted->replaceAllUsesWith(Transition);
3711 // 2. Update the type of the uses.
3712 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3713 Type *TransitionTy = getTransitionType();
3714 ToBePromoted->mutateType(TransitionTy);
3715 // 3. Update all the operands of the promoted operation with promoted
3717 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3718 for (Use &U : ToBePromoted->operands()) {
3719 Value *Val = U.get();
3720 Value *NewVal = nullptr;
3721 if (Val == Transition)
3722 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3723 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3724 isa<ConstantFP>(Val)) {
3725 // Use a splat constant if it is not safe to use undef.
3726 NewVal = getConstantVector(
3727 cast<Constant>(Val),
3728 isa<UndefValue>(Val) ||
3729 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3731 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3732 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3734 Transition->removeFromParent();
3735 Transition->insertAfter(ToBePromoted);
3736 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3739 /// Some targets can do store(extractelement) with one instruction.
3740 /// Try to push the extractelement towards the stores when the target
3741 /// has this feature and this is profitable.
3742 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3743 unsigned CombineCost = UINT_MAX;
3744 if (DisableStoreExtract || !TLI ||
3745 (!StressStoreExtract &&
3746 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3747 Inst->getOperand(1), CombineCost)))
3750 // At this point we know that Inst is a vector to scalar transition.
3751 // Try to move it down the def-use chain, until:
3752 // - We can combine the transition with its single use
3753 // => we got rid of the transition.
3754 // - We escape the current basic block
3755 // => we would need to check that we are moving it at a cheaper place and
3756 // we do not do that for now.
3757 BasicBlock *Parent = Inst->getParent();
3758 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3759 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3760 // If the transition has more than one use, assume this is not going to be
3762 while (Inst->hasOneUse()) {
3763 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3764 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3766 if (ToBePromoted->getParent() != Parent) {
3767 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3768 << ToBePromoted->getParent()->getName()
3769 << ") than the transition (" << Parent->getName() << ").\n");
3773 if (VPH.canCombine(ToBePromoted)) {
3774 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3775 << "will be combined with: " << *ToBePromoted << '\n');
3776 VPH.recordCombineInstruction(ToBePromoted);
3777 bool Changed = VPH.promote();
3778 NumStoreExtractExposed += Changed;
3782 DEBUG(dbgs() << "Try promoting.\n");
3783 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3786 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3788 VPH.enqueueForPromotion(ToBePromoted);
3789 Inst = ToBePromoted;
3794 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3795 if (PHINode *P = dyn_cast<PHINode>(I)) {
3796 // It is possible for very late stage optimizations (such as SimplifyCFG)
3797 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3798 // trivial PHI, go ahead and zap it here.
3799 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3801 P->replaceAllUsesWith(V);
3802 P->eraseFromParent();
3809 if (CastInst *CI = dyn_cast<CastInst>(I)) {
3810 // If the source of the cast is a constant, then this should have
3811 // already been constant folded. The only reason NOT to constant fold
3812 // it is if something (e.g. LSR) was careful to place the constant
3813 // evaluation in a block other than then one that uses it (e.g. to hoist
3814 // the address of globals out of a loop). If this is the case, we don't
3815 // want to forward-subst the cast.
3816 if (isa<Constant>(CI->getOperand(0)))
3819 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3822 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3823 /// Sink a zext or sext into its user blocks if the target type doesn't
3824 /// fit in one register
3825 if (TLI && TLI->getTypeAction(CI->getContext(),
3826 TLI->getValueType(CI->getType())) ==
3827 TargetLowering::TypeExpandInteger) {
3828 return SinkCast(CI);
3830 bool MadeChange = MoveExtToFormExtLoad(I);
3831 return MadeChange | OptimizeExtUses(I);
3837 if (CmpInst *CI = dyn_cast<CmpInst>(I))
3838 if (!TLI || !TLI->hasMultipleConditionRegisters())
3839 return OptimizeCmpExpression(CI);
3841 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3843 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3847 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3849 return OptimizeMemoryInst(I, SI->getOperand(1),
3850 SI->getOperand(0)->getType());
3854 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3856 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3857 BinOp->getOpcode() == Instruction::LShr)) {
3858 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3859 if (TLI && CI && TLI->hasExtractBitsInsn())
3860 return OptimizeExtractBits(BinOp, CI, *TLI);
3865 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3866 if (GEPI->hasAllZeroIndices()) {
3867 /// The GEP operand must be a pointer, so must its result -> BitCast
3868 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3869 GEPI->getName(), GEPI);
3870 GEPI->replaceAllUsesWith(NC);
3871 GEPI->eraseFromParent();
3879 if (CallInst *CI = dyn_cast<CallInst>(I))
3880 return OptimizeCallInst(CI);
3882 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3883 return OptimizeSelectInst(SI);
3885 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3886 return OptimizeShuffleVectorInst(SVI);
3888 if (isa<ExtractElementInst>(I))
3889 return OptimizeExtractElementInst(I);
3894 // In this pass we look for GEP and cast instructions that are used
3895 // across basic blocks and rewrite them to improve basic-block-at-a-time
3897 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3899 bool MadeChange = false;
3901 CurInstIterator = BB.begin();
3902 while (CurInstIterator != BB.end())
3903 MadeChange |= OptimizeInst(CurInstIterator++);
3905 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3910 // llvm.dbg.value is far away from the value then iSel may not be able
3911 // handle it properly. iSel will drop llvm.dbg.value if it can not
3912 // find a node corresponding to the value.
3913 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3914 bool MadeChange = false;
3915 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3916 Instruction *PrevNonDbgInst = nullptr;
3917 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3918 Instruction *Insn = BI; ++BI;
3919 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3920 // Leave dbg.values that refer to an alloca alone. These
3921 // instrinsics describe the address of a variable (= the alloca)
3922 // being taken. They should not be moved next to the alloca
3923 // (and to the beginning of the scope), but rather stay close to
3924 // where said address is used.
3925 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3926 PrevNonDbgInst = Insn;
3930 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3931 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3932 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3933 DVI->removeFromParent();
3934 if (isa<PHINode>(VI))
3935 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3937 DVI->insertAfter(VI);
3946 // If there is a sequence that branches based on comparing a single bit
3947 // against zero that can be combined into a single instruction, and the
3948 // target supports folding these into a single instruction, sink the
3949 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3950 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3952 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3953 if (!EnableAndCmpSinking)
3955 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3957 bool MadeChange = false;
3958 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3959 BasicBlock *BB = I++;
3961 // Does this BB end with the following?
3962 // %andVal = and %val, #single-bit-set
3963 // %icmpVal = icmp %andResult, 0
3964 // br i1 %cmpVal label %dest1, label %dest2"
3965 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3966 if (!Brcc || !Brcc->isConditional())
3968 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3969 if (!Cmp || Cmp->getParent() != BB)
3971 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3972 if (!Zero || !Zero->isZero())
3974 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3975 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3977 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3978 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3980 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3982 // Push the "and; icmp" for any users that are conditional branches.
3983 // Since there can only be one branch use per BB, we don't need to keep
3984 // track of which BBs we insert into.
3985 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3989 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3991 if (!BrccUser || !BrccUser->isConditional())
3993 BasicBlock *UserBB = BrccUser->getParent();
3994 if (UserBB == BB) continue;
3995 DEBUG(dbgs() << "found Brcc use\n");
3997 // Sink the "and; icmp" to use.
3999 BinaryOperator *NewAnd =
4000 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4003 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4007 DEBUG(BrccUser->getParent()->dump());
4013 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4014 /// success, or returns false if no or invalid metadata was found.
4015 static bool extractBranchMetadata(BranchInst *BI,
4016 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4017 assert(BI->isConditional() &&
4018 "Looking for probabilities on unconditional branch?");
4019 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4020 if (!ProfileData || ProfileData->getNumOperands() != 3)
4023 const auto *CITrue =
4024 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4025 const auto *CIFalse =
4026 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4027 if (!CITrue || !CIFalse)
4030 ProbTrue = CITrue->getValue().getZExtValue();
4031 ProbFalse = CIFalse->getValue().getZExtValue();
4036 /// \brief Scale down both weights to fit into uint32_t.
4037 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4038 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4039 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4040 NewTrue = NewTrue / Scale;
4041 NewFalse = NewFalse / Scale;
4044 /// \brief Some targets prefer to split a conditional branch like:
4046 /// %0 = icmp ne i32 %a, 0
4047 /// %1 = icmp ne i32 %b, 0
4048 /// %or.cond = or i1 %0, %1
4049 /// br i1 %or.cond, label %TrueBB, label %FalseBB
4051 /// into multiple branch instructions like:
4054 /// %0 = icmp ne i32 %a, 0
4055 /// br i1 %0, label %TrueBB, label %bb2
4057 /// %1 = icmp ne i32 %b, 0
4058 /// br i1 %1, label %TrueBB, label %FalseBB
4060 /// This usually allows instruction selection to do even further optimizations
4061 /// and combine the compare with the branch instruction. Currently this is
4062 /// applied for targets which have "cheap" jump instructions.
4064 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4066 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4067 if (!TM || TM->Options.EnableFastISel != true ||
4068 !TLI || TLI->isJumpExpensive())
4071 bool MadeChange = false;
4072 for (auto &BB : F) {
4073 // Does this BB end with the following?
4074 // %cond1 = icmp|fcmp|binary instruction ...
4075 // %cond2 = icmp|fcmp|binary instruction ...
4076 // %cond.or = or|and i1 %cond1, cond2
4077 // br i1 %cond.or label %dest1, label %dest2"
4078 BinaryOperator *LogicOp;
4079 BasicBlock *TBB, *FBB;
4080 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4084 Value *Cond1, *Cond2;
4085 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4086 m_OneUse(m_Value(Cond2)))))
4087 Opc = Instruction::And;
4088 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4089 m_OneUse(m_Value(Cond2)))))
4090 Opc = Instruction::Or;
4094 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4095 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4098 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4101 auto *InsertBefore = std::next(Function::iterator(BB))
4102 .getNodePtrUnchecked();
4103 auto TmpBB = BasicBlock::Create(BB.getContext(),
4104 BB.getName() + ".cond.split",
4105 BB.getParent(), InsertBefore);
4107 // Update original basic block by using the first condition directly by the
4108 // branch instruction and removing the no longer needed and/or instruction.
4109 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4110 Br1->setCondition(Cond1);
4111 LogicOp->eraseFromParent();
4113 // Depending on the conditon we have to either replace the true or the false
4114 // successor of the original branch instruction.
4115 if (Opc == Instruction::And)
4116 Br1->setSuccessor(0, TmpBB);
4118 Br1->setSuccessor(1, TmpBB);
4120 // Fill in the new basic block.
4121 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4122 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4123 I->removeFromParent();
4124 I->insertBefore(Br2);
4127 // Update PHI nodes in both successors. The original BB needs to be
4128 // replaced in one succesor's PHI nodes, because the branch comes now from
4129 // the newly generated BB (NewBB). In the other successor we need to add one
4130 // incoming edge to the PHI nodes, because both branch instructions target
4131 // now the same successor. Depending on the original branch condition
4132 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4133 // we perfrom the correct update for the PHI nodes.
4134 // This doesn't change the successor order of the just created branch
4135 // instruction (or any other instruction).
4136 if (Opc == Instruction::Or)
4137 std::swap(TBB, FBB);
4139 // Replace the old BB with the new BB.
4140 for (auto &I : *TBB) {
4141 PHINode *PN = dyn_cast<PHINode>(&I);
4145 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4146 PN->setIncomingBlock(i, TmpBB);
4149 // Add another incoming edge form the new BB.
4150 for (auto &I : *FBB) {
4151 PHINode *PN = dyn_cast<PHINode>(&I);
4154 auto *Val = PN->getIncomingValueForBlock(&BB);
4155 PN->addIncoming(Val, TmpBB);
4158 // Update the branch weights (from SelectionDAGBuilder::
4159 // FindMergedConditions).
4160 if (Opc == Instruction::Or) {
4161 // Codegen X | Y as:
4170 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4171 // The requirement is that
4172 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4173 // = TrueProb for orignal BB.
4174 // Assuming the orignal weights are A and B, one choice is to set BB1's
4175 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4177 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4178 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4179 // TmpBB, but the math is more complicated.
4180 uint64_t TrueWeight, FalseWeight;
4181 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4182 uint64_t NewTrueWeight = TrueWeight;
4183 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4184 scaleWeights(NewTrueWeight, NewFalseWeight);
4185 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4186 .createBranchWeights(TrueWeight, FalseWeight));
4188 NewTrueWeight = TrueWeight;
4189 NewFalseWeight = 2 * FalseWeight;
4190 scaleWeights(NewTrueWeight, NewFalseWeight);
4191 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4192 .createBranchWeights(TrueWeight, FalseWeight));
4195 // Codegen X & Y as:
4203 // This requires creation of TmpBB after CurBB.
4205 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4206 // The requirement is that
4207 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4208 // = FalseProb for orignal BB.
4209 // Assuming the orignal weights are A and B, one choice is to set BB1's
4210 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4212 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4213 uint64_t TrueWeight, FalseWeight;
4214 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4215 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4216 uint64_t NewFalseWeight = FalseWeight;
4217 scaleWeights(NewTrueWeight, NewFalseWeight);
4218 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4219 .createBranchWeights(TrueWeight, FalseWeight));
4221 NewTrueWeight = 2 * TrueWeight;
4222 NewFalseWeight = FalseWeight;
4223 scaleWeights(NewTrueWeight, NewFalseWeight);
4224 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4225 .createBranchWeights(TrueWeight, FalseWeight));
4229 // Request DOM Tree update.
4230 // Note: No point in getting fancy here, since the DT info is never
4231 // available to CodeGenPrepare and the existing update code is broken
4237 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();