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"
48 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
50 using namespace llvm::PatternMatch;
52 #define DEBUG_TYPE "codegenprepare"
54 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
55 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
56 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
57 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
62 "computations were sunk");
63 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
64 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
65 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
66 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
67 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
68 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
69 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
71 static cl::opt<bool> DisableBranchOpts(
72 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
73 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75 static cl::opt<bool> DisableSelectToBranch(
76 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
77 cl::desc("Disable select to branch conversion."));
79 static cl::opt<bool> AddrSinkUsingGEPs(
80 "addr-sink-using-gep", cl::Hidden, cl::init(false),
81 cl::desc("Address sinking in CGP using GEPs."));
83 static cl::opt<bool> EnableAndCmpSinking(
84 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
85 cl::desc("Enable sinkinig and/cmp into branches."));
87 static cl::opt<bool> DisableStoreExtract(
88 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
89 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
91 static cl::opt<bool> StressStoreExtract(
92 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
93 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
95 static cl::opt<bool> DisableExtLdPromotion(
96 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
97 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
100 static cl::opt<bool> StressExtLdPromotion(
101 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
103 "optimization in CodeGenPrepare"));
106 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
110 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
112 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
113 class TypePromotionTransaction;
115 class CodeGenPrepare : public FunctionPass {
116 /// TLI - Keep a pointer of a TargetLowering to consult for determining
117 /// transformation profitability.
118 const TargetMachine *TM;
119 const TargetLowering *TLI;
120 const TargetTransformInfo *TTI;
121 const TargetLibraryInfo *TLInfo;
124 /// CurInstIterator - As we scan instructions optimizing them, this is the
125 /// next instruction to optimize. Xforms that can invalidate this should
127 BasicBlock::iterator CurInstIterator;
129 /// Keeps track of non-local addresses that have been sunk into a block.
130 /// This allows us to avoid inserting duplicate code for blocks with
131 /// multiple load/stores of the same address.
132 ValueMap<Value*, Value*> SunkAddrs;
134 /// Keeps track of all truncates inserted for the current function.
135 SetOfInstrs InsertedTruncsSet;
136 /// Keeps track of the type of the related instruction before their
137 /// promotion for the current function.
138 InstrToOrigTy PromotedInsts;
140 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
144 /// OptSize - True if optimizing for size.
148 static char ID; // Pass identification, replacement for typeid
149 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
150 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
151 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
153 bool runOnFunction(Function &F) override;
155 const char *getPassName() const override { return "CodeGen Prepare"; }
157 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.addPreserved<DominatorTreeWrapperPass>();
159 AU.addRequired<TargetLibraryInfo>();
160 AU.addRequired<TargetTransformInfo>();
164 bool EliminateFallThrough(Function &F);
165 bool EliminateMostlyEmptyBlocks(Function &F);
166 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
167 void EliminateMostlyEmptyBlock(BasicBlock *BB);
168 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
169 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
170 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
171 bool OptimizeInlineAsmInst(CallInst *CS);
172 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
173 bool MoveExtToFormExtLoad(Instruction *&I);
174 bool OptimizeExtUses(Instruction *I);
175 bool OptimizeSelectInst(SelectInst *SI);
176 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
177 bool OptimizeExtractElementInst(Instruction *Inst);
178 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
179 bool PlaceDbgValues(Function &F);
180 bool sinkAndCmp(Function &F);
181 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
183 const SmallVectorImpl<Instruction *> &Exts,
184 unsigned CreatedInst);
185 bool splitBranchCondition(Function &F);
189 char CodeGenPrepare::ID = 0;
190 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
191 "Optimize for code generation", false, false)
193 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
194 return new CodeGenPrepare(TM);
197 bool CodeGenPrepare::runOnFunction(Function &F) {
198 if (skipOptnoneFunction(F))
201 bool EverMadeChange = false;
202 // Clear per function information.
203 InsertedTruncsSet.clear();
204 PromotedInsts.clear();
208 TLI = TM->getSubtargetImpl()->getTargetLowering();
209 TLInfo = &getAnalysis<TargetLibraryInfo>();
210 TTI = &getAnalysis<TargetTransformInfo>();
211 DominatorTreeWrapperPass *DTWP =
212 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
213 DT = DTWP ? &DTWP->getDomTree() : nullptr;
214 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
215 Attribute::OptimizeForSize);
217 /// This optimization identifies DIV instructions that can be
218 /// profitably bypassed and carried out with a shorter, faster divide.
219 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
220 const DenseMap<unsigned int, unsigned int> &BypassWidths =
221 TLI->getBypassSlowDivWidths();
222 for (Function::iterator I = F.begin(); I != F.end(); I++)
223 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
226 // Eliminate blocks that contain only PHI nodes and an
227 // unconditional branch.
228 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
230 // llvm.dbg.value is far away from the value then iSel may not be able
231 // handle it properly. iSel will drop llvm.dbg.value if it can not
232 // find a node corresponding to the value.
233 EverMadeChange |= PlaceDbgValues(F);
235 // If there is a mask, compare against zero, and branch that can be combined
236 // into a single target instruction, push the mask and compare into branch
237 // users. Do this before OptimizeBlock -> OptimizeInst ->
238 // OptimizeCmpExpression, which perturbs the pattern being searched for.
239 if (!DisableBranchOpts) {
240 EverMadeChange |= sinkAndCmp(F);
241 EverMadeChange |= splitBranchCondition(F);
244 bool MadeChange = true;
247 for (Function::iterator I = F.begin(); I != F.end(); ) {
248 BasicBlock *BB = I++;
249 bool ModifiedDTOnIteration = false;
250 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
252 // Restart BB iteration if the dominator tree of the Function was changed
253 ModifiedDT |= ModifiedDTOnIteration;
254 if (ModifiedDTOnIteration)
257 EverMadeChange |= MadeChange;
262 if (!DisableBranchOpts) {
264 SmallPtrSet<BasicBlock*, 8> WorkList;
265 for (BasicBlock &BB : F) {
266 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
267 MadeChange |= ConstantFoldTerminator(&BB, true);
268 if (!MadeChange) continue;
270 for (SmallVectorImpl<BasicBlock*>::iterator
271 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
272 if (pred_begin(*II) == pred_end(*II))
273 WorkList.insert(*II);
276 // Delete the dead blocks and any of their dead successors.
277 MadeChange |= !WorkList.empty();
278 while (!WorkList.empty()) {
279 BasicBlock *BB = *WorkList.begin();
281 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
285 for (SmallVectorImpl<BasicBlock*>::iterator
286 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
287 if (pred_begin(*II) == pred_end(*II))
288 WorkList.insert(*II);
291 // Merge pairs of basic blocks with unconditional branches, connected by
293 if (EverMadeChange || MadeChange)
294 MadeChange |= EliminateFallThrough(F);
298 EverMadeChange |= MadeChange;
301 if (ModifiedDT && DT)
304 return EverMadeChange;
307 /// EliminateFallThrough - Merge basic blocks which are connected
308 /// by a single edge, where one of the basic blocks has a single successor
309 /// pointing to the other basic block, which has a single predecessor.
310 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
311 bool Changed = false;
312 // Scan all of the blocks in the function, except for the entry block.
313 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
314 BasicBlock *BB = I++;
315 // If the destination block has a single pred, then this is a trivial
316 // edge, just collapse it.
317 BasicBlock *SinglePred = BB->getSinglePredecessor();
319 // Don't merge if BB's address is taken.
320 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
322 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
323 if (Term && !Term->isConditional()) {
325 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
326 // Remember if SinglePred was the entry block of the function.
327 // If so, we will need to move BB back to the entry position.
328 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
329 MergeBasicBlockIntoOnlyPred(BB, this);
331 if (isEntry && BB != &BB->getParent()->getEntryBlock())
332 BB->moveBefore(&BB->getParent()->getEntryBlock());
334 // We have erased a block. Update the iterator.
341 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
342 /// debug info directives, and an unconditional branch. Passes before isel
343 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
344 /// isel. Start by eliminating these blocks so we can split them the way we
346 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
347 bool MadeChange = false;
348 // Note that this intentionally skips the entry block.
349 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
350 BasicBlock *BB = I++;
352 // If this block doesn't end with an uncond branch, ignore it.
353 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
354 if (!BI || !BI->isUnconditional())
357 // If the instruction before the branch (skipping debug info) isn't a phi
358 // node, then other stuff is happening here.
359 BasicBlock::iterator BBI = BI;
360 if (BBI != BB->begin()) {
362 while (isa<DbgInfoIntrinsic>(BBI)) {
363 if (BBI == BB->begin())
367 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
371 // Do not break infinite loops.
372 BasicBlock *DestBB = BI->getSuccessor(0);
376 if (!CanMergeBlocks(BB, DestBB))
379 EliminateMostlyEmptyBlock(BB);
385 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
386 /// single uncond branch between them, and BB contains no other non-phi
388 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
389 const BasicBlock *DestBB) const {
390 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
391 // the successor. If there are more complex condition (e.g. preheaders),
392 // don't mess around with them.
393 BasicBlock::const_iterator BBI = BB->begin();
394 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
395 for (const User *U : PN->users()) {
396 const Instruction *UI = cast<Instruction>(U);
397 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
399 // If User is inside DestBB block and it is a PHINode then check
400 // incoming value. If incoming value is not from BB then this is
401 // a complex condition (e.g. preheaders) we want to avoid here.
402 if (UI->getParent() == DestBB) {
403 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
404 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
405 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
406 if (Insn && Insn->getParent() == BB &&
407 Insn->getParent() != UPN->getIncomingBlock(I))
414 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
415 // and DestBB may have conflicting incoming values for the block. If so, we
416 // can't merge the block.
417 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
418 if (!DestBBPN) return true; // no conflict.
420 // Collect the preds of BB.
421 SmallPtrSet<const BasicBlock*, 16> BBPreds;
422 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
423 // It is faster to get preds from a PHI than with pred_iterator.
424 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
425 BBPreds.insert(BBPN->getIncomingBlock(i));
427 BBPreds.insert(pred_begin(BB), pred_end(BB));
430 // Walk the preds of DestBB.
431 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
432 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
433 if (BBPreds.count(Pred)) { // Common predecessor?
434 BBI = DestBB->begin();
435 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
436 const Value *V1 = PN->getIncomingValueForBlock(Pred);
437 const Value *V2 = PN->getIncomingValueForBlock(BB);
439 // If V2 is a phi node in BB, look up what the mapped value will be.
440 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
441 if (V2PN->getParent() == BB)
442 V2 = V2PN->getIncomingValueForBlock(Pred);
444 // If there is a conflict, bail out.
445 if (V1 != V2) return false;
454 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
455 /// an unconditional branch in it.
456 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
457 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
458 BasicBlock *DestBB = BI->getSuccessor(0);
460 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
462 // If the destination block has a single pred, then this is a trivial edge,
464 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
465 if (SinglePred != DestBB) {
466 // Remember if SinglePred was the entry block of the function. If so, we
467 // will need to move BB back to the entry position.
468 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
469 MergeBasicBlockIntoOnlyPred(DestBB, this);
471 if (isEntry && BB != &BB->getParent()->getEntryBlock())
472 BB->moveBefore(&BB->getParent()->getEntryBlock());
474 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
479 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
480 // to handle the new incoming edges it is about to have.
482 for (BasicBlock::iterator BBI = DestBB->begin();
483 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
484 // Remove the incoming value for BB, and remember it.
485 Value *InVal = PN->removeIncomingValue(BB, false);
487 // Two options: either the InVal is a phi node defined in BB or it is some
488 // value that dominates BB.
489 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
490 if (InValPhi && InValPhi->getParent() == BB) {
491 // Add all of the input values of the input PHI as inputs of this phi.
492 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
493 PN->addIncoming(InValPhi->getIncomingValue(i),
494 InValPhi->getIncomingBlock(i));
496 // Otherwise, add one instance of the dominating value for each edge that
497 // we will be adding.
498 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
499 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
500 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
502 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
503 PN->addIncoming(InVal, *PI);
508 // The PHIs are now updated, change everything that refers to BB to use
509 // DestBB and remove BB.
510 BB->replaceAllUsesWith(DestBB);
511 if (DT && !ModifiedDT) {
512 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
513 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
514 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
515 DT->changeImmediateDominator(DestBB, NewIDom);
518 BB->eraseFromParent();
521 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
524 /// SinkCast - Sink the specified cast instruction into its user blocks
525 static bool SinkCast(CastInst *CI) {
526 BasicBlock *DefBB = CI->getParent();
528 /// InsertedCasts - Only insert a cast in each block once.
529 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
531 bool MadeChange = false;
532 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
534 Use &TheUse = UI.getUse();
535 Instruction *User = cast<Instruction>(*UI);
537 // Figure out which BB this cast is used in. For PHI's this is the
538 // appropriate predecessor block.
539 BasicBlock *UserBB = User->getParent();
540 if (PHINode *PN = dyn_cast<PHINode>(User)) {
541 UserBB = PN->getIncomingBlock(TheUse);
544 // Preincrement use iterator so we don't invalidate it.
547 // If this user is in the same block as the cast, don't change the cast.
548 if (UserBB == DefBB) continue;
550 // If we have already inserted a cast into this block, use it.
551 CastInst *&InsertedCast = InsertedCasts[UserBB];
554 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
556 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
561 // Replace a use of the cast with a use of the new cast.
562 TheUse = InsertedCast;
566 // If we removed all uses, nuke the cast.
567 if (CI->use_empty()) {
568 CI->eraseFromParent();
575 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
576 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
577 /// sink it into user blocks to reduce the number of virtual
578 /// registers that must be created and coalesced.
580 /// Return true if any changes are made.
582 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
583 // If this is a noop copy,
584 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
585 EVT DstVT = TLI.getValueType(CI->getType());
587 // This is an fp<->int conversion?
588 if (SrcVT.isInteger() != DstVT.isInteger())
591 // If this is an extension, it will be a zero or sign extension, which
593 if (SrcVT.bitsLT(DstVT)) return false;
595 // If these values will be promoted, find out what they will be promoted
596 // to. This helps us consider truncates on PPC as noop copies when they
598 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
599 TargetLowering::TypePromoteInteger)
600 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
601 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
602 TargetLowering::TypePromoteInteger)
603 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
605 // If, after promotion, these are the same types, this is a noop copy.
612 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
613 /// the number of virtual registers that must be created and coalesced. This is
614 /// a clear win except on targets with multiple condition code registers
615 /// (PowerPC), where it might lose; some adjustment may be wanted there.
617 /// Return true if any changes are made.
618 static bool OptimizeCmpExpression(CmpInst *CI) {
619 BasicBlock *DefBB = CI->getParent();
621 /// InsertedCmp - Only insert a cmp in each block once.
622 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
624 bool MadeChange = false;
625 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
627 Use &TheUse = UI.getUse();
628 Instruction *User = cast<Instruction>(*UI);
630 // Preincrement use iterator so we don't invalidate it.
633 // Don't bother for PHI nodes.
634 if (isa<PHINode>(User))
637 // Figure out which BB this cmp is used in.
638 BasicBlock *UserBB = User->getParent();
640 // If this user is in the same block as the cmp, don't change the cmp.
641 if (UserBB == DefBB) continue;
643 // If we have already inserted a cmp into this block, use it.
644 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
647 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
649 CmpInst::Create(CI->getOpcode(),
650 CI->getPredicate(), CI->getOperand(0),
651 CI->getOperand(1), "", InsertPt);
655 // Replace a use of the cmp with a use of the new cmp.
656 TheUse = InsertedCmp;
660 // If we removed all uses, nuke the cmp.
662 CI->eraseFromParent();
667 /// isExtractBitsCandidateUse - Check if the candidates could
668 /// be combined with shift instruction, which includes:
669 /// 1. Truncate instruction
670 /// 2. And instruction and the imm is a mask of the low bits:
671 /// imm & (imm+1) == 0
672 static bool isExtractBitsCandidateUse(Instruction *User) {
673 if (!isa<TruncInst>(User)) {
674 if (User->getOpcode() != Instruction::And ||
675 !isa<ConstantInt>(User->getOperand(1)))
678 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
680 if ((Cimm & (Cimm + 1)).getBoolValue())
686 /// SinkShiftAndTruncate - sink both shift and truncate instruction
687 /// to the use of truncate's BB.
689 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
690 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
691 const TargetLowering &TLI) {
692 BasicBlock *UserBB = User->getParent();
693 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
694 TruncInst *TruncI = dyn_cast<TruncInst>(User);
695 bool MadeChange = false;
697 for (Value::user_iterator TruncUI = TruncI->user_begin(),
698 TruncE = TruncI->user_end();
699 TruncUI != TruncE;) {
701 Use &TruncTheUse = TruncUI.getUse();
702 Instruction *TruncUser = cast<Instruction>(*TruncUI);
703 // Preincrement use iterator so we don't invalidate it.
707 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
711 // If the use is actually a legal node, there will not be an
712 // implicit truncate.
713 // FIXME: always querying the result type is just an
714 // approximation; some nodes' legality is determined by the
715 // operand or other means. There's no good way to find out though.
716 if (TLI.isOperationLegalOrCustom(
717 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
720 // Don't bother for PHI nodes.
721 if (isa<PHINode>(TruncUser))
724 BasicBlock *TruncUserBB = TruncUser->getParent();
726 if (UserBB == TruncUserBB)
729 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
730 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
732 if (!InsertedShift && !InsertedTrunc) {
733 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
735 if (ShiftI->getOpcode() == Instruction::AShr)
737 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
740 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
743 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
746 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
747 TruncI->getType(), "", TruncInsertPt);
751 TruncTheUse = InsertedTrunc;
757 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
758 /// the uses could potentially be combined with this shift instruction and
759 /// generate BitExtract instruction. It will only be applied if the architecture
760 /// supports BitExtract instruction. Here is an example:
762 /// %x.extract.shift = lshr i64 %arg1, 32
764 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
768 /// %x.extract.shift.1 = lshr i64 %arg1, 32
769 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
771 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
773 /// Return true if any changes are made.
774 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
775 const TargetLowering &TLI) {
776 BasicBlock *DefBB = ShiftI->getParent();
778 /// Only insert instructions in each block once.
779 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
781 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
783 bool MadeChange = false;
784 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
786 Use &TheUse = UI.getUse();
787 Instruction *User = cast<Instruction>(*UI);
788 // Preincrement use iterator so we don't invalidate it.
791 // Don't bother for PHI nodes.
792 if (isa<PHINode>(User))
795 if (!isExtractBitsCandidateUse(User))
798 BasicBlock *UserBB = User->getParent();
800 if (UserBB == DefBB) {
801 // If the shift and truncate instruction are in the same BB. The use of
802 // the truncate(TruncUse) may still introduce another truncate if not
803 // legal. In this case, we would like to sink both shift and truncate
804 // instruction to the BB of TruncUse.
807 // i64 shift.result = lshr i64 opnd, imm
808 // trunc.result = trunc shift.result to i16
811 // ----> We will have an implicit truncate here if the architecture does
812 // not have i16 compare.
813 // cmp i16 trunc.result, opnd2
815 if (isa<TruncInst>(User) && shiftIsLegal
816 // If the type of the truncate is legal, no trucate will be
817 // introduced in other basic blocks.
818 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
820 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
824 // If we have already inserted a shift into this block, use it.
825 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
827 if (!InsertedShift) {
828 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
830 if (ShiftI->getOpcode() == Instruction::AShr)
832 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
835 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
840 // Replace a use of the shift with a use of the new shift.
841 TheUse = InsertedShift;
844 // If we removed all uses, nuke the shift.
845 if (ShiftI->use_empty())
846 ShiftI->eraseFromParent();
851 // ScalarizeMaskedLoad() translates masked load intrinsic, like
852 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
853 // <16 x i1> %mask, <16 x i32> %passthru)
854 // to a chain of basic blocks, whith loading element one-by-one if
855 // the appropriate mask bit is set
857 // %1 = bitcast i8* %addr to i32*
858 // %2 = extractelement <16 x i1> %mask, i32 0
859 // %3 = icmp eq i1 %2, true
860 // br i1 %3, label %cond.load, label %else
862 //cond.load: ; preds = %0
863 // %4 = getelementptr i32* %1, i32 0
865 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
868 //else: ; preds = %0, %cond.load
869 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
870 // %7 = extractelement <16 x i1> %mask, i32 1
871 // %8 = icmp eq i1 %7, true
872 // br i1 %8, label %cond.load1, label %else2
874 //cond.load1: ; preds = %else
875 // %9 = getelementptr i32* %1, i32 1
876 // %10 = load i32* %9
877 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
880 //else2: ; preds = %else, %cond.load1
881 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
882 // %12 = extractelement <16 x i1> %mask, i32 2
883 // %13 = icmp eq i1 %12, true
884 // br i1 %13, label %cond.load4, label %else5
886 static void ScalarizeMaskedLoad(CallInst *CI) {
887 Value *Ptr = CI->getArgOperand(0);
888 Value *Src0 = CI->getArgOperand(3);
889 Value *Mask = CI->getArgOperand(2);
890 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
891 Type *EltTy = VecType->getElementType();
893 assert(VecType && "Unexpected return type of masked load intrinsic");
895 IRBuilder<> Builder(CI->getContext());
896 Instruction *InsertPt = CI;
897 BasicBlock *IfBlock = CI->getParent();
898 BasicBlock *CondBlock = nullptr;
899 BasicBlock *PrevIfBlock = CI->getParent();
900 Builder.SetInsertPoint(InsertPt);
902 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
904 // Bitcast %addr fron i8* to EltTy*
906 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
907 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
908 Value *UndefVal = UndefValue::get(VecType);
911 Value *VResult = UndefVal;
913 PHINode *Phi = nullptr;
914 Value *PrevPhi = UndefVal;
916 unsigned VectorWidth = VecType->getNumElements();
917 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
919 // Fill the "else" block, created in the previous iteration
921 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
922 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
923 // %to_load = icmp eq i1 %mask_1, true
924 // br i1 %to_load, label %cond.load, label %else
927 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
928 Phi->addIncoming(VResult, CondBlock);
929 Phi->addIncoming(PrevPhi, PrevIfBlock);
934 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
935 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
936 ConstantInt::get(Predicate->getType(), 1));
938 // Create "cond" block
940 // %EltAddr = getelementptr i32* %1, i32 0
941 // %Elt = load i32* %EltAddr
942 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
944 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
945 Builder.SetInsertPoint(InsertPt);
947 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
948 LoadInst* Load = Builder.CreateLoad(Gep, false);
949 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
951 // Create "else" block, fill it in the next iteration
952 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
953 Builder.SetInsertPoint(InsertPt);
954 Instruction *OldBr = IfBlock->getTerminator();
955 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
956 OldBr->eraseFromParent();
957 PrevIfBlock = IfBlock;
958 IfBlock = NewIfBlock;
961 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
962 Phi->addIncoming(VResult, CondBlock);
963 Phi->addIncoming(PrevPhi, PrevIfBlock);
964 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
965 CI->replaceAllUsesWith(NewI);
966 CI->eraseFromParent();
969 // ScalarizeMaskedStore() translates masked store intrinsic, like
970 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
972 // to a chain of basic blocks, that stores element one-by-one if
973 // the appropriate mask bit is set
975 // %1 = bitcast i8* %addr to i32*
976 // %2 = extractelement <16 x i1> %mask, i32 0
977 // %3 = icmp eq i1 %2, true
978 // br i1 %3, label %cond.store, label %else
980 // cond.store: ; preds = %0
981 // %4 = extractelement <16 x i32> %val, i32 0
982 // %5 = getelementptr i32* %1, i32 0
983 // store i32 %4, i32* %5
986 // else: ; preds = %0, %cond.store
987 // %6 = extractelement <16 x i1> %mask, i32 1
988 // %7 = icmp eq i1 %6, true
989 // br i1 %7, label %cond.store1, label %else2
991 // cond.store1: ; preds = %else
992 // %8 = extractelement <16 x i32> %val, i32 1
993 // %9 = getelementptr i32* %1, i32 1
994 // store i32 %8, i32* %9
997 static void ScalarizeMaskedStore(CallInst *CI) {
998 Value *Ptr = CI->getArgOperand(1);
999 Value *Src = CI->getArgOperand(0);
1000 Value *Mask = CI->getArgOperand(3);
1002 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1003 Type *EltTy = VecType->getElementType();
1005 assert(VecType && "Unexpected data type in masked store intrinsic");
1007 IRBuilder<> Builder(CI->getContext());
1008 Instruction *InsertPt = CI;
1009 BasicBlock *IfBlock = CI->getParent();
1010 Builder.SetInsertPoint(InsertPt);
1011 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1013 // Bitcast %addr fron i8* to EltTy*
1015 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1016 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1018 unsigned VectorWidth = VecType->getNumElements();
1019 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1021 // Fill the "else" block, created in the previous iteration
1023 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1024 // %to_store = icmp eq i1 %mask_1, true
1025 // br i1 %to_load, label %cond.store, label %else
1027 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1028 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1029 ConstantInt::get(Predicate->getType(), 1));
1031 // Create "cond" block
1033 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1034 // %EltAddr = getelementptr i32* %1, i32 0
1035 // %store i32 %OneElt, i32* %EltAddr
1037 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1038 Builder.SetInsertPoint(InsertPt);
1040 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1041 Value* Gep = Builder.CreateInBoundsGEP(FirstEltPtr, Builder.getInt32(Idx));
1042 Builder.CreateStore(OneElt, Gep);
1044 // Create "else" block, fill it in the next iteration
1045 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1046 Builder.SetInsertPoint(InsertPt);
1047 Instruction *OldBr = IfBlock->getTerminator();
1048 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1049 OldBr->eraseFromParent();
1050 IfBlock = NewIfBlock;
1052 CI->eraseFromParent();
1055 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
1056 BasicBlock *BB = CI->getParent();
1058 // Lower inline assembly if we can.
1059 // If we found an inline asm expession, and if the target knows how to
1060 // lower it to normal LLVM code, do so now.
1061 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1062 if (TLI->ExpandInlineAsm(CI)) {
1063 // Avoid invalidating the iterator.
1064 CurInstIterator = BB->begin();
1065 // Avoid processing instructions out of order, which could cause
1066 // reuse before a value is defined.
1070 // Sink address computing for memory operands into the block.
1071 if (OptimizeInlineAsmInst(CI))
1075 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1077 switch (II->getIntrinsicID()) {
1079 case Intrinsic::objectsize: {
1080 // Lower all uses of llvm.objectsize.*
1081 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1082 Type *ReturnTy = CI->getType();
1083 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
1085 // Substituting this can cause recursive simplifications, which can
1086 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1088 WeakVH IterHandle(CurInstIterator);
1090 replaceAndRecursivelySimplify(CI, RetVal,
1091 TLI ? TLI->getDataLayout() : nullptr,
1092 TLInfo, ModifiedDT ? nullptr : DT);
1094 // If the iterator instruction was recursively deleted, start over at the
1095 // start of the block.
1096 if (IterHandle != CurInstIterator) {
1097 CurInstIterator = BB->begin();
1102 case Intrinsic::masked_load: {
1103 // Scalarize unsupported vector masked load
1104 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1105 ScalarizeMaskedLoad(CI);
1111 case Intrinsic::masked_store: {
1112 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1113 ScalarizeMaskedStore(CI);
1122 SmallVector<Value*, 2> PtrOps;
1124 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
1125 while (!PtrOps.empty())
1126 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
1131 // From here on out we're working with named functions.
1132 if (!CI->getCalledFunction()) return false;
1134 // We'll need DataLayout from here on out.
1135 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
1136 if (!TD) return false;
1138 // Lower all default uses of _chk calls. This is very similar
1139 // to what InstCombineCalls does, but here we are only lowering calls
1140 // to fortified library functions (e.g. __memcpy_chk) that have the default
1141 // "don't know" as the objectsize. Anything else should be left alone.
1142 FortifiedLibCallSimplifier Simplifier(TD, TLInfo, true);
1143 if (Value *V = Simplifier.optimizeCall(CI)) {
1144 CI->replaceAllUsesWith(V);
1145 CI->eraseFromParent();
1151 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1152 /// instructions to the predecessor to enable tail call optimizations. The
1153 /// case it is currently looking for is:
1156 /// %tmp0 = tail call i32 @f0()
1157 /// br label %return
1159 /// %tmp1 = tail call i32 @f1()
1160 /// br label %return
1162 /// %tmp2 = tail call i32 @f2()
1163 /// br label %return
1165 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1173 /// %tmp0 = tail call i32 @f0()
1176 /// %tmp1 = tail call i32 @f1()
1179 /// %tmp2 = tail call i32 @f2()
1182 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
1186 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1190 PHINode *PN = nullptr;
1191 BitCastInst *BCI = nullptr;
1192 Value *V = RI->getReturnValue();
1194 BCI = dyn_cast<BitCastInst>(V);
1196 V = BCI->getOperand(0);
1198 PN = dyn_cast<PHINode>(V);
1203 if (PN && PN->getParent() != BB)
1206 // It's not safe to eliminate the sign / zero extension of the return value.
1207 // See llvm::isInTailCallPosition().
1208 const Function *F = BB->getParent();
1209 AttributeSet CallerAttrs = F->getAttributes();
1210 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1211 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1214 // Make sure there are no instructions between the PHI and return, or that the
1215 // return is the first instruction in the block.
1217 BasicBlock::iterator BI = BB->begin();
1218 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
1220 // Also skip over the bitcast.
1225 BasicBlock::iterator BI = BB->begin();
1226 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1231 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1233 SmallVector<CallInst*, 4> TailCalls;
1235 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1236 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1237 // Make sure the phi value is indeed produced by the tail call.
1238 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1239 TLI->mayBeEmittedAsTailCall(CI))
1240 TailCalls.push_back(CI);
1243 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1244 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1245 if (!VisitedBBs.insert(*PI).second)
1248 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1249 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1250 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1251 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1255 CallInst *CI = dyn_cast<CallInst>(&*RI);
1256 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1257 TailCalls.push_back(CI);
1261 bool Changed = false;
1262 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1263 CallInst *CI = TailCalls[i];
1266 // Conservatively require the attributes of the call to match those of the
1267 // return. Ignore noalias because it doesn't affect the call sequence.
1268 AttributeSet CalleeAttrs = CS.getAttributes();
1269 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1270 removeAttribute(Attribute::NoAlias) !=
1271 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1272 removeAttribute(Attribute::NoAlias))
1275 // Make sure the call instruction is followed by an unconditional branch to
1276 // the return block.
1277 BasicBlock *CallBB = CI->getParent();
1278 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1279 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1282 // Duplicate the return into CallBB.
1283 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1284 ModifiedDT = Changed = true;
1288 // If we eliminated all predecessors of the block, delete the block now.
1289 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1290 BB->eraseFromParent();
1295 //===----------------------------------------------------------------------===//
1296 // Memory Optimization
1297 //===----------------------------------------------------------------------===//
1301 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1302 /// which holds actual Value*'s for register values.
1303 struct ExtAddrMode : public TargetLowering::AddrMode {
1306 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1307 void print(raw_ostream &OS) const;
1310 bool operator==(const ExtAddrMode& O) const {
1311 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1312 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1313 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1318 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1324 void ExtAddrMode::print(raw_ostream &OS) const {
1325 bool NeedPlus = false;
1328 OS << (NeedPlus ? " + " : "")
1330 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1335 OS << (NeedPlus ? " + " : "")
1341 OS << (NeedPlus ? " + " : "")
1343 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1347 OS << (NeedPlus ? " + " : "")
1349 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1355 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1356 void ExtAddrMode::dump() const {
1362 /// \brief This class provides transaction based operation on the IR.
1363 /// Every change made through this class is recorded in the internal state and
1364 /// can be undone (rollback) until commit is called.
1365 class TypePromotionTransaction {
1367 /// \brief This represents the common interface of the individual transaction.
1368 /// Each class implements the logic for doing one specific modification on
1369 /// the IR via the TypePromotionTransaction.
1370 class TypePromotionAction {
1372 /// The Instruction modified.
1376 /// \brief Constructor of the action.
1377 /// The constructor performs the related action on the IR.
1378 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1380 virtual ~TypePromotionAction() {}
1382 /// \brief Undo the modification done by this action.
1383 /// When this method is called, the IR must be in the same state as it was
1384 /// before this action was applied.
1385 /// \pre Undoing the action works if and only if the IR is in the exact same
1386 /// state as it was directly after this action was applied.
1387 virtual void undo() = 0;
1389 /// \brief Advocate every change made by this action.
1390 /// When the results on the IR of the action are to be kept, it is important
1391 /// to call this function, otherwise hidden information may be kept forever.
1392 virtual void commit() {
1393 // Nothing to be done, this action is not doing anything.
1397 /// \brief Utility to remember the position of an instruction.
1398 class InsertionHandler {
1399 /// Position of an instruction.
1400 /// Either an instruction:
1401 /// - Is the first in a basic block: BB is used.
1402 /// - Has a previous instructon: PrevInst is used.
1404 Instruction *PrevInst;
1407 /// Remember whether or not the instruction had a previous instruction.
1408 bool HasPrevInstruction;
1411 /// \brief Record the position of \p Inst.
1412 InsertionHandler(Instruction *Inst) {
1413 BasicBlock::iterator It = Inst;
1414 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1415 if (HasPrevInstruction)
1416 Point.PrevInst = --It;
1418 Point.BB = Inst->getParent();
1421 /// \brief Insert \p Inst at the recorded position.
1422 void insert(Instruction *Inst) {
1423 if (HasPrevInstruction) {
1424 if (Inst->getParent())
1425 Inst->removeFromParent();
1426 Inst->insertAfter(Point.PrevInst);
1428 Instruction *Position = Point.BB->getFirstInsertionPt();
1429 if (Inst->getParent())
1430 Inst->moveBefore(Position);
1432 Inst->insertBefore(Position);
1437 /// \brief Move an instruction before another.
1438 class InstructionMoveBefore : public TypePromotionAction {
1439 /// Original position of the instruction.
1440 InsertionHandler Position;
1443 /// \brief Move \p Inst before \p Before.
1444 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1445 : TypePromotionAction(Inst), Position(Inst) {
1446 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1447 Inst->moveBefore(Before);
1450 /// \brief Move the instruction back to its original position.
1451 void undo() override {
1452 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1453 Position.insert(Inst);
1457 /// \brief Set the operand of an instruction with a new value.
1458 class OperandSetter : public TypePromotionAction {
1459 /// Original operand of the instruction.
1461 /// Index of the modified instruction.
1465 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1466 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1467 : TypePromotionAction(Inst), Idx(Idx) {
1468 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1469 << "for:" << *Inst << "\n"
1470 << "with:" << *NewVal << "\n");
1471 Origin = Inst->getOperand(Idx);
1472 Inst->setOperand(Idx, NewVal);
1475 /// \brief Restore the original value of the instruction.
1476 void undo() override {
1477 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1478 << "for: " << *Inst << "\n"
1479 << "with: " << *Origin << "\n");
1480 Inst->setOperand(Idx, Origin);
1484 /// \brief Hide the operands of an instruction.
1485 /// Do as if this instruction was not using any of its operands.
1486 class OperandsHider : public TypePromotionAction {
1487 /// The list of original operands.
1488 SmallVector<Value *, 4> OriginalValues;
1491 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1492 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1493 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1494 unsigned NumOpnds = Inst->getNumOperands();
1495 OriginalValues.reserve(NumOpnds);
1496 for (unsigned It = 0; It < NumOpnds; ++It) {
1497 // Save the current operand.
1498 Value *Val = Inst->getOperand(It);
1499 OriginalValues.push_back(Val);
1501 // We could use OperandSetter here, but that would implied an overhead
1502 // that we are not willing to pay.
1503 Inst->setOperand(It, UndefValue::get(Val->getType()));
1507 /// \brief Restore the original list of uses.
1508 void undo() override {
1509 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1510 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1511 Inst->setOperand(It, OriginalValues[It]);
1515 /// \brief Build a truncate instruction.
1516 class TruncBuilder : public TypePromotionAction {
1519 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1521 /// trunc Opnd to Ty.
1522 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1523 IRBuilder<> Builder(Opnd);
1524 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1525 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1528 /// \brief Get the built value.
1529 Value *getBuiltValue() { return Val; }
1531 /// \brief Remove the built instruction.
1532 void undo() override {
1533 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1534 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1535 IVal->eraseFromParent();
1539 /// \brief Build a sign extension instruction.
1540 class SExtBuilder : public TypePromotionAction {
1543 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1545 /// sext Opnd to Ty.
1546 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1547 : TypePromotionAction(InsertPt) {
1548 IRBuilder<> Builder(InsertPt);
1549 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1550 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1553 /// \brief Get the built value.
1554 Value *getBuiltValue() { return Val; }
1556 /// \brief Remove the built instruction.
1557 void undo() override {
1558 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1559 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1560 IVal->eraseFromParent();
1564 /// \brief Build a zero extension instruction.
1565 class ZExtBuilder : public TypePromotionAction {
1568 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1570 /// zext Opnd to Ty.
1571 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1572 : TypePromotionAction(InsertPt) {
1573 IRBuilder<> Builder(InsertPt);
1574 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1575 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1578 /// \brief Get the built value.
1579 Value *getBuiltValue() { return Val; }
1581 /// \brief Remove the built instruction.
1582 void undo() override {
1583 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1584 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1585 IVal->eraseFromParent();
1589 /// \brief Mutate an instruction to another type.
1590 class TypeMutator : public TypePromotionAction {
1591 /// Record the original type.
1595 /// \brief Mutate the type of \p Inst into \p NewTy.
1596 TypeMutator(Instruction *Inst, Type *NewTy)
1597 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1598 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1600 Inst->mutateType(NewTy);
1603 /// \brief Mutate the instruction back to its original type.
1604 void undo() override {
1605 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1607 Inst->mutateType(OrigTy);
1611 /// \brief Replace the uses of an instruction by another instruction.
1612 class UsesReplacer : public TypePromotionAction {
1613 /// Helper structure to keep track of the replaced uses.
1614 struct InstructionAndIdx {
1615 /// The instruction using the instruction.
1617 /// The index where this instruction is used for Inst.
1619 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1620 : Inst(Inst), Idx(Idx) {}
1623 /// Keep track of the original uses (pair Instruction, Index).
1624 SmallVector<InstructionAndIdx, 4> OriginalUses;
1625 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1628 /// \brief Replace all the use of \p Inst by \p New.
1629 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1630 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1632 // Record the original uses.
1633 for (Use &U : Inst->uses()) {
1634 Instruction *UserI = cast<Instruction>(U.getUser());
1635 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1637 // Now, we can replace the uses.
1638 Inst->replaceAllUsesWith(New);
1641 /// \brief Reassign the original uses of Inst to Inst.
1642 void undo() override {
1643 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1644 for (use_iterator UseIt = OriginalUses.begin(),
1645 EndIt = OriginalUses.end();
1646 UseIt != EndIt; ++UseIt) {
1647 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1652 /// \brief Remove an instruction from the IR.
1653 class InstructionRemover : public TypePromotionAction {
1654 /// Original position of the instruction.
1655 InsertionHandler Inserter;
1656 /// Helper structure to hide all the link to the instruction. In other
1657 /// words, this helps to do as if the instruction was removed.
1658 OperandsHider Hider;
1659 /// Keep track of the uses replaced, if any.
1660 UsesReplacer *Replacer;
1663 /// \brief Remove all reference of \p Inst and optinally replace all its
1665 /// \pre If !Inst->use_empty(), then New != nullptr
1666 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1667 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1670 Replacer = new UsesReplacer(Inst, New);
1671 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1672 Inst->removeFromParent();
1675 ~InstructionRemover() { delete Replacer; }
1677 /// \brief Really remove the instruction.
1678 void commit() override { delete Inst; }
1680 /// \brief Resurrect the instruction and reassign it to the proper uses if
1681 /// new value was provided when build this action.
1682 void undo() override {
1683 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1684 Inserter.insert(Inst);
1692 /// Restoration point.
1693 /// The restoration point is a pointer to an action instead of an iterator
1694 /// because the iterator may be invalidated but not the pointer.
1695 typedef const TypePromotionAction *ConstRestorationPt;
1696 /// Advocate every changes made in that transaction.
1698 /// Undo all the changes made after the given point.
1699 void rollback(ConstRestorationPt Point);
1700 /// Get the current restoration point.
1701 ConstRestorationPt getRestorationPoint() const;
1703 /// \name API for IR modification with state keeping to support rollback.
1705 /// Same as Instruction::setOperand.
1706 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1707 /// Same as Instruction::eraseFromParent.
1708 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1709 /// Same as Value::replaceAllUsesWith.
1710 void replaceAllUsesWith(Instruction *Inst, Value *New);
1711 /// Same as Value::mutateType.
1712 void mutateType(Instruction *Inst, Type *NewTy);
1713 /// Same as IRBuilder::createTrunc.
1714 Value *createTrunc(Instruction *Opnd, Type *Ty);
1715 /// Same as IRBuilder::createSExt.
1716 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1717 /// Same as IRBuilder::createZExt.
1718 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1719 /// Same as Instruction::moveBefore.
1720 void moveBefore(Instruction *Inst, Instruction *Before);
1724 /// The ordered list of actions made so far.
1725 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1726 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1729 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1732 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1735 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1738 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1741 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1743 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1746 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1747 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1750 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1752 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1753 Value *Val = Ptr->getBuiltValue();
1754 Actions.push_back(std::move(Ptr));
1758 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1759 Value *Opnd, Type *Ty) {
1760 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1761 Value *Val = Ptr->getBuiltValue();
1762 Actions.push_back(std::move(Ptr));
1766 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1767 Value *Opnd, Type *Ty) {
1768 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1769 Value *Val = Ptr->getBuiltValue();
1770 Actions.push_back(std::move(Ptr));
1774 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1775 Instruction *Before) {
1777 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1780 TypePromotionTransaction::ConstRestorationPt
1781 TypePromotionTransaction::getRestorationPoint() const {
1782 return !Actions.empty() ? Actions.back().get() : nullptr;
1785 void TypePromotionTransaction::commit() {
1786 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1792 void TypePromotionTransaction::rollback(
1793 TypePromotionTransaction::ConstRestorationPt Point) {
1794 while (!Actions.empty() && Point != Actions.back().get()) {
1795 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1800 /// \brief A helper class for matching addressing modes.
1802 /// This encapsulates the logic for matching the target-legal addressing modes.
1803 class AddressingModeMatcher {
1804 SmallVectorImpl<Instruction*> &AddrModeInsts;
1805 const TargetLowering &TLI;
1807 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1808 /// the memory instruction that we're computing this address for.
1810 Instruction *MemoryInst;
1812 /// AddrMode - This is the addressing mode that we're building up. This is
1813 /// part of the return value of this addressing mode matching stuff.
1814 ExtAddrMode &AddrMode;
1816 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1817 const SetOfInstrs &InsertedTruncs;
1818 /// A map from the instructions to their type before promotion.
1819 InstrToOrigTy &PromotedInsts;
1820 /// The ongoing transaction where every action should be registered.
1821 TypePromotionTransaction &TPT;
1823 /// IgnoreProfitability - This is set to true when we should not do
1824 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1825 /// always returns true.
1826 bool IgnoreProfitability;
1828 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1829 const TargetLowering &T, Type *AT,
1830 Instruction *MI, ExtAddrMode &AM,
1831 const SetOfInstrs &InsertedTruncs,
1832 InstrToOrigTy &PromotedInsts,
1833 TypePromotionTransaction &TPT)
1834 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1835 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1836 IgnoreProfitability = false;
1840 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1841 /// give an access type of AccessTy. This returns a list of involved
1842 /// instructions in AddrModeInsts.
1843 /// \p InsertedTruncs The truncate instruction inserted by other
1846 /// \p PromotedInsts maps the instructions to their type before promotion.
1847 /// \p The ongoing transaction where every action should be registered.
1848 static ExtAddrMode Match(Value *V, Type *AccessTy,
1849 Instruction *MemoryInst,
1850 SmallVectorImpl<Instruction*> &AddrModeInsts,
1851 const TargetLowering &TLI,
1852 const SetOfInstrs &InsertedTruncs,
1853 InstrToOrigTy &PromotedInsts,
1854 TypePromotionTransaction &TPT) {
1857 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1858 MemoryInst, Result, InsertedTruncs,
1859 PromotedInsts, TPT).MatchAddr(V, 0);
1860 (void)Success; assert(Success && "Couldn't select *anything*?");
1864 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1865 bool MatchAddr(Value *V, unsigned Depth);
1866 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1867 bool *MovedAway = nullptr);
1868 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1869 ExtAddrMode &AMBefore,
1870 ExtAddrMode &AMAfter);
1871 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1872 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1873 Value *PromotedOperand) const;
1876 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1877 /// Return true and update AddrMode if this addr mode is legal for the target,
1879 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1881 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1882 // mode. Just process that directly.
1884 return MatchAddr(ScaleReg, Depth);
1886 // If the scale is 0, it takes nothing to add this.
1890 // If we already have a scale of this value, we can add to it, otherwise, we
1891 // need an available scale field.
1892 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1895 ExtAddrMode TestAddrMode = AddrMode;
1897 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1898 // [A+B + A*7] -> [B+A*8].
1899 TestAddrMode.Scale += Scale;
1900 TestAddrMode.ScaledReg = ScaleReg;
1902 // If the new address isn't legal, bail out.
1903 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1906 // It was legal, so commit it.
1907 AddrMode = TestAddrMode;
1909 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1910 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1911 // X*Scale + C*Scale to addr mode.
1912 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1913 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1914 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1915 TestAddrMode.ScaledReg = AddLHS;
1916 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1918 // If this addressing mode is legal, commit it and remember that we folded
1919 // this instruction.
1920 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1921 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1922 AddrMode = TestAddrMode;
1927 // Otherwise, not (x+c)*scale, just return what we have.
1931 /// MightBeFoldableInst - This is a little filter, which returns true if an
1932 /// addressing computation involving I might be folded into a load/store
1933 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1934 /// the set of instructions that MatchOperationAddr can.
1935 static bool MightBeFoldableInst(Instruction *I) {
1936 switch (I->getOpcode()) {
1937 case Instruction::BitCast:
1938 case Instruction::AddrSpaceCast:
1939 // Don't touch identity bitcasts.
1940 if (I->getType() == I->getOperand(0)->getType())
1942 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1943 case Instruction::PtrToInt:
1944 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1946 case Instruction::IntToPtr:
1947 // We know the input is intptr_t, so this is foldable.
1949 case Instruction::Add:
1951 case Instruction::Mul:
1952 case Instruction::Shl:
1953 // Can only handle X*C and X << C.
1954 return isa<ConstantInt>(I->getOperand(1));
1955 case Instruction::GetElementPtr:
1962 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
1963 /// \note \p Val is assumed to be the product of some type promotion.
1964 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
1965 /// to be legal, as the non-promoted value would have had the same state.
1966 static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
1967 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
1970 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1971 // If the ISDOpcode is undefined, it was undefined before the promotion.
1974 // Otherwise, check if the promoted instruction is legal or not.
1975 return TLI.isOperationLegalOrCustom(
1976 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
1979 /// \brief Hepler class to perform type promotion.
1980 class TypePromotionHelper {
1981 /// \brief Utility function to check whether or not a sign or zero extension
1982 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1983 /// either using the operands of \p Inst or promoting \p Inst.
1984 /// The type of the extension is defined by \p IsSExt.
1985 /// In other words, check if:
1986 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
1987 /// #1 Promotion applies:
1988 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
1989 /// #2 Operand reuses:
1990 /// ext opnd1 to ConsideredExtType.
1991 /// \p PromotedInsts maps the instructions to their type before promotion.
1992 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1993 const InstrToOrigTy &PromotedInsts, bool IsSExt);
1995 /// \brief Utility function to determine if \p OpIdx should be promoted when
1996 /// promoting \p Inst.
1997 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
1998 if (isa<SelectInst>(Inst) && OpIdx == 0)
2003 /// \brief Utility function to promote the operand of \p Ext when this
2004 /// operand is a promotable trunc or sext or zext.
2005 /// \p PromotedInsts maps the instructions to their type before promotion.
2006 /// \p CreatedInsts[out] contains how many non-free instructions have been
2007 /// created to promote the operand of Ext.
2008 /// Newly added extensions are inserted in \p Exts.
2009 /// Newly added truncates are inserted in \p Truncs.
2010 /// Should never be called directly.
2011 /// \return The promoted value which is used instead of Ext.
2012 static Value *promoteOperandForTruncAndAnyExt(
2013 Instruction *Ext, TypePromotionTransaction &TPT,
2014 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2015 SmallVectorImpl<Instruction *> *Exts,
2016 SmallVectorImpl<Instruction *> *Truncs);
2018 /// \brief Utility function to promote the operand of \p Ext when this
2019 /// operand is promotable and is not a supported trunc or sext.
2020 /// \p PromotedInsts maps the instructions to their type before promotion.
2021 /// \p CreatedInsts[out] contains how many non-free instructions have been
2022 /// created to promote the operand of Ext.
2023 /// Newly added extensions are inserted in \p Exts.
2024 /// Newly added truncates are inserted in \p Truncs.
2025 /// Should never be called directly.
2026 /// \return The promoted value which is used instead of Ext.
2028 promoteOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2029 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2030 SmallVectorImpl<Instruction *> *Exts,
2031 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt);
2033 /// \see promoteOperandForOther.
2035 signExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2036 InstrToOrigTy &PromotedInsts,
2037 unsigned &CreatedInsts,
2038 SmallVectorImpl<Instruction *> *Exts,
2039 SmallVectorImpl<Instruction *> *Truncs) {
2040 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2044 /// \see promoteOperandForOther.
2046 zeroExtendOperandForOther(Instruction *Ext, TypePromotionTransaction &TPT,
2047 InstrToOrigTy &PromotedInsts,
2048 unsigned &CreatedInsts,
2049 SmallVectorImpl<Instruction *> *Exts,
2050 SmallVectorImpl<Instruction *> *Truncs) {
2051 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, Exts,
2056 /// Type for the utility function that promotes the operand of Ext.
2057 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2058 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2059 SmallVectorImpl<Instruction *> *Exts,
2060 SmallVectorImpl<Instruction *> *Truncs);
2061 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2062 /// action to promote the operand of \p Ext instead of using Ext.
2063 /// \return NULL if no promotable action is possible with the current
2065 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
2066 /// the others CodeGenPrepare optimizations. This information is important
2067 /// because we do not want to promote these instructions as CodeGenPrepare
2068 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2069 /// \p PromotedInsts maps the instructions to their type before promotion.
2070 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2071 const TargetLowering &TLI,
2072 const InstrToOrigTy &PromotedInsts);
2075 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2076 Type *ConsideredExtType,
2077 const InstrToOrigTy &PromotedInsts,
2079 // The promotion helper does not know how to deal with vector types yet.
2080 // To be able to fix that, we would need to fix the places where we
2081 // statically extend, e.g., constants and such.
2082 if (Inst->getType()->isVectorTy())
2085 // We can always get through zext.
2086 if (isa<ZExtInst>(Inst))
2089 // sext(sext) is ok too.
2090 if (IsSExt && isa<SExtInst>(Inst))
2093 // We can get through binary operator, if it is legal. In other words, the
2094 // binary operator must have a nuw or nsw flag.
2095 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2096 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
2097 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2098 (IsSExt && BinOp->hasNoSignedWrap())))
2101 // Check if we can do the following simplification.
2102 // ext(trunc(opnd)) --> ext(opnd)
2103 if (!isa<TruncInst>(Inst))
2106 Value *OpndVal = Inst->getOperand(0);
2107 // Check if we can use this operand in the extension.
2108 // If the type is larger than the result type of the extension,
2110 if (!OpndVal->getType()->isIntegerTy() ||
2111 OpndVal->getType()->getIntegerBitWidth() >
2112 ConsideredExtType->getIntegerBitWidth())
2115 // If the operand of the truncate is not an instruction, we will not have
2116 // any information on the dropped bits.
2117 // (Actually we could for constant but it is not worth the extra logic).
2118 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2122 // Check if the source of the type is narrow enough.
2123 // I.e., check that trunc just drops extended bits of the same kind of
2125 // #1 get the type of the operand and check the kind of the extended bits.
2126 const Type *OpndType;
2127 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
2128 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2129 OpndType = It->second.Ty;
2130 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2131 OpndType = Opnd->getOperand(0)->getType();
2135 // #2 check that the truncate just drop extended bits.
2136 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2142 TypePromotionHelper::Action TypePromotionHelper::getAction(
2143 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
2144 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
2145 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2146 "Unexpected instruction type");
2147 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2148 Type *ExtTy = Ext->getType();
2149 bool IsSExt = isa<SExtInst>(Ext);
2150 // If the operand of the extension is not an instruction, we cannot
2152 // If it, check we can get through.
2153 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
2156 // Do not promote if the operand has been added by codegenprepare.
2157 // Otherwise, it means we are undoing an optimization that is likely to be
2158 // redone, thus causing potential infinite loop.
2159 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
2162 // SExt or Trunc instructions.
2163 // Return the related handler.
2164 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2165 isa<ZExtInst>(ExtOpnd))
2166 return promoteOperandForTruncAndAnyExt;
2168 // Regular instruction.
2169 // Abort early if we will have to insert non-free instructions.
2170 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
2172 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
2175 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
2176 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2177 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2178 SmallVectorImpl<Instruction *> *Exts,
2179 SmallVectorImpl<Instruction *> *Truncs) {
2180 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2181 // get through it and this method should not be called.
2182 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
2183 Value *ExtVal = SExt;
2184 if (isa<ZExtInst>(SExtOpnd)) {
2185 // Replace s|zext(zext(opnd))
2188 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2189 TPT.replaceAllUsesWith(SExt, ZExt);
2190 TPT.eraseInstruction(SExt);
2193 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2195 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2199 // Remove dead code.
2200 if (SExtOpnd->use_empty())
2201 TPT.eraseInstruction(SExtOpnd);
2203 // Check if the extension is still needed.
2204 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
2205 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2206 if (ExtInst && Exts)
2207 Exts->push_back(ExtInst);
2211 // At this point we have: ext ty opnd to ty.
2212 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2213 Value *NextVal = ExtInst->getOperand(0);
2214 TPT.eraseInstruction(ExtInst, NextVal);
2218 Value *TypePromotionHelper::promoteOperandForOther(
2219 Instruction *Ext, TypePromotionTransaction &TPT,
2220 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts,
2221 SmallVectorImpl<Instruction *> *Exts,
2222 SmallVectorImpl<Instruction *> *Truncs, bool IsSExt) {
2223 // By construction, the operand of Ext is an instruction. Otherwise we cannot
2224 // get through it and this method should not be called.
2225 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2227 if (!ExtOpnd->hasOneUse()) {
2228 // ExtOpnd will be promoted.
2229 // All its uses, but Ext, will need to use a truncated value of the
2230 // promoted version.
2231 // Create the truncate now.
2232 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2233 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2234 ITrunc->removeFromParent();
2235 // Insert it just after the definition.
2236 ITrunc->insertAfter(ExtOpnd);
2238 Truncs->push_back(ITrunc);
2241 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2242 // Restore the operand of Ext (which has been replace by the previous call
2243 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2244 TPT.setOperand(Ext, 0, ExtOpnd);
2247 // Get through the Instruction:
2248 // 1. Update its type.
2249 // 2. Replace the uses of Ext by Inst.
2250 // 3. Extend each operand that needs to be extended.
2252 // Remember the original type of the instruction before promotion.
2253 // This is useful to know that the high bits are sign extended bits.
2254 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2255 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2257 TPT.mutateType(ExtOpnd, Ext->getType());
2259 TPT.replaceAllUsesWith(Ext, ExtOpnd);
2261 Instruction *ExtForOpnd = Ext;
2263 DEBUG(dbgs() << "Propagate Ext to operands\n");
2264 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2266 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2267 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2268 !shouldExtOperand(ExtOpnd, OpIdx)) {
2269 DEBUG(dbgs() << "No need to propagate\n");
2272 // Check if we can statically extend the operand.
2273 Value *Opnd = ExtOpnd->getOperand(OpIdx);
2274 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2275 DEBUG(dbgs() << "Statically extend\n");
2276 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2277 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2278 : Cst->getValue().zext(BitWidth);
2279 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2282 // UndefValue are typed, so we have to statically sign extend them.
2283 if (isa<UndefValue>(Opnd)) {
2284 DEBUG(dbgs() << "Statically extend\n");
2285 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2289 // Otherwise we have to explicity sign extend the operand.
2290 // Check if Ext was reused to extend an operand.
2292 // If yes, create a new one.
2293 DEBUG(dbgs() << "More operands to ext\n");
2294 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2295 : TPT.createZExt(Ext, Opnd, Ext->getType());
2296 if (!isa<Instruction>(ValForExtOpnd)) {
2297 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2300 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
2304 Exts->push_back(ExtForOpnd);
2305 TPT.setOperand(ExtForOpnd, 0, Opnd);
2307 // Move the sign extension before the insertion point.
2308 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2309 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2310 // If more sext are required, new instructions will have to be created.
2311 ExtForOpnd = nullptr;
2313 if (ExtForOpnd == Ext) {
2314 DEBUG(dbgs() << "Extension is useless now\n");
2315 TPT.eraseInstruction(Ext);
2320 /// IsPromotionProfitable - Check whether or not promoting an instruction
2321 /// to a wider type was profitable.
2322 /// \p MatchedSize gives the number of instructions that have been matched
2323 /// in the addressing mode after the promotion was applied.
2324 /// \p SizeWithPromotion gives the number of created instructions for
2325 /// the promotion plus the number of instructions that have been
2326 /// matched in the addressing mode before the promotion.
2327 /// \p PromotedOperand is the value that has been promoted.
2328 /// \return True if the promotion is profitable, false otherwise.
2330 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2331 unsigned SizeWithPromotion,
2332 Value *PromotedOperand) const {
2333 // We folded less instructions than what we created to promote the operand.
2334 // This is not profitable.
2335 if (MatchedSize < SizeWithPromotion)
2337 if (MatchedSize > SizeWithPromotion)
2339 // The promotion is neutral but it may help folding the sign extension in
2340 // loads for instance.
2341 // Check that we did not create an illegal instruction.
2342 return isPromotedInstructionLegal(TLI, PromotedOperand);
2345 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2346 /// fold the operation into the addressing mode. If so, update the addressing
2347 /// mode and return true, otherwise return false without modifying AddrMode.
2348 /// If \p MovedAway is not NULL, it contains the information of whether or
2349 /// not AddrInst has to be folded into the addressing mode on success.
2350 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2351 /// because it has been moved away.
2352 /// Thus AddrInst must not be added in the matched instructions.
2353 /// This state can happen when AddrInst is a sext, since it may be moved away.
2354 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2355 /// not be referenced anymore.
2356 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2359 // Avoid exponential behavior on extremely deep expression trees.
2360 if (Depth >= 5) return false;
2362 // By default, all matched instructions stay in place.
2367 case Instruction::PtrToInt:
2368 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2369 return MatchAddr(AddrInst->getOperand(0), Depth);
2370 case Instruction::IntToPtr:
2371 // This inttoptr is a no-op if the integer type is pointer sized.
2372 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2373 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2374 return MatchAddr(AddrInst->getOperand(0), Depth);
2376 case Instruction::BitCast:
2377 case Instruction::AddrSpaceCast:
2378 // BitCast is always a noop, and we can handle it as long as it is
2379 // int->int or pointer->pointer (we don't want int<->fp or something).
2380 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2381 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2382 // Don't touch identity bitcasts. These were probably put here by LSR,
2383 // and we don't want to mess around with them. Assume it knows what it
2385 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2386 return MatchAddr(AddrInst->getOperand(0), Depth);
2388 case Instruction::Add: {
2389 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2390 ExtAddrMode BackupAddrMode = AddrMode;
2391 unsigned OldSize = AddrModeInsts.size();
2392 // Start a transaction at this point.
2393 // The LHS may match but not the RHS.
2394 // Therefore, we need a higher level restoration point to undo partially
2395 // matched operation.
2396 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2397 TPT.getRestorationPoint();
2399 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2400 MatchAddr(AddrInst->getOperand(0), Depth+1))
2403 // Restore the old addr mode info.
2404 AddrMode = BackupAddrMode;
2405 AddrModeInsts.resize(OldSize);
2406 TPT.rollback(LastKnownGood);
2408 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2409 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2410 MatchAddr(AddrInst->getOperand(1), Depth+1))
2413 // Otherwise we definitely can't merge the ADD in.
2414 AddrMode = BackupAddrMode;
2415 AddrModeInsts.resize(OldSize);
2416 TPT.rollback(LastKnownGood);
2419 //case Instruction::Or:
2420 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2422 case Instruction::Mul:
2423 case Instruction::Shl: {
2424 // Can only handle X*C and X << C.
2425 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2428 int64_t Scale = RHS->getSExtValue();
2429 if (Opcode == Instruction::Shl)
2430 Scale = 1LL << Scale;
2432 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2434 case Instruction::GetElementPtr: {
2435 // Scan the GEP. We check it if it contains constant offsets and at most
2436 // one variable offset.
2437 int VariableOperand = -1;
2438 unsigned VariableScale = 0;
2440 int64_t ConstantOffset = 0;
2441 const DataLayout *TD = TLI.getDataLayout();
2442 gep_type_iterator GTI = gep_type_begin(AddrInst);
2443 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2444 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2445 const StructLayout *SL = TD->getStructLayout(STy);
2447 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2448 ConstantOffset += SL->getElementOffset(Idx);
2450 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2451 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2452 ConstantOffset += CI->getSExtValue()*TypeSize;
2453 } else if (TypeSize) { // Scales of zero don't do anything.
2454 // We only allow one variable index at the moment.
2455 if (VariableOperand != -1)
2458 // Remember the variable index.
2459 VariableOperand = i;
2460 VariableScale = TypeSize;
2465 // A common case is for the GEP to only do a constant offset. In this case,
2466 // just add it to the disp field and check validity.
2467 if (VariableOperand == -1) {
2468 AddrMode.BaseOffs += ConstantOffset;
2469 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2470 // Check to see if we can fold the base pointer in too.
2471 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2474 AddrMode.BaseOffs -= ConstantOffset;
2478 // Save the valid addressing mode in case we can't match.
2479 ExtAddrMode BackupAddrMode = AddrMode;
2480 unsigned OldSize = AddrModeInsts.size();
2482 // See if the scale and offset amount is valid for this target.
2483 AddrMode.BaseOffs += ConstantOffset;
2485 // Match the base operand of the GEP.
2486 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2487 // If it couldn't be matched, just stuff the value in a register.
2488 if (AddrMode.HasBaseReg) {
2489 AddrMode = BackupAddrMode;
2490 AddrModeInsts.resize(OldSize);
2493 AddrMode.HasBaseReg = true;
2494 AddrMode.BaseReg = AddrInst->getOperand(0);
2497 // Match the remaining variable portion of the GEP.
2498 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2500 // If it couldn't be matched, try stuffing the base into a register
2501 // instead of matching it, and retrying the match of the scale.
2502 AddrMode = BackupAddrMode;
2503 AddrModeInsts.resize(OldSize);
2504 if (AddrMode.HasBaseReg)
2506 AddrMode.HasBaseReg = true;
2507 AddrMode.BaseReg = AddrInst->getOperand(0);
2508 AddrMode.BaseOffs += ConstantOffset;
2509 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2510 VariableScale, Depth)) {
2511 // If even that didn't work, bail.
2512 AddrMode = BackupAddrMode;
2513 AddrModeInsts.resize(OldSize);
2520 case Instruction::SExt:
2521 case Instruction::ZExt: {
2522 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2526 // Try to move this ext out of the way of the addressing mode.
2527 // Ask for a method for doing so.
2528 TypePromotionHelper::Action TPH =
2529 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2533 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2534 TPT.getRestorationPoint();
2535 unsigned CreatedInsts = 0;
2536 Value *PromotedOperand =
2537 TPH(Ext, TPT, PromotedInsts, CreatedInsts, nullptr, nullptr);
2538 // SExt has been moved away.
2539 // Thus either it will be rematched later in the recursive calls or it is
2540 // gone. Anyway, we must not fold it into the addressing mode at this point.
2544 // addr = gep base, idx
2546 // promotedOpnd = ext opnd <- no match here
2547 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2548 // addr = gep base, op <- match
2552 assert(PromotedOperand &&
2553 "TypePromotionHelper should have filtered out those cases");
2555 ExtAddrMode BackupAddrMode = AddrMode;
2556 unsigned OldSize = AddrModeInsts.size();
2558 if (!MatchAddr(PromotedOperand, Depth) ||
2559 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2561 AddrMode = BackupAddrMode;
2562 AddrModeInsts.resize(OldSize);
2563 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2564 TPT.rollback(LastKnownGood);
2573 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2574 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2575 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2576 /// or intptr_t for the target.
2578 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2579 // Start a transaction at this point that we will rollback if the matching
2581 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2582 TPT.getRestorationPoint();
2583 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2584 // Fold in immediates if legal for the target.
2585 AddrMode.BaseOffs += CI->getSExtValue();
2586 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2588 AddrMode.BaseOffs -= CI->getSExtValue();
2589 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2590 // If this is a global variable, try to fold it into the addressing mode.
2591 if (!AddrMode.BaseGV) {
2592 AddrMode.BaseGV = GV;
2593 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2595 AddrMode.BaseGV = nullptr;
2597 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2598 ExtAddrMode BackupAddrMode = AddrMode;
2599 unsigned OldSize = AddrModeInsts.size();
2601 // Check to see if it is possible to fold this operation.
2602 bool MovedAway = false;
2603 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2604 // This instruction may have been move away. If so, there is nothing
2608 // Okay, it's possible to fold this. Check to see if it is actually
2609 // *profitable* to do so. We use a simple cost model to avoid increasing
2610 // register pressure too much.
2611 if (I->hasOneUse() ||
2612 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2613 AddrModeInsts.push_back(I);
2617 // It isn't profitable to do this, roll back.
2618 //cerr << "NOT FOLDING: " << *I;
2619 AddrMode = BackupAddrMode;
2620 AddrModeInsts.resize(OldSize);
2621 TPT.rollback(LastKnownGood);
2623 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2624 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2626 TPT.rollback(LastKnownGood);
2627 } else if (isa<ConstantPointerNull>(Addr)) {
2628 // Null pointer gets folded without affecting the addressing mode.
2632 // Worse case, the target should support [reg] addressing modes. :)
2633 if (!AddrMode.HasBaseReg) {
2634 AddrMode.HasBaseReg = true;
2635 AddrMode.BaseReg = Addr;
2636 // Still check for legality in case the target supports [imm] but not [i+r].
2637 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2639 AddrMode.HasBaseReg = false;
2640 AddrMode.BaseReg = nullptr;
2643 // If the base register is already taken, see if we can do [r+r].
2644 if (AddrMode.Scale == 0) {
2646 AddrMode.ScaledReg = Addr;
2647 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2650 AddrMode.ScaledReg = nullptr;
2653 TPT.rollback(LastKnownGood);
2657 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2658 /// inline asm call are due to memory operands. If so, return true, otherwise
2660 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2661 const TargetLowering &TLI) {
2662 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2663 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2664 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2666 // Compute the constraint code and ConstraintType to use.
2667 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2669 // If this asm operand is our Value*, and if it isn't an indirect memory
2670 // operand, we can't fold it!
2671 if (OpInfo.CallOperandVal == OpVal &&
2672 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2673 !OpInfo.isIndirect))
2680 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2681 /// memory use. If we find an obviously non-foldable instruction, return true.
2682 /// Add the ultimately found memory instructions to MemoryUses.
2683 static bool FindAllMemoryUses(Instruction *I,
2684 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2685 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2686 const TargetLowering &TLI) {
2687 // If we already considered this instruction, we're done.
2688 if (!ConsideredInsts.insert(I).second)
2691 // If this is an obviously unfoldable instruction, bail out.
2692 if (!MightBeFoldableInst(I))
2695 // Loop over all the uses, recursively processing them.
2696 for (Use &U : I->uses()) {
2697 Instruction *UserI = cast<Instruction>(U.getUser());
2699 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2700 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2704 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2705 unsigned opNo = U.getOperandNo();
2706 if (opNo == 0) return true; // Storing addr, not into addr.
2707 MemoryUses.push_back(std::make_pair(SI, opNo));
2711 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2712 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2713 if (!IA) return true;
2715 // If this is a memory operand, we're cool, otherwise bail out.
2716 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2721 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2728 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2729 /// the use site that we're folding it into. If so, there is no cost to
2730 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2731 /// that we know are live at the instruction already.
2732 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2733 Value *KnownLive2) {
2734 // If Val is either of the known-live values, we know it is live!
2735 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2738 // All values other than instructions and arguments (e.g. constants) are live.
2739 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2741 // If Val is a constant sized alloca in the entry block, it is live, this is
2742 // true because it is just a reference to the stack/frame pointer, which is
2743 // live for the whole function.
2744 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2745 if (AI->isStaticAlloca())
2748 // Check to see if this value is already used in the memory instruction's
2749 // block. If so, it's already live into the block at the very least, so we
2750 // can reasonably fold it.
2751 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2754 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2755 /// mode of the machine to fold the specified instruction into a load or store
2756 /// that ultimately uses it. However, the specified instruction has multiple
2757 /// uses. Given this, it may actually increase register pressure to fold it
2758 /// into the load. For example, consider this code:
2762 /// use(Y) -> nonload/store
2766 /// In this case, Y has multiple uses, and can be folded into the load of Z
2767 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2768 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2769 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2770 /// number of computations either.
2772 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2773 /// X was live across 'load Z' for other reasons, we actually *would* want to
2774 /// fold the addressing mode in the Z case. This would make Y die earlier.
2775 bool AddressingModeMatcher::
2776 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2777 ExtAddrMode &AMAfter) {
2778 if (IgnoreProfitability) return true;
2780 // AMBefore is the addressing mode before this instruction was folded into it,
2781 // and AMAfter is the addressing mode after the instruction was folded. Get
2782 // the set of registers referenced by AMAfter and subtract out those
2783 // referenced by AMBefore: this is the set of values which folding in this
2784 // address extends the lifetime of.
2786 // Note that there are only two potential values being referenced here,
2787 // BaseReg and ScaleReg (global addresses are always available, as are any
2788 // folded immediates).
2789 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2791 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2792 // lifetime wasn't extended by adding this instruction.
2793 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2795 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2796 ScaledReg = nullptr;
2798 // If folding this instruction (and it's subexprs) didn't extend any live
2799 // ranges, we're ok with it.
2800 if (!BaseReg && !ScaledReg)
2803 // If all uses of this instruction are ultimately load/store/inlineasm's,
2804 // check to see if their addressing modes will include this instruction. If
2805 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2807 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2808 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2809 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2810 return false; // Has a non-memory, non-foldable use!
2812 // Now that we know that all uses of this instruction are part of a chain of
2813 // computation involving only operations that could theoretically be folded
2814 // into a memory use, loop over each of these uses and see if they could
2815 // *actually* fold the instruction.
2816 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2817 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2818 Instruction *User = MemoryUses[i].first;
2819 unsigned OpNo = MemoryUses[i].second;
2821 // Get the access type of this use. If the use isn't a pointer, we don't
2822 // know what it accesses.
2823 Value *Address = User->getOperand(OpNo);
2824 if (!Address->getType()->isPointerTy())
2826 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2828 // Do a match against the root of this address, ignoring profitability. This
2829 // will tell us if the addressing mode for the memory operation will
2830 // *actually* cover the shared instruction.
2832 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2833 TPT.getRestorationPoint();
2834 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2835 MemoryInst, Result, InsertedTruncs,
2836 PromotedInsts, TPT);
2837 Matcher.IgnoreProfitability = true;
2838 bool Success = Matcher.MatchAddr(Address, 0);
2839 (void)Success; assert(Success && "Couldn't select *anything*?");
2841 // The match was to check the profitability, the changes made are not
2842 // part of the original matcher. Therefore, they should be dropped
2843 // otherwise the original matcher will not present the right state.
2844 TPT.rollback(LastKnownGood);
2846 // If the match didn't cover I, then it won't be shared by it.
2847 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2848 I) == MatchedAddrModeInsts.end())
2851 MatchedAddrModeInsts.clear();
2857 } // end anonymous namespace
2859 /// IsNonLocalValue - Return true if the specified values are defined in a
2860 /// different basic block than BB.
2861 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2862 if (Instruction *I = dyn_cast<Instruction>(V))
2863 return I->getParent() != BB;
2867 /// OptimizeMemoryInst - Load and Store Instructions often have
2868 /// addressing modes that can do significant amounts of computation. As such,
2869 /// instruction selection will try to get the load or store to do as much
2870 /// computation as possible for the program. The problem is that isel can only
2871 /// see within a single block. As such, we sink as much legal addressing mode
2872 /// stuff into the block as possible.
2874 /// This method is used to optimize both load/store and inline asms with memory
2876 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2880 // Try to collapse single-value PHI nodes. This is necessary to undo
2881 // unprofitable PRE transformations.
2882 SmallVector<Value*, 8> worklist;
2883 SmallPtrSet<Value*, 16> Visited;
2884 worklist.push_back(Addr);
2886 // Use a worklist to iteratively look through PHI nodes, and ensure that
2887 // the addressing mode obtained from the non-PHI roots of the graph
2889 Value *Consensus = nullptr;
2890 unsigned NumUsesConsensus = 0;
2891 bool IsNumUsesConsensusValid = false;
2892 SmallVector<Instruction*, 16> AddrModeInsts;
2893 ExtAddrMode AddrMode;
2894 TypePromotionTransaction TPT;
2895 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2896 TPT.getRestorationPoint();
2897 while (!worklist.empty()) {
2898 Value *V = worklist.back();
2899 worklist.pop_back();
2901 // Break use-def graph loops.
2902 if (!Visited.insert(V).second) {
2903 Consensus = nullptr;
2907 // For a PHI node, push all of its incoming values.
2908 if (PHINode *P = dyn_cast<PHINode>(V)) {
2909 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2910 worklist.push_back(P->getIncomingValue(i));
2914 // For non-PHIs, determine the addressing mode being computed.
2915 SmallVector<Instruction*, 16> NewAddrModeInsts;
2916 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2917 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2918 PromotedInsts, TPT);
2920 // This check is broken into two cases with very similar code to avoid using
2921 // getNumUses() as much as possible. Some values have a lot of uses, so
2922 // calling getNumUses() unconditionally caused a significant compile-time
2926 AddrMode = NewAddrMode;
2927 AddrModeInsts = NewAddrModeInsts;
2929 } else if (NewAddrMode == AddrMode) {
2930 if (!IsNumUsesConsensusValid) {
2931 NumUsesConsensus = Consensus->getNumUses();
2932 IsNumUsesConsensusValid = true;
2935 // Ensure that the obtained addressing mode is equivalent to that obtained
2936 // for all other roots of the PHI traversal. Also, when choosing one
2937 // such root as representative, select the one with the most uses in order
2938 // to keep the cost modeling heuristics in AddressingModeMatcher
2940 unsigned NumUses = V->getNumUses();
2941 if (NumUses > NumUsesConsensus) {
2943 NumUsesConsensus = NumUses;
2944 AddrModeInsts = NewAddrModeInsts;
2949 Consensus = nullptr;
2953 // If the addressing mode couldn't be determined, or if multiple different
2954 // ones were determined, bail out now.
2956 TPT.rollback(LastKnownGood);
2961 // Check to see if any of the instructions supersumed by this addr mode are
2962 // non-local to I's BB.
2963 bool AnyNonLocal = false;
2964 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2965 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2971 // If all the instructions matched are already in this BB, don't do anything.
2973 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2977 // Insert this computation right after this user. Since our caller is
2978 // scanning from the top of the BB to the bottom, reuse of the expr are
2979 // guaranteed to happen later.
2980 IRBuilder<> Builder(MemoryInst);
2982 // Now that we determined the addressing expression we want to use and know
2983 // that we have to sink it into this block. Check to see if we have already
2984 // done this for some other load/store instr in this block. If so, reuse the
2986 Value *&SunkAddr = SunkAddrs[Addr];
2988 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2989 << *MemoryInst << "\n");
2990 if (SunkAddr->getType() != Addr->getType())
2991 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2992 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2993 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2994 // By default, we use the GEP-based method when AA is used later. This
2995 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2996 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2997 << *MemoryInst << "\n");
2998 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2999 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3001 // First, find the pointer.
3002 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3003 ResultPtr = AddrMode.BaseReg;
3004 AddrMode.BaseReg = nullptr;
3007 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3008 // We can't add more than one pointer together, nor can we scale a
3009 // pointer (both of which seem meaningless).
3010 if (ResultPtr || AddrMode.Scale != 1)
3013 ResultPtr = AddrMode.ScaledReg;
3017 if (AddrMode.BaseGV) {
3021 ResultPtr = AddrMode.BaseGV;
3024 // If the real base value actually came from an inttoptr, then the matcher
3025 // will look through it and provide only the integer value. In that case,
3027 if (!ResultPtr && AddrMode.BaseReg) {
3029 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3030 AddrMode.BaseReg = nullptr;
3031 } else if (!ResultPtr && AddrMode.Scale == 1) {
3033 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3038 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3039 SunkAddr = Constant::getNullValue(Addr->getType());
3040 } else if (!ResultPtr) {
3044 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3046 // Start with the base register. Do this first so that subsequent address
3047 // matching finds it last, which will prevent it from trying to match it
3048 // as the scaled value in case it happens to be a mul. That would be
3049 // problematic if we've sunk a different mul for the scale, because then
3050 // we'd end up sinking both muls.
3051 if (AddrMode.BaseReg) {
3052 Value *V = AddrMode.BaseReg;
3053 if (V->getType() != IntPtrTy)
3054 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3059 // Add the scale value.
3060 if (AddrMode.Scale) {
3061 Value *V = AddrMode.ScaledReg;
3062 if (V->getType() == IntPtrTy) {
3064 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3065 cast<IntegerType>(V->getType())->getBitWidth()) {
3066 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3068 // It is only safe to sign extend the BaseReg if we know that the math
3069 // required to create it did not overflow before we extend it. Since
3070 // the original IR value was tossed in favor of a constant back when
3071 // the AddrMode was created we need to bail out gracefully if widths
3072 // do not match instead of extending it.
3073 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3074 if (I && (ResultIndex != AddrMode.BaseReg))
3075 I->eraseFromParent();
3079 if (AddrMode.Scale != 1)
3080 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3083 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3088 // Add in the Base Offset if present.
3089 if (AddrMode.BaseOffs) {
3090 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3092 // We need to add this separately from the scale above to help with
3093 // SDAG consecutive load/store merging.
3094 if (ResultPtr->getType() != I8PtrTy)
3095 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3096 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3103 SunkAddr = ResultPtr;
3105 if (ResultPtr->getType() != I8PtrTy)
3106 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3107 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
3110 if (SunkAddr->getType() != Addr->getType())
3111 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3114 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3115 << *MemoryInst << "\n");
3116 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
3117 Value *Result = nullptr;
3119 // Start with the base register. Do this first so that subsequent address
3120 // matching finds it last, which will prevent it from trying to match it
3121 // as the scaled value in case it happens to be a mul. That would be
3122 // problematic if we've sunk a different mul for the scale, because then
3123 // we'd end up sinking both muls.
3124 if (AddrMode.BaseReg) {
3125 Value *V = AddrMode.BaseReg;
3126 if (V->getType()->isPointerTy())
3127 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3128 if (V->getType() != IntPtrTy)
3129 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3133 // Add the scale value.
3134 if (AddrMode.Scale) {
3135 Value *V = AddrMode.ScaledReg;
3136 if (V->getType() == IntPtrTy) {
3138 } else if (V->getType()->isPointerTy()) {
3139 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3140 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3141 cast<IntegerType>(V->getType())->getBitWidth()) {
3142 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3144 // It is only safe to sign extend the BaseReg if we know that the math
3145 // required to create it did not overflow before we extend it. Since
3146 // the original IR value was tossed in favor of a constant back when
3147 // the AddrMode was created we need to bail out gracefully if widths
3148 // do not match instead of extending it.
3149 Instruction *I = dyn_cast_or_null<Instruction>(Result);
3150 if (I && (Result != AddrMode.BaseReg))
3151 I->eraseFromParent();
3154 if (AddrMode.Scale != 1)
3155 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3158 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3163 // Add in the BaseGV if present.
3164 if (AddrMode.BaseGV) {
3165 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
3167 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3172 // Add in the Base Offset if present.
3173 if (AddrMode.BaseOffs) {
3174 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3176 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3182 SunkAddr = Constant::getNullValue(Addr->getType());
3184 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
3187 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
3189 // If we have no uses, recursively delete the value and all dead instructions
3191 if (Repl->use_empty()) {
3192 // This can cause recursive deletion, which can invalidate our iterator.
3193 // Use a WeakVH to hold onto it in case this happens.
3194 WeakVH IterHandle(CurInstIterator);
3195 BasicBlock *BB = CurInstIterator->getParent();
3197 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
3199 if (IterHandle != CurInstIterator) {
3200 // If the iterator instruction was recursively deleted, start over at the
3201 // start of the block.
3202 CurInstIterator = BB->begin();
3210 /// OptimizeInlineAsmInst - If there are any memory operands, use
3211 /// OptimizeMemoryInst to sink their address computing into the block when
3212 /// possible / profitable.
3213 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
3214 bool MadeChange = false;
3216 TargetLowering::AsmOperandInfoVector
3217 TargetConstraints = TLI->ParseConstraints(CS);
3219 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3220 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3222 // Compute the constraint code and ConstraintType to use.
3223 TLI->ComputeConstraintToUse(OpInfo, SDValue());
3225 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3226 OpInfo.isIndirect) {
3227 Value *OpVal = CS->getArgOperand(ArgNo++);
3228 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
3229 } else if (OpInfo.Type == InlineAsm::isInput)
3236 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3237 /// sign extensions.
3238 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3239 assert(!Inst->use_empty() && "Input must have at least one use");
3240 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3241 bool IsSExt = isa<SExtInst>(FirstUser);
3242 Type *ExtTy = FirstUser->getType();
3243 for (const User *U : Inst->users()) {
3244 const Instruction *UI = cast<Instruction>(U);
3245 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3247 Type *CurTy = UI->getType();
3248 // Same input and output types: Same instruction after CSE.
3252 // If IsSExt is true, we are in this situation:
3254 // b = sext ty1 a to ty2
3255 // c = sext ty1 a to ty3
3256 // Assuming ty2 is shorter than ty3, this could be turned into:
3258 // b = sext ty1 a to ty2
3259 // c = sext ty2 b to ty3
3260 // However, the last sext is not free.
3264 // This is a ZExt, maybe this is free to extend from one type to another.
3265 // In that case, we would not account for a different use.
3268 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3269 CurTy->getScalarType()->getIntegerBitWidth()) {
3277 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3280 // All uses are the same or can be derived from one another for free.
3284 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3285 /// load instruction.
3286 /// If an ext(load) can be formed, it is returned via \p LI for the load
3287 /// and \p Inst for the extension.
3288 /// Otherwise LI == nullptr and Inst == nullptr.
3289 /// When some promotion happened, \p TPT contains the proper state to
3292 /// \return true when promoting was necessary to expose the ext(load)
3293 /// opportunity, false otherwise.
3297 /// %ld = load i32* %addr
3298 /// %add = add nuw i32 %ld, 4
3299 /// %zext = zext i32 %add to i64
3303 /// %ld = load i32* %addr
3304 /// %zext = zext i32 %ld to i64
3305 /// %add = add nuw i64 %zext, 4
3307 /// Thanks to the promotion, we can match zext(load i32*) to i64.
3308 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3309 LoadInst *&LI, Instruction *&Inst,
3310 const SmallVectorImpl<Instruction *> &Exts,
3311 unsigned CreatedInsts = 0) {
3312 // Iterate over all the extensions to see if one form an ext(load).
3313 for (auto I : Exts) {
3314 // Check if we directly have ext(load).
3315 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3317 // No promotion happened here.
3320 // Check whether or not we want to do any promotion.
3321 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3323 // Get the action to perform the promotion.
3324 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3325 I, InsertedTruncsSet, *TLI, PromotedInsts);
3326 // Check if we can promote.
3329 // Save the current state.
3330 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3331 TPT.getRestorationPoint();
3332 SmallVector<Instruction *, 4> NewExts;
3333 unsigned NewCreatedInsts = 0;
3335 Value *PromotedVal =
3336 TPH(I, TPT, PromotedInsts, NewCreatedInsts, &NewExts, nullptr);
3337 assert(PromotedVal &&
3338 "TypePromotionHelper should have filtered out those cases");
3340 // We would be able to merge only one extension in a load.
3341 // Therefore, if we have more than 1 new extension we heuristically
3342 // cut this search path, because it means we degrade the code quality.
3343 // With exactly 2, the transformation is neutral, because we will merge
3344 // one extension but leave one. However, we optimistically keep going,
3345 // because the new extension may be removed too.
3346 unsigned TotalCreatedInsts = CreatedInsts + NewCreatedInsts;
3347 if (!StressExtLdPromotion &&
3348 (TotalCreatedInsts > 1 ||
3349 !isPromotedInstructionLegal(*TLI, PromotedVal))) {
3350 // The promotion is not profitable, rollback to the previous state.
3351 TPT.rollback(LastKnownGood);
3354 // The promotion is profitable.
3355 // Check if it exposes an ext(load).
3356 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInsts);
3357 if (LI && (StressExtLdPromotion || NewCreatedInsts == 0 ||
3358 // If we have created a new extension, i.e., now we have two
3359 // extensions. We must make sure one of them is merged with
3360 // the load, otherwise we may degrade the code quality.
3361 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3362 // Promotion happened.
3364 // If this does not help to expose an ext(load) then, rollback.
3365 TPT.rollback(LastKnownGood);
3367 // None of the extension can form an ext(load).
3373 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3374 /// basic block as the load, unless conditions are unfavorable. This allows
3375 /// SelectionDAG to fold the extend into the load.
3376 /// \p I[in/out] the extension may be modified during the process if some
3377 /// promotions apply.
3379 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3380 // Try to promote a chain of computation if it allows to form
3381 // an extended load.
3382 TypePromotionTransaction TPT;
3383 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3384 TPT.getRestorationPoint();
3385 SmallVector<Instruction *, 1> Exts;
3387 // Look for a load being extended.
3388 LoadInst *LI = nullptr;
3389 Instruction *OldExt = I;
3390 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3392 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3393 "the code must remain the same");
3398 // If they're already in the same block, there's nothing to do.
3399 // Make the cheap checks first if we did not promote.
3400 // If we promoted, we need to check if it is indeed profitable.
3401 if (!HasPromoted && LI->getParent() == I->getParent())
3404 EVT VT = TLI->getValueType(I->getType());
3405 EVT LoadVT = TLI->getValueType(LI->getType());
3407 // If the load has other users and the truncate is not free, this probably
3408 // isn't worthwhile.
3409 if (!LI->hasOneUse() && TLI &&
3410 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3411 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3413 TPT.rollback(LastKnownGood);
3417 // Check whether the target supports casts folded into loads.
3419 if (isa<ZExtInst>(I))
3420 LType = ISD::ZEXTLOAD;
3422 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3423 LType = ISD::SEXTLOAD;
3425 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
3427 TPT.rollback(LastKnownGood);
3431 // Move the extend into the same block as the load, so that SelectionDAG
3434 I->removeFromParent();
3440 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3441 BasicBlock *DefBB = I->getParent();
3443 // If the result of a {s|z}ext and its source are both live out, rewrite all
3444 // other uses of the source with result of extension.
3445 Value *Src = I->getOperand(0);
3446 if (Src->hasOneUse())
3449 // Only do this xform if truncating is free.
3450 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3453 // Only safe to perform the optimization if the source is also defined in
3455 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3458 bool DefIsLiveOut = false;
3459 for (User *U : I->users()) {
3460 Instruction *UI = cast<Instruction>(U);
3462 // Figure out which BB this ext is used in.
3463 BasicBlock *UserBB = UI->getParent();
3464 if (UserBB == DefBB) continue;
3465 DefIsLiveOut = true;
3471 // Make sure none of the uses are PHI nodes.
3472 for (User *U : Src->users()) {
3473 Instruction *UI = cast<Instruction>(U);
3474 BasicBlock *UserBB = UI->getParent();
3475 if (UserBB == DefBB) continue;
3476 // Be conservative. We don't want this xform to end up introducing
3477 // reloads just before load / store instructions.
3478 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3482 // InsertedTruncs - Only insert one trunc in each block once.
3483 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3485 bool MadeChange = false;
3486 for (Use &U : Src->uses()) {
3487 Instruction *User = cast<Instruction>(U.getUser());
3489 // Figure out which BB this ext is used in.
3490 BasicBlock *UserBB = User->getParent();
3491 if (UserBB == DefBB) continue;
3493 // Both src and def are live in this block. Rewrite the use.
3494 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3496 if (!InsertedTrunc) {
3497 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3498 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3499 InsertedTruncsSet.insert(InsertedTrunc);
3502 // Replace a use of the {s|z}ext source with a use of the result.
3511 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3512 /// turned into an explicit branch.
3513 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3514 // FIXME: This should use the same heuristics as IfConversion to determine
3515 // whether a select is better represented as a branch. This requires that
3516 // branch probability metadata is preserved for the select, which is not the
3519 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3521 // If the branch is predicted right, an out of order CPU can avoid blocking on
3522 // the compare. Emit cmovs on compares with a memory operand as branches to
3523 // avoid stalls on the load from memory. If the compare has more than one use
3524 // there's probably another cmov or setcc around so it's not worth emitting a
3529 Value *CmpOp0 = Cmp->getOperand(0);
3530 Value *CmpOp1 = Cmp->getOperand(1);
3532 // We check that the memory operand has one use to avoid uses of the loaded
3533 // value directly after the compare, making branches unprofitable.
3534 return Cmp->hasOneUse() &&
3535 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3536 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3540 /// If we have a SelectInst that will likely profit from branch prediction,
3541 /// turn it into a branch.
3542 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3543 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3545 // Can we convert the 'select' to CF ?
3546 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3549 TargetLowering::SelectSupportKind SelectKind;
3551 SelectKind = TargetLowering::VectorMaskSelect;
3552 else if (SI->getType()->isVectorTy())
3553 SelectKind = TargetLowering::ScalarCondVectorVal;
3555 SelectKind = TargetLowering::ScalarValSelect;
3557 // Do we have efficient codegen support for this kind of 'selects' ?
3558 if (TLI->isSelectSupported(SelectKind)) {
3559 // We have efficient codegen support for the select instruction.
3560 // Check if it is profitable to keep this 'select'.
3561 if (!TLI->isPredictableSelectExpensive() ||
3562 !isFormingBranchFromSelectProfitable(SI))
3568 // First, we split the block containing the select into 2 blocks.
3569 BasicBlock *StartBlock = SI->getParent();
3570 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3571 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3573 // Create a new block serving as the landing pad for the branch.
3574 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3575 NextBlock->getParent(), NextBlock);
3577 // Move the unconditional branch from the block with the select in it into our
3578 // landing pad block.
3579 StartBlock->getTerminator()->eraseFromParent();
3580 BranchInst::Create(NextBlock, SmallBlock);
3582 // Insert the real conditional branch based on the original condition.
3583 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3585 // The select itself is replaced with a PHI Node.
3586 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3588 PN->addIncoming(SI->getTrueValue(), StartBlock);
3589 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3590 SI->replaceAllUsesWith(PN);
3591 SI->eraseFromParent();
3593 // Instruct OptimizeBlock to skip to the next block.
3594 CurInstIterator = StartBlock->end();
3595 ++NumSelectsExpanded;
3599 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3600 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3602 for (unsigned i = 0; i < Mask.size(); ++i) {
3603 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3605 SplatElem = Mask[i];
3611 /// Some targets have expensive vector shifts if the lanes aren't all the same
3612 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3613 /// it's often worth sinking a shufflevector splat down to its use so that
3614 /// codegen can spot all lanes are identical.
3615 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3616 BasicBlock *DefBB = SVI->getParent();
3618 // Only do this xform if variable vector shifts are particularly expensive.
3619 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3622 // We only expect better codegen by sinking a shuffle if we can recognise a
3624 if (!isBroadcastShuffle(SVI))
3627 // InsertedShuffles - Only insert a shuffle in each block once.
3628 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3630 bool MadeChange = false;
3631 for (User *U : SVI->users()) {
3632 Instruction *UI = cast<Instruction>(U);
3634 // Figure out which BB this ext is used in.
3635 BasicBlock *UserBB = UI->getParent();
3636 if (UserBB == DefBB) continue;
3638 // For now only apply this when the splat is used by a shift instruction.
3639 if (!UI->isShift()) continue;
3641 // Everything checks out, sink the shuffle if the user's block doesn't
3642 // already have a copy.
3643 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3645 if (!InsertedShuffle) {
3646 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3647 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3649 SVI->getOperand(2), "", InsertPt);
3652 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3656 // If we removed all uses, nuke the shuffle.
3657 if (SVI->use_empty()) {
3658 SVI->eraseFromParent();
3666 /// \brief Helper class to promote a scalar operation to a vector one.
3667 /// This class is used to move downward extractelement transition.
3669 /// a = vector_op <2 x i32>
3670 /// b = extractelement <2 x i32> a, i32 0
3675 /// a = vector_op <2 x i32>
3676 /// c = vector_op a (equivalent to scalar_op on the related lane)
3677 /// * d = extractelement <2 x i32> c, i32 0
3679 /// Assuming both extractelement and store can be combine, we get rid of the
3681 class VectorPromoteHelper {
3682 /// Used to perform some checks on the legality of vector operations.
3683 const TargetLowering &TLI;
3685 /// Used to estimated the cost of the promoted chain.
3686 const TargetTransformInfo &TTI;
3688 /// The transition being moved downwards.
3689 Instruction *Transition;
3690 /// The sequence of instructions to be promoted.
3691 SmallVector<Instruction *, 4> InstsToBePromoted;
3692 /// Cost of combining a store and an extract.
3693 unsigned StoreExtractCombineCost;
3694 /// Instruction that will be combined with the transition.
3695 Instruction *CombineInst;
3697 /// \brief The instruction that represents the current end of the transition.
3698 /// Since we are faking the promotion until we reach the end of the chain
3699 /// of computation, we need a way to get the current end of the transition.
3700 Instruction *getEndOfTransition() const {
3701 if (InstsToBePromoted.empty())
3703 return InstsToBePromoted.back();
3706 /// \brief Return the index of the original value in the transition.
3707 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3708 /// c, is at index 0.
3709 unsigned getTransitionOriginalValueIdx() const {
3710 assert(isa<ExtractElementInst>(Transition) &&
3711 "Other kind of transitions are not supported yet");
3715 /// \brief Return the index of the index in the transition.
3716 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3718 unsigned getTransitionIdx() const {
3719 assert(isa<ExtractElementInst>(Transition) &&
3720 "Other kind of transitions are not supported yet");
3724 /// \brief Get the type of the transition.
3725 /// This is the type of the original value.
3726 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3727 /// transition is <2 x i32>.
3728 Type *getTransitionType() const {
3729 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3732 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3733 /// I.e., we have the following sequence:
3734 /// Def = Transition <ty1> a to <ty2>
3735 /// b = ToBePromoted <ty2> Def, ...
3737 /// b = ToBePromoted <ty1> a, ...
3738 /// Def = Transition <ty1> ToBePromoted to <ty2>
3739 void promoteImpl(Instruction *ToBePromoted);
3741 /// \brief Check whether or not it is profitable to promote all the
3742 /// instructions enqueued to be promoted.
3743 bool isProfitableToPromote() {
3744 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3745 unsigned Index = isa<ConstantInt>(ValIdx)
3746 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3748 Type *PromotedType = getTransitionType();
3750 StoreInst *ST = cast<StoreInst>(CombineInst);
3751 unsigned AS = ST->getPointerAddressSpace();
3752 unsigned Align = ST->getAlignment();
3753 // Check if this store is supported.
3754 if (!TLI.allowsMisalignedMemoryAccesses(
3755 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3756 // If this is not supported, there is no way we can combine
3757 // the extract with the store.
3761 // The scalar chain of computation has to pay for the transition
3762 // scalar to vector.
3763 // The vector chain has to account for the combining cost.
3764 uint64_t ScalarCost =
3765 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3766 uint64_t VectorCost = StoreExtractCombineCost;
3767 for (const auto &Inst : InstsToBePromoted) {
3768 // Compute the cost.
3769 // By construction, all instructions being promoted are arithmetic ones.
3770 // Moreover, one argument is a constant that can be viewed as a splat
3772 Value *Arg0 = Inst->getOperand(0);
3773 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3774 isa<ConstantFP>(Arg0);
3775 TargetTransformInfo::OperandValueKind Arg0OVK =
3776 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3777 : TargetTransformInfo::OK_AnyValue;
3778 TargetTransformInfo::OperandValueKind Arg1OVK =
3779 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3780 : TargetTransformInfo::OK_AnyValue;
3781 ScalarCost += TTI.getArithmeticInstrCost(
3782 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3783 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3786 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3787 << ScalarCost << "\nVector: " << VectorCost << '\n');
3788 return ScalarCost > VectorCost;
3791 /// \brief Generate a constant vector with \p Val with the same
3792 /// number of elements as the transition.
3793 /// \p UseSplat defines whether or not \p Val should be replicated
3794 /// accross the whole vector.
3795 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3796 /// otherwise we generate a vector with as many undef as possible:
3797 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3798 /// used at the index of the extract.
3799 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3800 unsigned ExtractIdx = UINT_MAX;
3802 // If we cannot determine where the constant must be, we have to
3803 // use a splat constant.
3804 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3805 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3806 ExtractIdx = CstVal->getSExtValue();
3811 unsigned End = getTransitionType()->getVectorNumElements();
3813 return ConstantVector::getSplat(End, Val);
3815 SmallVector<Constant *, 4> ConstVec;
3816 UndefValue *UndefVal = UndefValue::get(Val->getType());
3817 for (unsigned Idx = 0; Idx != End; ++Idx) {
3818 if (Idx == ExtractIdx)
3819 ConstVec.push_back(Val);
3821 ConstVec.push_back(UndefVal);
3823 return ConstantVector::get(ConstVec);
3826 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3827 /// in \p Use can trigger undefined behavior.
3828 static bool canCauseUndefinedBehavior(const Instruction *Use,
3829 unsigned OperandIdx) {
3830 // This is not safe to introduce undef when the operand is on
3831 // the right hand side of a division-like instruction.
3832 if (OperandIdx != 1)
3834 switch (Use->getOpcode()) {
3837 case Instruction::SDiv:
3838 case Instruction::UDiv:
3839 case Instruction::SRem:
3840 case Instruction::URem:
3842 case Instruction::FDiv:
3843 case Instruction::FRem:
3844 return !Use->hasNoNaNs();
3846 llvm_unreachable(nullptr);
3850 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3851 Instruction *Transition, unsigned CombineCost)
3852 : TLI(TLI), TTI(TTI), Transition(Transition),
3853 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3854 assert(Transition && "Do not know how to promote null");
3857 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3858 bool canPromote(const Instruction *ToBePromoted) const {
3859 // We could support CastInst too.
3860 return isa<BinaryOperator>(ToBePromoted);
3863 /// \brief Check if it is profitable to promote \p ToBePromoted
3864 /// by moving downward the transition through.
3865 bool shouldPromote(const Instruction *ToBePromoted) const {
3866 // Promote only if all the operands can be statically expanded.
3867 // Indeed, we do not want to introduce any new kind of transitions.
3868 for (const Use &U : ToBePromoted->operands()) {
3869 const Value *Val = U.get();
3870 if (Val == getEndOfTransition()) {
3871 // If the use is a division and the transition is on the rhs,
3872 // we cannot promote the operation, otherwise we may create a
3873 // division by zero.
3874 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3878 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3879 !isa<ConstantFP>(Val))
3882 // Check that the resulting operation is legal.
3883 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3886 return StressStoreExtract ||
3887 TLI.isOperationLegalOrCustom(
3888 ISDOpcode, TLI.getValueType(getTransitionType(), true));
3891 /// \brief Check whether or not \p Use can be combined
3892 /// with the transition.
3893 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3894 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3896 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3897 void enqueueForPromotion(Instruction *ToBePromoted) {
3898 InstsToBePromoted.push_back(ToBePromoted);
3901 /// \brief Set the instruction that will be combined with the transition.
3902 void recordCombineInstruction(Instruction *ToBeCombined) {
3903 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3904 CombineInst = ToBeCombined;
3907 /// \brief Promote all the instructions enqueued for promotion if it is
3909 /// \return True if the promotion happened, false otherwise.
3911 // Check if there is something to promote.
3912 // Right now, if we do not have anything to combine with,
3913 // we assume the promotion is not profitable.
3914 if (InstsToBePromoted.empty() || !CombineInst)
3918 if (!StressStoreExtract && !isProfitableToPromote())
3922 for (auto &ToBePromoted : InstsToBePromoted)
3923 promoteImpl(ToBePromoted);
3924 InstsToBePromoted.clear();
3928 } // End of anonymous namespace.
3930 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3931 // At this point, we know that all the operands of ToBePromoted but Def
3932 // can be statically promoted.
3933 // For Def, we need to use its parameter in ToBePromoted:
3934 // b = ToBePromoted ty1 a
3935 // Def = Transition ty1 b to ty2
3936 // Move the transition down.
3937 // 1. Replace all uses of the promoted operation by the transition.
3938 // = ... b => = ... Def.
3939 assert(ToBePromoted->getType() == Transition->getType() &&
3940 "The type of the result of the transition does not match "
3942 ToBePromoted->replaceAllUsesWith(Transition);
3943 // 2. Update the type of the uses.
3944 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3945 Type *TransitionTy = getTransitionType();
3946 ToBePromoted->mutateType(TransitionTy);
3947 // 3. Update all the operands of the promoted operation with promoted
3949 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3950 for (Use &U : ToBePromoted->operands()) {
3951 Value *Val = U.get();
3952 Value *NewVal = nullptr;
3953 if (Val == Transition)
3954 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3955 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3956 isa<ConstantFP>(Val)) {
3957 // Use a splat constant if it is not safe to use undef.
3958 NewVal = getConstantVector(
3959 cast<Constant>(Val),
3960 isa<UndefValue>(Val) ||
3961 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3963 llvm_unreachable("Did you modified shouldPromote and forgot to update "
3965 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3967 Transition->removeFromParent();
3968 Transition->insertAfter(ToBePromoted);
3969 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3972 // See if we can speculate calls to intrinsic cttz/ctlz.
3977 // %cmp = icmp eq i64 %val, 0
3978 // br i1 %cmp, label %end.bb, label %then.bb
3981 // %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 true)
3985 // %cond = phi i64 [ %c, %then.bb ], [ 64, %entry ]
3991 // %c = tail call i64 @llvm.cttz.i64(i64 %val, i1 false)
3993 static bool OptimizeBranchInst(BranchInst *BrInst, const TargetLowering &TLI) {
3994 assert(BrInst->isConditional() && "Expected a conditional branch!");
3995 BasicBlock *ThenBB = BrInst->getSuccessor(1);
3996 BasicBlock *EndBB = BrInst->getSuccessor(0);
3998 // See if ThenBB contains only one instruction (excluding the
3999 // terminator and DbgInfoIntrinsic calls).
4000 IntrinsicInst *II = nullptr;
4001 CastInst *CI = nullptr;
4002 for (BasicBlock::iterator I = ThenBB->begin(),
4003 E = std::prev(ThenBB->end()); I != E; ++I) {
4005 if (isa<DbgInfoIntrinsic>(I))
4008 // Check if this is a zero extension or a truncate of a previously
4009 // matched call to intrinsic cttz/ctlz.
4011 // Early exit if we already found a "free" zero extend/truncate.
4015 Type *SrcTy = II->getType();
4016 Type *DestTy = I->getType();
4019 if (match(cast<Instruction>(I), m_ZExt(m_Value(V))) && V == II) {
4020 // Speculate this zero extend only if it is "free" for the target.
4021 if (TLI.isZExtFree(SrcTy, DestTy)) {
4022 CI = cast<CastInst>(I);
4025 } else if (match(cast<Instruction>(I), m_Trunc(m_Value(V))) && V == II) {
4026 // Speculate this truncate only if it is "free" for the target.
4027 if (TLI.isTruncateFree(SrcTy, DestTy)) {
4028 CI = cast<CastInst>(I);
4032 // Avoid speculating more than one instruction.
4037 // See if this is a call to intrinsic cttz/ctlz.
4038 if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::cttz>())) {
4039 // Avoid speculating expensive intrinsic calls.
4040 if (!TLI.isCheapToSpeculateCttz())
4043 else if (match(cast<Instruction>(I), m_Intrinsic<Intrinsic::ctlz>())) {
4044 // Avoid speculating expensive intrinsic calls.
4045 if (!TLI.isCheapToSpeculateCtlz())
4050 II = cast<IntrinsicInst>(I);
4053 // Look for PHI nodes with 'II' as the incoming value from 'ThenBB'.
4054 BasicBlock *EntryBB = BrInst->getParent();
4055 for (BasicBlock::iterator I = EndBB->begin();
4056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
4057 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
4058 Value *OrigV = PN->getIncomingValueForBlock(EntryBB);
4063 if (ThenV != II && (!CI || ThenV != CI))
4066 if (ConstantInt *CInt = dyn_cast<ConstantInt>(OrigV)) {
4067 unsigned BitWidth = II->getType()->getIntegerBitWidth();
4069 // Don't try to simplify this phi node if 'ThenV' is a cttz/ctlz
4070 // intrinsic call, but 'OrigV' is not equal to the 'size-of' in bits
4071 // of the value in input to the cttz/ctlz.
4072 if (CInt->getValue() != BitWidth)
4075 // Hoist the call to cttz/ctlz from ThenBB into EntryBB.
4076 EntryBB->getInstList().splice(BrInst, ThenBB->getInstList(),
4077 ThenBB->begin(), std::prev(ThenBB->end()));
4079 // Update PN setting ThenV as the incoming value from both 'EntryBB'
4080 // and 'ThenBB'. Eventually, method 'OptimizeInst' will fold this
4081 // phi node if all the incoming values are the same.
4082 PN->setIncomingValue(PN->getBasicBlockIndex(EntryBB), ThenV);
4083 PN->setIncomingValue(PN->getBasicBlockIndex(ThenBB), ThenV);
4085 // Clear the 'undef on zero' flag of the cttz/ctlz intrinsic call.
4086 if (cast<ConstantInt>(II->getArgOperand(1))->isOne()) {
4087 Type *Ty = II->getArgOperand(0)->getType();
4088 Value *Args[] = { II->getArgOperand(0),
4089 ConstantInt::getFalse(II->getContext()) };
4090 Module *M = EntryBB->getParent()->getParent();
4091 Value *IF = Intrinsic::getDeclaration(M, II->getIntrinsicID(), Ty);
4092 IRBuilder<> Builder(II);
4093 Instruction *NewI = Builder.CreateCall(IF, Args);
4095 // Replace the old call to cttz/ctlz.
4096 II->replaceAllUsesWith(NewI);
4097 II->eraseFromParent();
4100 // Update BrInst condition so that the branch to EndBB is always taken.
4101 // Later on, method 'ConstantFoldTerminator' will simplify this branch
4102 // replacing it with a direct branch to 'EndBB'.
4103 // As a side effect, CodeGenPrepare will attempt to simplify the control
4104 // flow graph by deleting basic block 'ThenBB' and merging 'EntryBB' into
4105 // 'EndBB' (calling method 'EliminateFallThrough').
4106 BrInst->setCondition(ConstantInt::getTrue(BrInst->getContext()));
4114 /// Some targets can do store(extractelement) with one instruction.
4115 /// Try to push the extractelement towards the stores when the target
4116 /// has this feature and this is profitable.
4117 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4118 unsigned CombineCost = UINT_MAX;
4119 if (DisableStoreExtract || !TLI ||
4120 (!StressStoreExtract &&
4121 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4122 Inst->getOperand(1), CombineCost)))
4125 // At this point we know that Inst is a vector to scalar transition.
4126 // Try to move it down the def-use chain, until:
4127 // - We can combine the transition with its single use
4128 // => we got rid of the transition.
4129 // - We escape the current basic block
4130 // => we would need to check that we are moving it at a cheaper place and
4131 // we do not do that for now.
4132 BasicBlock *Parent = Inst->getParent();
4133 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4134 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
4135 // If the transition has more than one use, assume this is not going to be
4137 while (Inst->hasOneUse()) {
4138 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4139 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4141 if (ToBePromoted->getParent() != Parent) {
4142 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4143 << ToBePromoted->getParent()->getName()
4144 << ") than the transition (" << Parent->getName() << ").\n");
4148 if (VPH.canCombine(ToBePromoted)) {
4149 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4150 << "will be combined with: " << *ToBePromoted << '\n');
4151 VPH.recordCombineInstruction(ToBePromoted);
4152 bool Changed = VPH.promote();
4153 NumStoreExtractExposed += Changed;
4157 DEBUG(dbgs() << "Try promoting.\n");
4158 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4161 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4163 VPH.enqueueForPromotion(ToBePromoted);
4164 Inst = ToBePromoted;
4169 bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
4170 if (PHINode *P = dyn_cast<PHINode>(I)) {
4171 // It is possible for very late stage optimizations (such as SimplifyCFG)
4172 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4173 // trivial PHI, go ahead and zap it here.
4174 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
4176 P->replaceAllUsesWith(V);
4177 P->eraseFromParent();
4184 if (CastInst *CI = dyn_cast<CastInst>(I)) {
4185 // If the source of the cast is a constant, then this should have
4186 // already been constant folded. The only reason NOT to constant fold
4187 // it is if something (e.g. LSR) was careful to place the constant
4188 // evaluation in a block other than then one that uses it (e.g. to hoist
4189 // the address of globals out of a loop). If this is the case, we don't
4190 // want to forward-subst the cast.
4191 if (isa<Constant>(CI->getOperand(0)))
4194 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
4197 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4198 /// Sink a zext or sext into its user blocks if the target type doesn't
4199 /// fit in one register
4200 if (TLI && TLI->getTypeAction(CI->getContext(),
4201 TLI->getValueType(CI->getType())) ==
4202 TargetLowering::TypeExpandInteger) {
4203 return SinkCast(CI);
4205 bool MadeChange = MoveExtToFormExtLoad(I);
4206 return MadeChange | OptimizeExtUses(I);
4212 if (CmpInst *CI = dyn_cast<CmpInst>(I))
4213 if (!TLI || !TLI->hasMultipleConditionRegisters())
4214 return OptimizeCmpExpression(CI);
4216 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4218 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
4222 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4224 return OptimizeMemoryInst(I, SI->getOperand(1),
4225 SI->getOperand(0)->getType());
4229 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4231 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4232 BinOp->getOpcode() == Instruction::LShr)) {
4233 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4234 if (TLI && CI && TLI->hasExtractBitsInsn())
4235 return OptimizeExtractBits(BinOp, CI, *TLI);
4240 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4241 if (GEPI->hasAllZeroIndices()) {
4242 /// The GEP operand must be a pointer, so must its result -> BitCast
4243 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4244 GEPI->getName(), GEPI);
4245 GEPI->replaceAllUsesWith(NC);
4246 GEPI->eraseFromParent();
4248 OptimizeInst(NC, ModifiedDT);
4254 if (CallInst *CI = dyn_cast<CallInst>(I))
4255 return OptimizeCallInst(CI, ModifiedDT);
4257 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4258 return OptimizeSelectInst(SI);
4260 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4261 return OptimizeShuffleVectorInst(SVI);
4263 if (isa<ExtractElementInst>(I))
4264 return OptimizeExtractElementInst(I);
4266 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
4267 if (TLI && BI->isConditional() && BI->getCondition()->hasOneUse()) {
4268 // Check if the branch condition compares a value agaist zero.
4269 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
4270 if (ICI->getPredicate() == ICmpInst::ICMP_EQ &&
4271 match(ICI->getOperand(1), m_Zero())) {
4272 BasicBlock *ThenBB = BI->getSuccessor(1);
4273 BasicBlock *EndBB = BI->getSuccessor(0);
4275 // Check if ThenBB is only reachable from this basic block; also,
4276 // check if EndBB has more than one predecessor.
4277 if (ThenBB->getSinglePredecessor() &&
4278 !EndBB->getSinglePredecessor()) {
4279 TerminatorInst *TI = ThenBB->getTerminator();
4281 if (TI->getNumSuccessors() == 1 && TI->getSuccessor(0) == EndBB &&
4282 // Try to speculate calls to intrinsic cttz/ctlz from 'ThenBB'.
4283 OptimizeBranchInst(BI, *TLI)) {
4297 // In this pass we look for GEP and cast instructions that are used
4298 // across basic blocks and rewrite them to improve basic-block-at-a-time
4300 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
4302 bool MadeChange = false;
4304 CurInstIterator = BB.begin();
4305 while (CurInstIterator != BB.end()) {
4306 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4310 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4315 // llvm.dbg.value is far away from the value then iSel may not be able
4316 // handle it properly. iSel will drop llvm.dbg.value if it can not
4317 // find a node corresponding to the value.
4318 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4319 bool MadeChange = false;
4320 for (BasicBlock &BB : F) {
4321 Instruction *PrevNonDbgInst = nullptr;
4322 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
4323 Instruction *Insn = BI++;
4324 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
4325 // Leave dbg.values that refer to an alloca alone. These
4326 // instrinsics describe the address of a variable (= the alloca)
4327 // being taken. They should not be moved next to the alloca
4328 // (and to the beginning of the scope), but rather stay close to
4329 // where said address is used.
4330 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
4331 PrevNonDbgInst = Insn;
4335 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4336 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4337 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4338 DVI->removeFromParent();
4339 if (isa<PHINode>(VI))
4340 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4342 DVI->insertAfter(VI);
4351 // If there is a sequence that branches based on comparing a single bit
4352 // against zero that can be combined into a single instruction, and the
4353 // target supports folding these into a single instruction, sink the
4354 // mask and compare into the branch uses. Do this before OptimizeBlock ->
4355 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4357 bool CodeGenPrepare::sinkAndCmp(Function &F) {
4358 if (!EnableAndCmpSinking)
4360 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4362 bool MadeChange = false;
4363 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4364 BasicBlock *BB = I++;
4366 // Does this BB end with the following?
4367 // %andVal = and %val, #single-bit-set
4368 // %icmpVal = icmp %andResult, 0
4369 // br i1 %cmpVal label %dest1, label %dest2"
4370 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4371 if (!Brcc || !Brcc->isConditional())
4373 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4374 if (!Cmp || Cmp->getParent() != BB)
4376 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4377 if (!Zero || !Zero->isZero())
4379 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4380 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4382 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4383 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4385 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4387 // Push the "and; icmp" for any users that are conditional branches.
4388 // Since there can only be one branch use per BB, we don't need to keep
4389 // track of which BBs we insert into.
4390 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4394 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4396 if (!BrccUser || !BrccUser->isConditional())
4398 BasicBlock *UserBB = BrccUser->getParent();
4399 if (UserBB == BB) continue;
4400 DEBUG(dbgs() << "found Brcc use\n");
4402 // Sink the "and; icmp" to use.
4404 BinaryOperator *NewAnd =
4405 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4408 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4412 DEBUG(BrccUser->getParent()->dump());
4418 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4419 /// success, or returns false if no or invalid metadata was found.
4420 static bool extractBranchMetadata(BranchInst *BI,
4421 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4422 assert(BI->isConditional() &&
4423 "Looking for probabilities on unconditional branch?");
4424 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4425 if (!ProfileData || ProfileData->getNumOperands() != 3)
4428 const auto *CITrue =
4429 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4430 const auto *CIFalse =
4431 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4432 if (!CITrue || !CIFalse)
4435 ProbTrue = CITrue->getValue().getZExtValue();
4436 ProbFalse = CIFalse->getValue().getZExtValue();
4441 /// \brief Scale down both weights to fit into uint32_t.
4442 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4443 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4444 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4445 NewTrue = NewTrue / Scale;
4446 NewFalse = NewFalse / Scale;
4449 /// \brief Some targets prefer to split a conditional branch like:
4451 /// %0 = icmp ne i32 %a, 0
4452 /// %1 = icmp ne i32 %b, 0
4453 /// %or.cond = or i1 %0, %1
4454 /// br i1 %or.cond, label %TrueBB, label %FalseBB
4456 /// into multiple branch instructions like:
4459 /// %0 = icmp ne i32 %a, 0
4460 /// br i1 %0, label %TrueBB, label %bb2
4462 /// %1 = icmp ne i32 %b, 0
4463 /// br i1 %1, label %TrueBB, label %FalseBB
4465 /// This usually allows instruction selection to do even further optimizations
4466 /// and combine the compare with the branch instruction. Currently this is
4467 /// applied for targets which have "cheap" jump instructions.
4469 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4471 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4472 if (!TM || TM->Options.EnableFastISel != true ||
4473 !TLI || TLI->isJumpExpensive())
4476 bool MadeChange = false;
4477 for (auto &BB : F) {
4478 // Does this BB end with the following?
4479 // %cond1 = icmp|fcmp|binary instruction ...
4480 // %cond2 = icmp|fcmp|binary instruction ...
4481 // %cond.or = or|and i1 %cond1, cond2
4482 // br i1 %cond.or label %dest1, label %dest2"
4483 BinaryOperator *LogicOp;
4484 BasicBlock *TBB, *FBB;
4485 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4489 Value *Cond1, *Cond2;
4490 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4491 m_OneUse(m_Value(Cond2)))))
4492 Opc = Instruction::And;
4493 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4494 m_OneUse(m_Value(Cond2)))))
4495 Opc = Instruction::Or;
4499 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4500 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4503 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4506 auto *InsertBefore = std::next(Function::iterator(BB))
4507 .getNodePtrUnchecked();
4508 auto TmpBB = BasicBlock::Create(BB.getContext(),
4509 BB.getName() + ".cond.split",
4510 BB.getParent(), InsertBefore);
4512 // Update original basic block by using the first condition directly by the
4513 // branch instruction and removing the no longer needed and/or instruction.
4514 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4515 Br1->setCondition(Cond1);
4516 LogicOp->eraseFromParent();
4518 // Depending on the conditon we have to either replace the true or the false
4519 // successor of the original branch instruction.
4520 if (Opc == Instruction::And)
4521 Br1->setSuccessor(0, TmpBB);
4523 Br1->setSuccessor(1, TmpBB);
4525 // Fill in the new basic block.
4526 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4527 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4528 I->removeFromParent();
4529 I->insertBefore(Br2);
4532 // Update PHI nodes in both successors. The original BB needs to be
4533 // replaced in one succesor's PHI nodes, because the branch comes now from
4534 // the newly generated BB (NewBB). In the other successor we need to add one
4535 // incoming edge to the PHI nodes, because both branch instructions target
4536 // now the same successor. Depending on the original branch condition
4537 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4538 // we perfrom the correct update for the PHI nodes.
4539 // This doesn't change the successor order of the just created branch
4540 // instruction (or any other instruction).
4541 if (Opc == Instruction::Or)
4542 std::swap(TBB, FBB);
4544 // Replace the old BB with the new BB.
4545 for (auto &I : *TBB) {
4546 PHINode *PN = dyn_cast<PHINode>(&I);
4550 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4551 PN->setIncomingBlock(i, TmpBB);
4554 // Add another incoming edge form the new BB.
4555 for (auto &I : *FBB) {
4556 PHINode *PN = dyn_cast<PHINode>(&I);
4559 auto *Val = PN->getIncomingValueForBlock(&BB);
4560 PN->addIncoming(Val, TmpBB);
4563 // Update the branch weights (from SelectionDAGBuilder::
4564 // FindMergedConditions).
4565 if (Opc == Instruction::Or) {
4566 // Codegen X | Y as:
4575 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4576 // The requirement is that
4577 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4578 // = TrueProb for orignal BB.
4579 // Assuming the orignal weights are A and B, one choice is to set BB1's
4580 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4582 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4583 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4584 // TmpBB, but the math is more complicated.
4585 uint64_t TrueWeight, FalseWeight;
4586 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4587 uint64_t NewTrueWeight = TrueWeight;
4588 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4589 scaleWeights(NewTrueWeight, NewFalseWeight);
4590 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4591 .createBranchWeights(TrueWeight, FalseWeight));
4593 NewTrueWeight = TrueWeight;
4594 NewFalseWeight = 2 * FalseWeight;
4595 scaleWeights(NewTrueWeight, NewFalseWeight);
4596 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4597 .createBranchWeights(TrueWeight, FalseWeight));
4600 // Codegen X & Y as:
4608 // This requires creation of TmpBB after CurBB.
4610 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4611 // The requirement is that
4612 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4613 // = FalseProb for orignal BB.
4614 // Assuming the orignal weights are A and B, one choice is to set BB1's
4615 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4617 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4618 uint64_t TrueWeight, FalseWeight;
4619 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4620 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4621 uint64_t NewFalseWeight = FalseWeight;
4622 scaleWeights(NewTrueWeight, NewFalseWeight);
4623 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4624 .createBranchWeights(TrueWeight, FalseWeight));
4626 NewTrueWeight = 2 * TrueWeight;
4627 NewFalseWeight = FalseWeight;
4628 scaleWeights(NewTrueWeight, NewFalseWeight);
4629 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4630 .createBranchWeights(TrueWeight, FalseWeight));
4634 // Request DOM Tree update.
4635 // Note: No point in getting fancy here, since the DT info is never
4636 // available to CodeGenPrepare and the existing update code is broken
4642 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();