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/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/IR/ValueMap.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/BuildLibCalls.h"
45 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
46 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm::PatternMatch;
50 #define DEBUG_TYPE "codegenprepare"
52 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
53 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
54 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
55 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
57 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
59 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60 "computations were sunk");
61 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
62 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
63 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
64 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
65 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
66 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
67 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
69 static cl::opt<bool> DisableBranchOpts(
70 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
71 cl::desc("Disable branch optimizations in CodeGenPrepare"));
73 static cl::opt<bool> DisableSelectToBranch(
74 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
75 cl::desc("Disable select to branch conversion."));
77 static cl::opt<bool> AddrSinkUsingGEPs(
78 "addr-sink-using-gep", cl::Hidden, cl::init(false),
79 cl::desc("Address sinking in CGP using GEPs."));
81 static cl::opt<bool> EnableAndCmpSinking(
82 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
83 cl::desc("Enable sinkinig and/cmp into branches."));
85 static cl::opt<bool> DisableStoreExtract(
86 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
87 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
89 static cl::opt<bool> StressStoreExtract(
90 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
91 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
94 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
98 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
100 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
102 class CodeGenPrepare : public FunctionPass {
103 /// TLI - Keep a pointer of a TargetLowering to consult for determining
104 /// transformation profitability.
105 const TargetMachine *TM;
106 const TargetLowering *TLI;
107 const TargetTransformInfo *TTI;
108 const TargetLibraryInfo *TLInfo;
111 /// CurInstIterator - As we scan instructions optimizing them, this is the
112 /// next instruction to optimize. Xforms that can invalidate this should
114 BasicBlock::iterator CurInstIterator;
116 /// Keeps track of non-local addresses that have been sunk into a block.
117 /// This allows us to avoid inserting duplicate code for blocks with
118 /// multiple load/stores of the same address.
119 ValueMap<Value*, Value*> SunkAddrs;
121 /// Keeps track of all truncates inserted for the current function.
122 SetOfInstrs InsertedTruncsSet;
123 /// Keeps track of the type of the related instruction before their
124 /// promotion for the current function.
125 InstrToOrigTy PromotedInsts;
127 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
131 /// OptSize - True if optimizing for size.
135 static char ID; // Pass identification, replacement for typeid
136 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
137 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
138 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
140 bool runOnFunction(Function &F) override;
142 const char *getPassName() const override { return "CodeGen Prepare"; }
144 void getAnalysisUsage(AnalysisUsage &AU) const override {
145 AU.addPreserved<DominatorTreeWrapperPass>();
146 AU.addRequired<TargetLibraryInfo>();
147 AU.addRequired<TargetTransformInfo>();
151 bool EliminateFallThrough(Function &F);
152 bool EliminateMostlyEmptyBlocks(Function &F);
153 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
154 void EliminateMostlyEmptyBlock(BasicBlock *BB);
155 bool OptimizeBlock(BasicBlock &BB);
156 bool OptimizeInst(Instruction *I);
157 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
158 bool OptimizeInlineAsmInst(CallInst *CS);
159 bool OptimizeCallInst(CallInst *CI);
160 bool MoveExtToFormExtLoad(Instruction *I);
161 bool OptimizeExtUses(Instruction *I);
162 bool OptimizeSelectInst(SelectInst *SI);
163 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
164 bool OptimizeExtractElementInst(Instruction *Inst);
165 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
166 bool PlaceDbgValues(Function &F);
167 bool sinkAndCmp(Function &F);
171 char CodeGenPrepare::ID = 0;
172 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
173 "Optimize for code generation", false, false)
175 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
176 return new CodeGenPrepare(TM);
179 bool CodeGenPrepare::runOnFunction(Function &F) {
180 if (skipOptnoneFunction(F))
183 bool EverMadeChange = false;
184 // Clear per function information.
185 InsertedTruncsSet.clear();
186 PromotedInsts.clear();
190 TLI = TM->getSubtargetImpl()->getTargetLowering();
191 TLInfo = &getAnalysis<TargetLibraryInfo>();
192 TTI = &getAnalysis<TargetTransformInfo>();
193 DominatorTreeWrapperPass *DTWP =
194 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
195 DT = DTWP ? &DTWP->getDomTree() : nullptr;
196 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
197 Attribute::OptimizeForSize);
199 /// This optimization identifies DIV instructions that can be
200 /// profitably bypassed and carried out with a shorter, faster divide.
201 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
202 const DenseMap<unsigned int, unsigned int> &BypassWidths =
203 TLI->getBypassSlowDivWidths();
204 for (Function::iterator I = F.begin(); I != F.end(); I++)
205 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
208 // Eliminate blocks that contain only PHI nodes and an
209 // unconditional branch.
210 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
212 // llvm.dbg.value is far away from the value then iSel may not be able
213 // handle it properly. iSel will drop llvm.dbg.value if it can not
214 // find a node corresponding to the value.
215 EverMadeChange |= PlaceDbgValues(F);
217 // If there is a mask, compare against zero, and branch that can be combined
218 // into a single target instruction, push the mask and compare into branch
219 // users. Do this before OptimizeBlock -> OptimizeInst ->
220 // OptimizeCmpExpression, which perturbs the pattern being searched for.
221 if (!DisableBranchOpts)
222 EverMadeChange |= sinkAndCmp(F);
224 bool MadeChange = true;
227 for (Function::iterator I = F.begin(); I != F.end(); ) {
228 BasicBlock *BB = I++;
229 MadeChange |= OptimizeBlock(*BB);
231 EverMadeChange |= MadeChange;
236 if (!DisableBranchOpts) {
238 SmallPtrSet<BasicBlock*, 8> WorkList;
239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
240 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
241 MadeChange |= ConstantFoldTerminator(BB, true);
242 if (!MadeChange) continue;
244 for (SmallVectorImpl<BasicBlock*>::iterator
245 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
246 if (pred_begin(*II) == pred_end(*II))
247 WorkList.insert(*II);
250 // Delete the dead blocks and any of their dead successors.
251 MadeChange |= !WorkList.empty();
252 while (!WorkList.empty()) {
253 BasicBlock *BB = *WorkList.begin();
255 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
259 for (SmallVectorImpl<BasicBlock*>::iterator
260 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
261 if (pred_begin(*II) == pred_end(*II))
262 WorkList.insert(*II);
265 // Merge pairs of basic blocks with unconditional branches, connected by
267 if (EverMadeChange || MadeChange)
268 MadeChange |= EliminateFallThrough(F);
272 EverMadeChange |= MadeChange;
275 if (ModifiedDT && DT)
278 return EverMadeChange;
281 /// EliminateFallThrough - Merge basic blocks which are connected
282 /// by a single edge, where one of the basic blocks has a single successor
283 /// pointing to the other basic block, which has a single predecessor.
284 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
285 bool Changed = false;
286 // Scan all of the blocks in the function, except for the entry block.
287 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
288 BasicBlock *BB = I++;
289 // If the destination block has a single pred, then this is a trivial
290 // edge, just collapse it.
291 BasicBlock *SinglePred = BB->getSinglePredecessor();
293 // Don't merge if BB's address is taken.
294 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
296 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
297 if (Term && !Term->isConditional()) {
299 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
300 // Remember if SinglePred was the entry block of the function.
301 // If so, we will need to move BB back to the entry position.
302 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
303 MergeBasicBlockIntoOnlyPred(BB, this);
305 if (isEntry && BB != &BB->getParent()->getEntryBlock())
306 BB->moveBefore(&BB->getParent()->getEntryBlock());
308 // We have erased a block. Update the iterator.
315 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
316 /// debug info directives, and an unconditional branch. Passes before isel
317 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
318 /// isel. Start by eliminating these blocks so we can split them the way we
320 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
321 bool MadeChange = false;
322 // Note that this intentionally skips the entry block.
323 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
324 BasicBlock *BB = I++;
326 // If this block doesn't end with an uncond branch, ignore it.
327 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
328 if (!BI || !BI->isUnconditional())
331 // If the instruction before the branch (skipping debug info) isn't a phi
332 // node, then other stuff is happening here.
333 BasicBlock::iterator BBI = BI;
334 if (BBI != BB->begin()) {
336 while (isa<DbgInfoIntrinsic>(BBI)) {
337 if (BBI == BB->begin())
341 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
345 // Do not break infinite loops.
346 BasicBlock *DestBB = BI->getSuccessor(0);
350 if (!CanMergeBlocks(BB, DestBB))
353 EliminateMostlyEmptyBlock(BB);
359 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
360 /// single uncond branch between them, and BB contains no other non-phi
362 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
363 const BasicBlock *DestBB) const {
364 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
365 // the successor. If there are more complex condition (e.g. preheaders),
366 // don't mess around with them.
367 BasicBlock::const_iterator BBI = BB->begin();
368 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
369 for (const User *U : PN->users()) {
370 const Instruction *UI = cast<Instruction>(U);
371 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
373 // If User is inside DestBB block and it is a PHINode then check
374 // incoming value. If incoming value is not from BB then this is
375 // a complex condition (e.g. preheaders) we want to avoid here.
376 if (UI->getParent() == DestBB) {
377 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
378 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
379 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
380 if (Insn && Insn->getParent() == BB &&
381 Insn->getParent() != UPN->getIncomingBlock(I))
388 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
389 // and DestBB may have conflicting incoming values for the block. If so, we
390 // can't merge the block.
391 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
392 if (!DestBBPN) return true; // no conflict.
394 // Collect the preds of BB.
395 SmallPtrSet<const BasicBlock*, 16> BBPreds;
396 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
397 // It is faster to get preds from a PHI than with pred_iterator.
398 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
399 BBPreds.insert(BBPN->getIncomingBlock(i));
401 BBPreds.insert(pred_begin(BB), pred_end(BB));
404 // Walk the preds of DestBB.
405 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
406 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
407 if (BBPreds.count(Pred)) { // Common predecessor?
408 BBI = DestBB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
410 const Value *V1 = PN->getIncomingValueForBlock(Pred);
411 const Value *V2 = PN->getIncomingValueForBlock(BB);
413 // If V2 is a phi node in BB, look up what the mapped value will be.
414 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
415 if (V2PN->getParent() == BB)
416 V2 = V2PN->getIncomingValueForBlock(Pred);
418 // If there is a conflict, bail out.
419 if (V1 != V2) return false;
428 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
429 /// an unconditional branch in it.
430 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
431 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
432 BasicBlock *DestBB = BI->getSuccessor(0);
434 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
436 // If the destination block has a single pred, then this is a trivial edge,
438 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
439 if (SinglePred != DestBB) {
440 // Remember if SinglePred was the entry block of the function. If so, we
441 // will need to move BB back to the entry position.
442 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
443 MergeBasicBlockIntoOnlyPred(DestBB, this);
445 if (isEntry && BB != &BB->getParent()->getEntryBlock())
446 BB->moveBefore(&BB->getParent()->getEntryBlock());
448 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
453 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
454 // to handle the new incoming edges it is about to have.
456 for (BasicBlock::iterator BBI = DestBB->begin();
457 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
458 // Remove the incoming value for BB, and remember it.
459 Value *InVal = PN->removeIncomingValue(BB, false);
461 // Two options: either the InVal is a phi node defined in BB or it is some
462 // value that dominates BB.
463 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
464 if (InValPhi && InValPhi->getParent() == BB) {
465 // Add all of the input values of the input PHI as inputs of this phi.
466 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
467 PN->addIncoming(InValPhi->getIncomingValue(i),
468 InValPhi->getIncomingBlock(i));
470 // Otherwise, add one instance of the dominating value for each edge that
471 // we will be adding.
472 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
473 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
474 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
476 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
477 PN->addIncoming(InVal, *PI);
482 // The PHIs are now updated, change everything that refers to BB to use
483 // DestBB and remove BB.
484 BB->replaceAllUsesWith(DestBB);
485 if (DT && !ModifiedDT) {
486 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
487 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
488 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
489 DT->changeImmediateDominator(DestBB, NewIDom);
492 BB->eraseFromParent();
495 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
498 /// SinkCast - Sink the specified cast instruction into its user blocks
499 static bool SinkCast(CastInst *CI) {
500 BasicBlock *DefBB = CI->getParent();
502 /// InsertedCasts - Only insert a cast in each block once.
503 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
505 bool MadeChange = false;
506 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
508 Use &TheUse = UI.getUse();
509 Instruction *User = cast<Instruction>(*UI);
511 // Figure out which BB this cast is used in. For PHI's this is the
512 // appropriate predecessor block.
513 BasicBlock *UserBB = User->getParent();
514 if (PHINode *PN = dyn_cast<PHINode>(User)) {
515 UserBB = PN->getIncomingBlock(TheUse);
518 // Preincrement use iterator so we don't invalidate it.
521 // If this user is in the same block as the cast, don't change the cast.
522 if (UserBB == DefBB) continue;
524 // If we have already inserted a cast into this block, use it.
525 CastInst *&InsertedCast = InsertedCasts[UserBB];
528 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
530 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
535 // Replace a use of the cast with a use of the new cast.
536 TheUse = InsertedCast;
540 // If we removed all uses, nuke the cast.
541 if (CI->use_empty()) {
542 CI->eraseFromParent();
549 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
550 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
551 /// sink it into user blocks to reduce the number of virtual
552 /// registers that must be created and coalesced.
554 /// Return true if any changes are made.
556 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
557 // If this is a noop copy,
558 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
559 EVT DstVT = TLI.getValueType(CI->getType());
561 // This is an fp<->int conversion?
562 if (SrcVT.isInteger() != DstVT.isInteger())
565 // If this is an extension, it will be a zero or sign extension, which
567 if (SrcVT.bitsLT(DstVT)) return false;
569 // If these values will be promoted, find out what they will be promoted
570 // to. This helps us consider truncates on PPC as noop copies when they
572 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
573 TargetLowering::TypePromoteInteger)
574 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
575 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
576 TargetLowering::TypePromoteInteger)
577 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
579 // If, after promotion, these are the same types, this is a noop copy.
586 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
587 /// the number of virtual registers that must be created and coalesced. This is
588 /// a clear win except on targets with multiple condition code registers
589 /// (PowerPC), where it might lose; some adjustment may be wanted there.
591 /// Return true if any changes are made.
592 static bool OptimizeCmpExpression(CmpInst *CI) {
593 BasicBlock *DefBB = CI->getParent();
595 /// InsertedCmp - Only insert a cmp in each block once.
596 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
598 bool MadeChange = false;
599 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
601 Use &TheUse = UI.getUse();
602 Instruction *User = cast<Instruction>(*UI);
604 // Preincrement use iterator so we don't invalidate it.
607 // Don't bother for PHI nodes.
608 if (isa<PHINode>(User))
611 // Figure out which BB this cmp is used in.
612 BasicBlock *UserBB = User->getParent();
614 // If this user is in the same block as the cmp, don't change the cmp.
615 if (UserBB == DefBB) continue;
617 // If we have already inserted a cmp into this block, use it.
618 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
621 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
623 CmpInst::Create(CI->getOpcode(),
624 CI->getPredicate(), CI->getOperand(0),
625 CI->getOperand(1), "", InsertPt);
629 // Replace a use of the cmp with a use of the new cmp.
630 TheUse = InsertedCmp;
634 // If we removed all uses, nuke the cmp.
636 CI->eraseFromParent();
641 /// isExtractBitsCandidateUse - Check if the candidates could
642 /// be combined with shift instruction, which includes:
643 /// 1. Truncate instruction
644 /// 2. And instruction and the imm is a mask of the low bits:
645 /// imm & (imm+1) == 0
646 static bool isExtractBitsCandidateUse(Instruction *User) {
647 if (!isa<TruncInst>(User)) {
648 if (User->getOpcode() != Instruction::And ||
649 !isa<ConstantInt>(User->getOperand(1)))
652 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
654 if ((Cimm & (Cimm + 1)).getBoolValue())
660 /// SinkShiftAndTruncate - sink both shift and truncate instruction
661 /// to the use of truncate's BB.
663 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
664 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
665 const TargetLowering &TLI) {
666 BasicBlock *UserBB = User->getParent();
667 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
668 TruncInst *TruncI = dyn_cast<TruncInst>(User);
669 bool MadeChange = false;
671 for (Value::user_iterator TruncUI = TruncI->user_begin(),
672 TruncE = TruncI->user_end();
673 TruncUI != TruncE;) {
675 Use &TruncTheUse = TruncUI.getUse();
676 Instruction *TruncUser = cast<Instruction>(*TruncUI);
677 // Preincrement use iterator so we don't invalidate it.
681 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
685 // If the use is actually a legal node, there will not be an
686 // implicit truncate.
687 // FIXME: always querying the result type is just an
688 // approximation; some nodes' legality is determined by the
689 // operand or other means. There's no good way to find out though.
690 if (TLI.isOperationLegalOrCustom(
691 ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
694 // Don't bother for PHI nodes.
695 if (isa<PHINode>(TruncUser))
698 BasicBlock *TruncUserBB = TruncUser->getParent();
700 if (UserBB == TruncUserBB)
703 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
704 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
706 if (!InsertedShift && !InsertedTrunc) {
707 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
709 if (ShiftI->getOpcode() == Instruction::AShr)
711 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
714 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
717 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
720 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
721 TruncI->getType(), "", TruncInsertPt);
725 TruncTheUse = InsertedTrunc;
731 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
732 /// the uses could potentially be combined with this shift instruction and
733 /// generate BitExtract instruction. It will only be applied if the architecture
734 /// supports BitExtract instruction. Here is an example:
736 /// %x.extract.shift = lshr i64 %arg1, 32
738 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
742 /// %x.extract.shift.1 = lshr i64 %arg1, 32
743 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
745 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
747 /// Return true if any changes are made.
748 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
749 const TargetLowering &TLI) {
750 BasicBlock *DefBB = ShiftI->getParent();
752 /// Only insert instructions in each block once.
753 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
755 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
757 bool MadeChange = false;
758 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
760 Use &TheUse = UI.getUse();
761 Instruction *User = cast<Instruction>(*UI);
762 // Preincrement use iterator so we don't invalidate it.
765 // Don't bother for PHI nodes.
766 if (isa<PHINode>(User))
769 if (!isExtractBitsCandidateUse(User))
772 BasicBlock *UserBB = User->getParent();
774 if (UserBB == DefBB) {
775 // If the shift and truncate instruction are in the same BB. The use of
776 // the truncate(TruncUse) may still introduce another truncate if not
777 // legal. In this case, we would like to sink both shift and truncate
778 // instruction to the BB of TruncUse.
781 // i64 shift.result = lshr i64 opnd, imm
782 // trunc.result = trunc shift.result to i16
785 // ----> We will have an implicit truncate here if the architecture does
786 // not have i16 compare.
787 // cmp i16 trunc.result, opnd2
789 if (isa<TruncInst>(User) && shiftIsLegal
790 // If the type of the truncate is legal, no trucate will be
791 // introduced in other basic blocks.
792 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
794 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
798 // If we have already inserted a shift into this block, use it.
799 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
801 if (!InsertedShift) {
802 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
804 if (ShiftI->getOpcode() == Instruction::AShr)
806 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
809 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
814 // Replace a use of the shift with a use of the new shift.
815 TheUse = InsertedShift;
818 // If we removed all uses, nuke the shift.
819 if (ShiftI->use_empty())
820 ShiftI->eraseFromParent();
826 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
828 void replaceCall(Value *With) override {
829 CI->replaceAllUsesWith(With);
830 CI->eraseFromParent();
832 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
833 if (ConstantInt *SizeCI =
834 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
835 return SizeCI->isAllOnesValue();
839 } // end anonymous namespace
841 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
842 BasicBlock *BB = CI->getParent();
844 // Lower inline assembly if we can.
845 // If we found an inline asm expession, and if the target knows how to
846 // lower it to normal LLVM code, do so now.
847 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
848 if (TLI->ExpandInlineAsm(CI)) {
849 // Avoid invalidating the iterator.
850 CurInstIterator = BB->begin();
851 // Avoid processing instructions out of order, which could cause
852 // reuse before a value is defined.
856 // Sink address computing for memory operands into the block.
857 if (OptimizeInlineAsmInst(CI))
861 // Lower all uses of llvm.objectsize.*
862 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
863 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
864 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
865 Type *ReturnTy = CI->getType();
866 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
868 // Substituting this can cause recursive simplifications, which can
869 // invalidate our iterator. Use a WeakVH to hold onto it in case this
871 WeakVH IterHandle(CurInstIterator);
873 replaceAndRecursivelySimplify(CI, RetVal,
874 TLI ? TLI->getDataLayout() : nullptr,
875 TLInfo, ModifiedDT ? nullptr : DT);
877 // If the iterator instruction was recursively deleted, start over at the
878 // start of the block.
879 if (IterHandle != CurInstIterator) {
880 CurInstIterator = BB->begin();
887 SmallVector<Value*, 2> PtrOps;
889 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
890 while (!PtrOps.empty())
891 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
895 // From here on out we're working with named functions.
896 if (!CI->getCalledFunction()) return false;
898 // We'll need DataLayout from here on out.
899 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
900 if (!TD) return false;
902 // Lower all default uses of _chk calls. This is very similar
903 // to what InstCombineCalls does, but here we are only lowering calls
904 // that have the default "don't know" as the objectsize. Anything else
905 // should be left alone.
906 CodeGenPrepareFortifiedLibCalls Simplifier;
907 return Simplifier.fold(CI, TD, TLInfo);
910 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
911 /// instructions to the predecessor to enable tail call optimizations. The
912 /// case it is currently looking for is:
915 /// %tmp0 = tail call i32 @f0()
918 /// %tmp1 = tail call i32 @f1()
921 /// %tmp2 = tail call i32 @f2()
924 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
932 /// %tmp0 = tail call i32 @f0()
935 /// %tmp1 = tail call i32 @f1()
938 /// %tmp2 = tail call i32 @f2()
941 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
945 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
949 PHINode *PN = nullptr;
950 BitCastInst *BCI = nullptr;
951 Value *V = RI->getReturnValue();
953 BCI = dyn_cast<BitCastInst>(V);
955 V = BCI->getOperand(0);
957 PN = dyn_cast<PHINode>(V);
962 if (PN && PN->getParent() != BB)
965 // It's not safe to eliminate the sign / zero extension of the return value.
966 // See llvm::isInTailCallPosition().
967 const Function *F = BB->getParent();
968 AttributeSet CallerAttrs = F->getAttributes();
969 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
970 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
973 // Make sure there are no instructions between the PHI and return, or that the
974 // return is the first instruction in the block.
976 BasicBlock::iterator BI = BB->begin();
977 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
979 // Also skip over the bitcast.
984 BasicBlock::iterator BI = BB->begin();
985 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
990 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
992 SmallVector<CallInst*, 4> TailCalls;
994 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
995 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
996 // Make sure the phi value is indeed produced by the tail call.
997 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
998 TLI->mayBeEmittedAsTailCall(CI))
999 TailCalls.push_back(CI);
1002 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1003 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1004 if (!VisitedBBs.insert(*PI).second)
1007 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1008 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1009 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1010 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1014 CallInst *CI = dyn_cast<CallInst>(&*RI);
1015 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1016 TailCalls.push_back(CI);
1020 bool Changed = false;
1021 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1022 CallInst *CI = TailCalls[i];
1025 // Conservatively require the attributes of the call to match those of the
1026 // return. Ignore noalias because it doesn't affect the call sequence.
1027 AttributeSet CalleeAttrs = CS.getAttributes();
1028 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1029 removeAttribute(Attribute::NoAlias) !=
1030 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1031 removeAttribute(Attribute::NoAlias))
1034 // Make sure the call instruction is followed by an unconditional branch to
1035 // the return block.
1036 BasicBlock *CallBB = CI->getParent();
1037 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1038 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1041 // Duplicate the return into CallBB.
1042 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1043 ModifiedDT = Changed = true;
1047 // If we eliminated all predecessors of the block, delete the block now.
1048 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1049 BB->eraseFromParent();
1054 //===----------------------------------------------------------------------===//
1055 // Memory Optimization
1056 //===----------------------------------------------------------------------===//
1060 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1061 /// which holds actual Value*'s for register values.
1062 struct ExtAddrMode : public TargetLowering::AddrMode {
1065 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1066 void print(raw_ostream &OS) const;
1069 bool operator==(const ExtAddrMode& O) const {
1070 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1071 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1072 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1077 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1083 void ExtAddrMode::print(raw_ostream &OS) const {
1084 bool NeedPlus = false;
1087 OS << (NeedPlus ? " + " : "")
1089 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1094 OS << (NeedPlus ? " + " : "")
1100 OS << (NeedPlus ? " + " : "")
1102 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1106 OS << (NeedPlus ? " + " : "")
1108 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1114 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1115 void ExtAddrMode::dump() const {
1121 /// \brief This class provides transaction based operation on the IR.
1122 /// Every change made through this class is recorded in the internal state and
1123 /// can be undone (rollback) until commit is called.
1124 class TypePromotionTransaction {
1126 /// \brief This represents the common interface of the individual transaction.
1127 /// Each class implements the logic for doing one specific modification on
1128 /// the IR via the TypePromotionTransaction.
1129 class TypePromotionAction {
1131 /// The Instruction modified.
1135 /// \brief Constructor of the action.
1136 /// The constructor performs the related action on the IR.
1137 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1139 virtual ~TypePromotionAction() {}
1141 /// \brief Undo the modification done by this action.
1142 /// When this method is called, the IR must be in the same state as it was
1143 /// before this action was applied.
1144 /// \pre Undoing the action works if and only if the IR is in the exact same
1145 /// state as it was directly after this action was applied.
1146 virtual void undo() = 0;
1148 /// \brief Advocate every change made by this action.
1149 /// When the results on the IR of the action are to be kept, it is important
1150 /// to call this function, otherwise hidden information may be kept forever.
1151 virtual void commit() {
1152 // Nothing to be done, this action is not doing anything.
1156 /// \brief Utility to remember the position of an instruction.
1157 class InsertionHandler {
1158 /// Position of an instruction.
1159 /// Either an instruction:
1160 /// - Is the first in a basic block: BB is used.
1161 /// - Has a previous instructon: PrevInst is used.
1163 Instruction *PrevInst;
1166 /// Remember whether or not the instruction had a previous instruction.
1167 bool HasPrevInstruction;
1170 /// \brief Record the position of \p Inst.
1171 InsertionHandler(Instruction *Inst) {
1172 BasicBlock::iterator It = Inst;
1173 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1174 if (HasPrevInstruction)
1175 Point.PrevInst = --It;
1177 Point.BB = Inst->getParent();
1180 /// \brief Insert \p Inst at the recorded position.
1181 void insert(Instruction *Inst) {
1182 if (HasPrevInstruction) {
1183 if (Inst->getParent())
1184 Inst->removeFromParent();
1185 Inst->insertAfter(Point.PrevInst);
1187 Instruction *Position = Point.BB->getFirstInsertionPt();
1188 if (Inst->getParent())
1189 Inst->moveBefore(Position);
1191 Inst->insertBefore(Position);
1196 /// \brief Move an instruction before another.
1197 class InstructionMoveBefore : public TypePromotionAction {
1198 /// Original position of the instruction.
1199 InsertionHandler Position;
1202 /// \brief Move \p Inst before \p Before.
1203 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1204 : TypePromotionAction(Inst), Position(Inst) {
1205 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1206 Inst->moveBefore(Before);
1209 /// \brief Move the instruction back to its original position.
1210 void undo() override {
1211 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1212 Position.insert(Inst);
1216 /// \brief Set the operand of an instruction with a new value.
1217 class OperandSetter : public TypePromotionAction {
1218 /// Original operand of the instruction.
1220 /// Index of the modified instruction.
1224 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1225 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1226 : TypePromotionAction(Inst), Idx(Idx) {
1227 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1228 << "for:" << *Inst << "\n"
1229 << "with:" << *NewVal << "\n");
1230 Origin = Inst->getOperand(Idx);
1231 Inst->setOperand(Idx, NewVal);
1234 /// \brief Restore the original value of the instruction.
1235 void undo() override {
1236 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1237 << "for: " << *Inst << "\n"
1238 << "with: " << *Origin << "\n");
1239 Inst->setOperand(Idx, Origin);
1243 /// \brief Hide the operands of an instruction.
1244 /// Do as if this instruction was not using any of its operands.
1245 class OperandsHider : public TypePromotionAction {
1246 /// The list of original operands.
1247 SmallVector<Value *, 4> OriginalValues;
1250 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1251 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1252 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1253 unsigned NumOpnds = Inst->getNumOperands();
1254 OriginalValues.reserve(NumOpnds);
1255 for (unsigned It = 0; It < NumOpnds; ++It) {
1256 // Save the current operand.
1257 Value *Val = Inst->getOperand(It);
1258 OriginalValues.push_back(Val);
1260 // We could use OperandSetter here, but that would implied an overhead
1261 // that we are not willing to pay.
1262 Inst->setOperand(It, UndefValue::get(Val->getType()));
1266 /// \brief Restore the original list of uses.
1267 void undo() override {
1268 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1269 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1270 Inst->setOperand(It, OriginalValues[It]);
1274 /// \brief Build a truncate instruction.
1275 class TruncBuilder : public TypePromotionAction {
1278 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1280 /// trunc Opnd to Ty.
1281 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1282 IRBuilder<> Builder(Opnd);
1283 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1284 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1287 /// \brief Get the built value.
1288 Value *getBuiltValue() { return Val; }
1290 /// \brief Remove the built instruction.
1291 void undo() override {
1292 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1293 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1294 IVal->eraseFromParent();
1298 /// \brief Build a sign extension instruction.
1299 class SExtBuilder : public TypePromotionAction {
1302 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1304 /// sext Opnd to Ty.
1305 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1306 : TypePromotionAction(InsertPt) {
1307 IRBuilder<> Builder(InsertPt);
1308 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1309 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1312 /// \brief Get the built value.
1313 Value *getBuiltValue() { return Val; }
1315 /// \brief Remove the built instruction.
1316 void undo() override {
1317 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1318 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1319 IVal->eraseFromParent();
1323 /// \brief Build a zero extension instruction.
1324 class ZExtBuilder : public TypePromotionAction {
1327 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1329 /// zext Opnd to Ty.
1330 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1331 : TypePromotionAction(InsertPt) {
1332 IRBuilder<> Builder(InsertPt);
1333 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1334 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1337 /// \brief Get the built value.
1338 Value *getBuiltValue() { return Val; }
1340 /// \brief Remove the built instruction.
1341 void undo() override {
1342 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1343 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1344 IVal->eraseFromParent();
1348 /// \brief Mutate an instruction to another type.
1349 class TypeMutator : public TypePromotionAction {
1350 /// Record the original type.
1354 /// \brief Mutate the type of \p Inst into \p NewTy.
1355 TypeMutator(Instruction *Inst, Type *NewTy)
1356 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1357 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1359 Inst->mutateType(NewTy);
1362 /// \brief Mutate the instruction back to its original type.
1363 void undo() override {
1364 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1366 Inst->mutateType(OrigTy);
1370 /// \brief Replace the uses of an instruction by another instruction.
1371 class UsesReplacer : public TypePromotionAction {
1372 /// Helper structure to keep track of the replaced uses.
1373 struct InstructionAndIdx {
1374 /// The instruction using the instruction.
1376 /// The index where this instruction is used for Inst.
1378 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1379 : Inst(Inst), Idx(Idx) {}
1382 /// Keep track of the original uses (pair Instruction, Index).
1383 SmallVector<InstructionAndIdx, 4> OriginalUses;
1384 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1387 /// \brief Replace all the use of \p Inst by \p New.
1388 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1389 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1391 // Record the original uses.
1392 for (Use &U : Inst->uses()) {
1393 Instruction *UserI = cast<Instruction>(U.getUser());
1394 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1396 // Now, we can replace the uses.
1397 Inst->replaceAllUsesWith(New);
1400 /// \brief Reassign the original uses of Inst to Inst.
1401 void undo() override {
1402 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1403 for (use_iterator UseIt = OriginalUses.begin(),
1404 EndIt = OriginalUses.end();
1405 UseIt != EndIt; ++UseIt) {
1406 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1411 /// \brief Remove an instruction from the IR.
1412 class InstructionRemover : public TypePromotionAction {
1413 /// Original position of the instruction.
1414 InsertionHandler Inserter;
1415 /// Helper structure to hide all the link to the instruction. In other
1416 /// words, this helps to do as if the instruction was removed.
1417 OperandsHider Hider;
1418 /// Keep track of the uses replaced, if any.
1419 UsesReplacer *Replacer;
1422 /// \brief Remove all reference of \p Inst and optinally replace all its
1424 /// \pre If !Inst->use_empty(), then New != nullptr
1425 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1426 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1429 Replacer = new UsesReplacer(Inst, New);
1430 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1431 Inst->removeFromParent();
1434 ~InstructionRemover() { delete Replacer; }
1436 /// \brief Really remove the instruction.
1437 void commit() override { delete Inst; }
1439 /// \brief Resurrect the instruction and reassign it to the proper uses if
1440 /// new value was provided when build this action.
1441 void undo() override {
1442 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1443 Inserter.insert(Inst);
1451 /// Restoration point.
1452 /// The restoration point is a pointer to an action instead of an iterator
1453 /// because the iterator may be invalidated but not the pointer.
1454 typedef const TypePromotionAction *ConstRestorationPt;
1455 /// Advocate every changes made in that transaction.
1457 /// Undo all the changes made after the given point.
1458 void rollback(ConstRestorationPt Point);
1459 /// Get the current restoration point.
1460 ConstRestorationPt getRestorationPoint() const;
1462 /// \name API for IR modification with state keeping to support rollback.
1464 /// Same as Instruction::setOperand.
1465 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1466 /// Same as Instruction::eraseFromParent.
1467 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1468 /// Same as Value::replaceAllUsesWith.
1469 void replaceAllUsesWith(Instruction *Inst, Value *New);
1470 /// Same as Value::mutateType.
1471 void mutateType(Instruction *Inst, Type *NewTy);
1472 /// Same as IRBuilder::createTrunc.
1473 Value *createTrunc(Instruction *Opnd, Type *Ty);
1474 /// Same as IRBuilder::createSExt.
1475 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1476 /// Same as IRBuilder::createZExt.
1477 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1478 /// Same as Instruction::moveBefore.
1479 void moveBefore(Instruction *Inst, Instruction *Before);
1483 /// The ordered list of actions made so far.
1484 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1485 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1488 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1491 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1494 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1497 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1500 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1502 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1505 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1506 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1509 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1511 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1512 Value *Val = Ptr->getBuiltValue();
1513 Actions.push_back(std::move(Ptr));
1517 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1518 Value *Opnd, Type *Ty) {
1519 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1520 Value *Val = Ptr->getBuiltValue();
1521 Actions.push_back(std::move(Ptr));
1525 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1526 Value *Opnd, Type *Ty) {
1527 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1528 Value *Val = Ptr->getBuiltValue();
1529 Actions.push_back(std::move(Ptr));
1533 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1534 Instruction *Before) {
1536 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1539 TypePromotionTransaction::ConstRestorationPt
1540 TypePromotionTransaction::getRestorationPoint() const {
1541 return !Actions.empty() ? Actions.back().get() : nullptr;
1544 void TypePromotionTransaction::commit() {
1545 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1551 void TypePromotionTransaction::rollback(
1552 TypePromotionTransaction::ConstRestorationPt Point) {
1553 while (!Actions.empty() && Point != Actions.back().get()) {
1554 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1559 /// \brief A helper class for matching addressing modes.
1561 /// This encapsulates the logic for matching the target-legal addressing modes.
1562 class AddressingModeMatcher {
1563 SmallVectorImpl<Instruction*> &AddrModeInsts;
1564 const TargetLowering &TLI;
1566 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1567 /// the memory instruction that we're computing this address for.
1569 Instruction *MemoryInst;
1571 /// AddrMode - This is the addressing mode that we're building up. This is
1572 /// part of the return value of this addressing mode matching stuff.
1573 ExtAddrMode &AddrMode;
1575 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1576 const SetOfInstrs &InsertedTruncs;
1577 /// A map from the instructions to their type before promotion.
1578 InstrToOrigTy &PromotedInsts;
1579 /// The ongoing transaction where every action should be registered.
1580 TypePromotionTransaction &TPT;
1582 /// IgnoreProfitability - This is set to true when we should not do
1583 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1584 /// always returns true.
1585 bool IgnoreProfitability;
1587 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1588 const TargetLowering &T, Type *AT,
1589 Instruction *MI, ExtAddrMode &AM,
1590 const SetOfInstrs &InsertedTruncs,
1591 InstrToOrigTy &PromotedInsts,
1592 TypePromotionTransaction &TPT)
1593 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1594 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1595 IgnoreProfitability = false;
1599 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1600 /// give an access type of AccessTy. This returns a list of involved
1601 /// instructions in AddrModeInsts.
1602 /// \p InsertedTruncs The truncate instruction inserted by other
1605 /// \p PromotedInsts maps the instructions to their type before promotion.
1606 /// \p The ongoing transaction where every action should be registered.
1607 static ExtAddrMode Match(Value *V, Type *AccessTy,
1608 Instruction *MemoryInst,
1609 SmallVectorImpl<Instruction*> &AddrModeInsts,
1610 const TargetLowering &TLI,
1611 const SetOfInstrs &InsertedTruncs,
1612 InstrToOrigTy &PromotedInsts,
1613 TypePromotionTransaction &TPT) {
1616 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1617 MemoryInst, Result, InsertedTruncs,
1618 PromotedInsts, TPT).MatchAddr(V, 0);
1619 (void)Success; assert(Success && "Couldn't select *anything*?");
1623 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1624 bool MatchAddr(Value *V, unsigned Depth);
1625 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1626 bool *MovedAway = nullptr);
1627 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1628 ExtAddrMode &AMBefore,
1629 ExtAddrMode &AMAfter);
1630 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1631 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1632 Value *PromotedOperand) const;
1635 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1636 /// Return true and update AddrMode if this addr mode is legal for the target,
1638 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1640 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1641 // mode. Just process that directly.
1643 return MatchAddr(ScaleReg, Depth);
1645 // If the scale is 0, it takes nothing to add this.
1649 // If we already have a scale of this value, we can add to it, otherwise, we
1650 // need an available scale field.
1651 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1654 ExtAddrMode TestAddrMode = AddrMode;
1656 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1657 // [A+B + A*7] -> [B+A*8].
1658 TestAddrMode.Scale += Scale;
1659 TestAddrMode.ScaledReg = ScaleReg;
1661 // If the new address isn't legal, bail out.
1662 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1665 // It was legal, so commit it.
1666 AddrMode = TestAddrMode;
1668 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1669 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1670 // X*Scale + C*Scale to addr mode.
1671 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1672 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1673 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1674 TestAddrMode.ScaledReg = AddLHS;
1675 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1677 // If this addressing mode is legal, commit it and remember that we folded
1678 // this instruction.
1679 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1680 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1681 AddrMode = TestAddrMode;
1686 // Otherwise, not (x+c)*scale, just return what we have.
1690 /// MightBeFoldableInst - This is a little filter, which returns true if an
1691 /// addressing computation involving I might be folded into a load/store
1692 /// accessing it. This doesn't need to be perfect, but needs to accept at least
1693 /// the set of instructions that MatchOperationAddr can.
1694 static bool MightBeFoldableInst(Instruction *I) {
1695 switch (I->getOpcode()) {
1696 case Instruction::BitCast:
1697 case Instruction::AddrSpaceCast:
1698 // Don't touch identity bitcasts.
1699 if (I->getType() == I->getOperand(0)->getType())
1701 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1702 case Instruction::PtrToInt:
1703 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1705 case Instruction::IntToPtr:
1706 // We know the input is intptr_t, so this is foldable.
1708 case Instruction::Add:
1710 case Instruction::Mul:
1711 case Instruction::Shl:
1712 // Can only handle X*C and X << C.
1713 return isa<ConstantInt>(I->getOperand(1));
1714 case Instruction::GetElementPtr:
1721 /// \brief Hepler class to perform type promotion.
1722 class TypePromotionHelper {
1723 /// \brief Utility function to check whether or not a sign or zero extension
1724 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
1725 /// either using the operands of \p Inst or promoting \p Inst.
1726 /// The type of the extension is defined by \p IsSExt.
1727 /// In other words, check if:
1728 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
1729 /// #1 Promotion applies:
1730 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
1731 /// #2 Operand reuses:
1732 /// ext opnd1 to ConsideredExtType.
1733 /// \p PromotedInsts maps the instructions to their type before promotion.
1734 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
1735 const InstrToOrigTy &PromotedInsts, bool IsSExt);
1737 /// \brief Utility function to determine if \p OpIdx should be promoted when
1738 /// promoting \p Inst.
1739 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
1740 if (isa<SelectInst>(Inst) && OpIdx == 0)
1745 /// \brief Utility function to promote the operand of \p Ext when this
1746 /// operand is a promotable trunc or sext or zext.
1747 /// \p PromotedInsts maps the instructions to their type before promotion.
1748 /// \p CreatedInsts[out] contains how many non-free instructions have been
1749 /// created to promote the operand of Ext.
1750 /// Should never be called directly.
1751 /// \return The promoted value which is used instead of Ext.
1752 static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
1753 TypePromotionTransaction &TPT,
1754 InstrToOrigTy &PromotedInsts,
1755 unsigned &CreatedInsts);
1757 /// \brief Utility function to promote the operand of \p Ext when this
1758 /// operand is promotable and is not a supported trunc or sext.
1759 /// \p PromotedInsts maps the instructions to their type before promotion.
1760 /// \p CreatedInsts[out] contains how many non-free instructions have been
1761 /// created to promote the operand of Ext.
1762 /// Should never be called directly.
1763 /// \return The promoted value which is used instead of Ext.
1764 static Value *promoteOperandForOther(Instruction *Ext,
1765 TypePromotionTransaction &TPT,
1766 InstrToOrigTy &PromotedInsts,
1767 unsigned &CreatedInsts, bool IsSExt);
1769 /// \see promoteOperandForOther.
1770 static Value *signExtendOperandForOther(Instruction *Ext,
1771 TypePromotionTransaction &TPT,
1772 InstrToOrigTy &PromotedInsts,
1773 unsigned &CreatedInsts) {
1774 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
1777 /// \see promoteOperandForOther.
1778 static Value *zeroExtendOperandForOther(Instruction *Ext,
1779 TypePromotionTransaction &TPT,
1780 InstrToOrigTy &PromotedInsts,
1781 unsigned &CreatedInsts) {
1782 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
1786 /// Type for the utility function that promotes the operand of Ext.
1787 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
1788 InstrToOrigTy &PromotedInsts,
1789 unsigned &CreatedInsts);
1790 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
1791 /// action to promote the operand of \p Ext instead of using Ext.
1792 /// \return NULL if no promotable action is possible with the current
1794 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1795 /// the others CodeGenPrepare optimizations. This information is important
1796 /// because we do not want to promote these instructions as CodeGenPrepare
1797 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1798 /// \p PromotedInsts maps the instructions to their type before promotion.
1799 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1800 const TargetLowering &TLI,
1801 const InstrToOrigTy &PromotedInsts);
1804 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1805 Type *ConsideredExtType,
1806 const InstrToOrigTy &PromotedInsts,
1808 // We can always get through zext.
1809 if (isa<ZExtInst>(Inst))
1812 // sext(sext) is ok too.
1813 if (IsSExt && isa<SExtInst>(Inst))
1816 // We can get through binary operator, if it is legal. In other words, the
1817 // binary operator must have a nuw or nsw flag.
1818 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1819 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1820 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
1821 (IsSExt && BinOp->hasNoSignedWrap())))
1824 // Check if we can do the following simplification.
1825 // ext(trunc(opnd)) --> ext(opnd)
1826 if (!isa<TruncInst>(Inst))
1829 Value *OpndVal = Inst->getOperand(0);
1830 // Check if we can use this operand in the extension.
1831 // If the type is larger than the result type of the extension,
1833 if (OpndVal->getType()->getIntegerBitWidth() >
1834 ConsideredExtType->getIntegerBitWidth())
1837 // If the operand of the truncate is not an instruction, we will not have
1838 // any information on the dropped bits.
1839 // (Actually we could for constant but it is not worth the extra logic).
1840 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1844 // Check if the source of the type is narrow enough.
1845 // I.e., check that trunc just drops extended bits of the same kind of
1847 // #1 get the type of the operand and check the kind of the extended bits.
1848 const Type *OpndType;
1849 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1850 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
1851 OpndType = It->second.Ty;
1852 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
1853 OpndType = Opnd->getOperand(0)->getType();
1857 // #2 check that the truncate just drop extended bits.
1858 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1864 TypePromotionHelper::Action TypePromotionHelper::getAction(
1865 Instruction *Ext, const SetOfInstrs &InsertedTruncs,
1866 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1867 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
1868 "Unexpected instruction type");
1869 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
1870 Type *ExtTy = Ext->getType();
1871 bool IsSExt = isa<SExtInst>(Ext);
1872 // If the operand of the extension is not an instruction, we cannot
1874 // If it, check we can get through.
1875 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
1878 // Do not promote if the operand has been added by codegenprepare.
1879 // Otherwise, it means we are undoing an optimization that is likely to be
1880 // redone, thus causing potential infinite loop.
1881 if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
1884 // SExt or Trunc instructions.
1885 // Return the related handler.
1886 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
1887 isa<ZExtInst>(ExtOpnd))
1888 return promoteOperandForTruncAndAnyExt;
1890 // Regular instruction.
1891 // Abort early if we will have to insert non-free instructions.
1892 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
1894 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
1897 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
1898 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1899 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1900 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1901 // get through it and this method should not be called.
1902 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1903 Value *ExtVal = SExt;
1904 if (isa<ZExtInst>(SExtOpnd)) {
1905 // Replace s|zext(zext(opnd))
1908 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1909 TPT.replaceAllUsesWith(SExt, ZExt);
1910 TPT.eraseInstruction(SExt);
1913 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
1915 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1919 // Remove dead code.
1920 if (SExtOpnd->use_empty())
1921 TPT.eraseInstruction(SExtOpnd);
1923 // Check if the extension is still needed.
1924 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1925 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1928 // At this point we have: ext ty opnd to ty.
1929 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1930 Value *NextVal = ExtInst->getOperand(0);
1931 TPT.eraseInstruction(ExtInst, NextVal);
1935 Value *TypePromotionHelper::promoteOperandForOther(
1936 Instruction *Ext, TypePromotionTransaction &TPT,
1937 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
1938 // By construction, the operand of Ext is an instruction. Otherwise we cannot
1939 // get through it and this method should not be called.
1940 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
1942 if (!ExtOpnd->hasOneUse()) {
1943 // ExtOpnd will be promoted.
1944 // All its uses, but Ext, will need to use a truncated value of the
1945 // promoted version.
1946 // Create the truncate now.
1947 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
1948 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1949 ITrunc->removeFromParent();
1950 // Insert it just after the definition.
1951 ITrunc->insertAfter(ExtOpnd);
1954 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
1955 // Restore the operand of Ext (which has been replace by the previous call
1956 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1957 TPT.setOperand(Ext, 0, ExtOpnd);
1960 // Get through the Instruction:
1961 // 1. Update its type.
1962 // 2. Replace the uses of Ext by Inst.
1963 // 3. Extend each operand that needs to be extended.
1965 // Remember the original type of the instruction before promotion.
1966 // This is useful to know that the high bits are sign extended bits.
1967 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
1968 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
1970 TPT.mutateType(ExtOpnd, Ext->getType());
1972 TPT.replaceAllUsesWith(Ext, ExtOpnd);
1974 Instruction *ExtForOpnd = Ext;
1976 DEBUG(dbgs() << "Propagate Ext to operands\n");
1977 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1979 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
1980 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
1981 !shouldExtOperand(ExtOpnd, OpIdx)) {
1982 DEBUG(dbgs() << "No need to propagate\n");
1985 // Check if we can statically extend the operand.
1986 Value *Opnd = ExtOpnd->getOperand(OpIdx);
1987 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1988 DEBUG(dbgs() << "Statically extend\n");
1989 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
1990 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
1991 : Cst->getValue().zext(BitWidth);
1992 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
1995 // UndefValue are typed, so we have to statically sign extend them.
1996 if (isa<UndefValue>(Opnd)) {
1997 DEBUG(dbgs() << "Statically extend\n");
1998 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2002 // Otherwise we have to explicity sign extend the operand.
2003 // Check if Ext was reused to extend an operand.
2005 // If yes, create a new one.
2006 DEBUG(dbgs() << "More operands to ext\n");
2008 cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2009 : TPT.createZExt(Ext, Opnd, Ext->getType()));
2013 TPT.setOperand(ExtForOpnd, 0, Opnd);
2015 // Move the sign extension before the insertion point.
2016 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2017 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2018 // If more sext are required, new instructions will have to be created.
2019 ExtForOpnd = nullptr;
2021 if (ExtForOpnd == Ext) {
2022 DEBUG(dbgs() << "Extension is useless now\n");
2023 TPT.eraseInstruction(Ext);
2028 /// IsPromotionProfitable - Check whether or not promoting an instruction
2029 /// to a wider type was profitable.
2030 /// \p MatchedSize gives the number of instructions that have been matched
2031 /// in the addressing mode after the promotion was applied.
2032 /// \p SizeWithPromotion gives the number of created instructions for
2033 /// the promotion plus the number of instructions that have been
2034 /// matched in the addressing mode before the promotion.
2035 /// \p PromotedOperand is the value that has been promoted.
2036 /// \return True if the promotion is profitable, false otherwise.
2038 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2039 unsigned SizeWithPromotion,
2040 Value *PromotedOperand) const {
2041 // We folded less instructions than what we created to promote the operand.
2042 // This is not profitable.
2043 if (MatchedSize < SizeWithPromotion)
2045 if (MatchedSize > SizeWithPromotion)
2047 // The promotion is neutral but it may help folding the sign extension in
2048 // loads for instance.
2049 // Check that we did not create an illegal instruction.
2050 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2053 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2054 // If the ISDOpcode is undefined, it was undefined before the promotion.
2057 // Otherwise, check if the promoted instruction is legal or not.
2058 return TLI.isOperationLegalOrCustom(
2059 ISDOpcode, TLI.getValueType(PromotedInst->getType()));
2062 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2063 /// fold the operation into the addressing mode. If so, update the addressing
2064 /// mode and return true, otherwise return false without modifying AddrMode.
2065 /// If \p MovedAway is not NULL, it contains the information of whether or
2066 /// not AddrInst has to be folded into the addressing mode on success.
2067 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2068 /// because it has been moved away.
2069 /// Thus AddrInst must not be added in the matched instructions.
2070 /// This state can happen when AddrInst is a sext, since it may be moved away.
2071 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2072 /// not be referenced anymore.
2073 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2076 // Avoid exponential behavior on extremely deep expression trees.
2077 if (Depth >= 5) return false;
2079 // By default, all matched instructions stay in place.
2084 case Instruction::PtrToInt:
2085 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2086 return MatchAddr(AddrInst->getOperand(0), Depth);
2087 case Instruction::IntToPtr:
2088 // This inttoptr is a no-op if the integer type is pointer sized.
2089 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2090 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2091 return MatchAddr(AddrInst->getOperand(0), Depth);
2093 case Instruction::BitCast:
2094 case Instruction::AddrSpaceCast:
2095 // BitCast is always a noop, and we can handle it as long as it is
2096 // int->int or pointer->pointer (we don't want int<->fp or something).
2097 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2098 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2099 // Don't touch identity bitcasts. These were probably put here by LSR,
2100 // and we don't want to mess around with them. Assume it knows what it
2102 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2103 return MatchAddr(AddrInst->getOperand(0), Depth);
2105 case Instruction::Add: {
2106 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2107 ExtAddrMode BackupAddrMode = AddrMode;
2108 unsigned OldSize = AddrModeInsts.size();
2109 // Start a transaction at this point.
2110 // The LHS may match but not the RHS.
2111 // Therefore, we need a higher level restoration point to undo partially
2112 // matched operation.
2113 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2114 TPT.getRestorationPoint();
2116 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2117 MatchAddr(AddrInst->getOperand(0), Depth+1))
2120 // Restore the old addr mode info.
2121 AddrMode = BackupAddrMode;
2122 AddrModeInsts.resize(OldSize);
2123 TPT.rollback(LastKnownGood);
2125 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2126 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2127 MatchAddr(AddrInst->getOperand(1), Depth+1))
2130 // Otherwise we definitely can't merge the ADD in.
2131 AddrMode = BackupAddrMode;
2132 AddrModeInsts.resize(OldSize);
2133 TPT.rollback(LastKnownGood);
2136 //case Instruction::Or:
2137 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2139 case Instruction::Mul:
2140 case Instruction::Shl: {
2141 // Can only handle X*C and X << C.
2142 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2145 int64_t Scale = RHS->getSExtValue();
2146 if (Opcode == Instruction::Shl)
2147 Scale = 1LL << Scale;
2149 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2151 case Instruction::GetElementPtr: {
2152 // Scan the GEP. We check it if it contains constant offsets and at most
2153 // one variable offset.
2154 int VariableOperand = -1;
2155 unsigned VariableScale = 0;
2157 int64_t ConstantOffset = 0;
2158 const DataLayout *TD = TLI.getDataLayout();
2159 gep_type_iterator GTI = gep_type_begin(AddrInst);
2160 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2161 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2162 const StructLayout *SL = TD->getStructLayout(STy);
2164 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2165 ConstantOffset += SL->getElementOffset(Idx);
2167 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2168 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2169 ConstantOffset += CI->getSExtValue()*TypeSize;
2170 } else if (TypeSize) { // Scales of zero don't do anything.
2171 // We only allow one variable index at the moment.
2172 if (VariableOperand != -1)
2175 // Remember the variable index.
2176 VariableOperand = i;
2177 VariableScale = TypeSize;
2182 // A common case is for the GEP to only do a constant offset. In this case,
2183 // just add it to the disp field and check validity.
2184 if (VariableOperand == -1) {
2185 AddrMode.BaseOffs += ConstantOffset;
2186 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2187 // Check to see if we can fold the base pointer in too.
2188 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2191 AddrMode.BaseOffs -= ConstantOffset;
2195 // Save the valid addressing mode in case we can't match.
2196 ExtAddrMode BackupAddrMode = AddrMode;
2197 unsigned OldSize = AddrModeInsts.size();
2199 // See if the scale and offset amount is valid for this target.
2200 AddrMode.BaseOffs += ConstantOffset;
2202 // Match the base operand of the GEP.
2203 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2204 // If it couldn't be matched, just stuff the value in a register.
2205 if (AddrMode.HasBaseReg) {
2206 AddrMode = BackupAddrMode;
2207 AddrModeInsts.resize(OldSize);
2210 AddrMode.HasBaseReg = true;
2211 AddrMode.BaseReg = AddrInst->getOperand(0);
2214 // Match the remaining variable portion of the GEP.
2215 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2217 // If it couldn't be matched, try stuffing the base into a register
2218 // instead of matching it, and retrying the match of the scale.
2219 AddrMode = BackupAddrMode;
2220 AddrModeInsts.resize(OldSize);
2221 if (AddrMode.HasBaseReg)
2223 AddrMode.HasBaseReg = true;
2224 AddrMode.BaseReg = AddrInst->getOperand(0);
2225 AddrMode.BaseOffs += ConstantOffset;
2226 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2227 VariableScale, Depth)) {
2228 // If even that didn't work, bail.
2229 AddrMode = BackupAddrMode;
2230 AddrModeInsts.resize(OldSize);
2237 case Instruction::SExt:
2238 case Instruction::ZExt: {
2239 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2243 // Try to move this ext out of the way of the addressing mode.
2244 // Ask for a method for doing so.
2245 TypePromotionHelper::Action TPH =
2246 TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
2250 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2251 TPT.getRestorationPoint();
2252 unsigned CreatedInsts = 0;
2253 Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
2254 // SExt has been moved away.
2255 // Thus either it will be rematched later in the recursive calls or it is
2256 // gone. Anyway, we must not fold it into the addressing mode at this point.
2260 // addr = gep base, idx
2262 // promotedOpnd = ext opnd <- no match here
2263 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2264 // addr = gep base, op <- match
2268 assert(PromotedOperand &&
2269 "TypePromotionHelper should have filtered out those cases");
2271 ExtAddrMode BackupAddrMode = AddrMode;
2272 unsigned OldSize = AddrModeInsts.size();
2274 if (!MatchAddr(PromotedOperand, Depth) ||
2275 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2277 AddrMode = BackupAddrMode;
2278 AddrModeInsts.resize(OldSize);
2279 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2280 TPT.rollback(LastKnownGood);
2289 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2290 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2291 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2292 /// or intptr_t for the target.
2294 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2295 // Start a transaction at this point that we will rollback if the matching
2297 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2298 TPT.getRestorationPoint();
2299 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2300 // Fold in immediates if legal for the target.
2301 AddrMode.BaseOffs += CI->getSExtValue();
2302 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2304 AddrMode.BaseOffs -= CI->getSExtValue();
2305 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2306 // If this is a global variable, try to fold it into the addressing mode.
2307 if (!AddrMode.BaseGV) {
2308 AddrMode.BaseGV = GV;
2309 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2311 AddrMode.BaseGV = nullptr;
2313 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2314 ExtAddrMode BackupAddrMode = AddrMode;
2315 unsigned OldSize = AddrModeInsts.size();
2317 // Check to see if it is possible to fold this operation.
2318 bool MovedAway = false;
2319 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2320 // This instruction may have been move away. If so, there is nothing
2324 // Okay, it's possible to fold this. Check to see if it is actually
2325 // *profitable* to do so. We use a simple cost model to avoid increasing
2326 // register pressure too much.
2327 if (I->hasOneUse() ||
2328 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2329 AddrModeInsts.push_back(I);
2333 // It isn't profitable to do this, roll back.
2334 //cerr << "NOT FOLDING: " << *I;
2335 AddrMode = BackupAddrMode;
2336 AddrModeInsts.resize(OldSize);
2337 TPT.rollback(LastKnownGood);
2339 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2340 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2342 TPT.rollback(LastKnownGood);
2343 } else if (isa<ConstantPointerNull>(Addr)) {
2344 // Null pointer gets folded without affecting the addressing mode.
2348 // Worse case, the target should support [reg] addressing modes. :)
2349 if (!AddrMode.HasBaseReg) {
2350 AddrMode.HasBaseReg = true;
2351 AddrMode.BaseReg = Addr;
2352 // Still check for legality in case the target supports [imm] but not [i+r].
2353 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2355 AddrMode.HasBaseReg = false;
2356 AddrMode.BaseReg = nullptr;
2359 // If the base register is already taken, see if we can do [r+r].
2360 if (AddrMode.Scale == 0) {
2362 AddrMode.ScaledReg = Addr;
2363 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2366 AddrMode.ScaledReg = nullptr;
2369 TPT.rollback(LastKnownGood);
2373 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2374 /// inline asm call are due to memory operands. If so, return true, otherwise
2376 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2377 const TargetLowering &TLI) {
2378 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2379 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2380 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2382 // Compute the constraint code and ConstraintType to use.
2383 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2385 // If this asm operand is our Value*, and if it isn't an indirect memory
2386 // operand, we can't fold it!
2387 if (OpInfo.CallOperandVal == OpVal &&
2388 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2389 !OpInfo.isIndirect))
2396 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2397 /// memory use. If we find an obviously non-foldable instruction, return true.
2398 /// Add the ultimately found memory instructions to MemoryUses.
2399 static bool FindAllMemoryUses(Instruction *I,
2400 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2401 SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2402 const TargetLowering &TLI) {
2403 // If we already considered this instruction, we're done.
2404 if (!ConsideredInsts.insert(I).second)
2407 // If this is an obviously unfoldable instruction, bail out.
2408 if (!MightBeFoldableInst(I))
2411 // Loop over all the uses, recursively processing them.
2412 for (Use &U : I->uses()) {
2413 Instruction *UserI = cast<Instruction>(U.getUser());
2415 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2416 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2420 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2421 unsigned opNo = U.getOperandNo();
2422 if (opNo == 0) return true; // Storing addr, not into addr.
2423 MemoryUses.push_back(std::make_pair(SI, opNo));
2427 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2428 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2429 if (!IA) return true;
2431 // If this is a memory operand, we're cool, otherwise bail out.
2432 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2437 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2444 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2445 /// the use site that we're folding it into. If so, there is no cost to
2446 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2447 /// that we know are live at the instruction already.
2448 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2449 Value *KnownLive2) {
2450 // If Val is either of the known-live values, we know it is live!
2451 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2454 // All values other than instructions and arguments (e.g. constants) are live.
2455 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2457 // If Val is a constant sized alloca in the entry block, it is live, this is
2458 // true because it is just a reference to the stack/frame pointer, which is
2459 // live for the whole function.
2460 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2461 if (AI->isStaticAlloca())
2464 // Check to see if this value is already used in the memory instruction's
2465 // block. If so, it's already live into the block at the very least, so we
2466 // can reasonably fold it.
2467 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2470 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2471 /// mode of the machine to fold the specified instruction into a load or store
2472 /// that ultimately uses it. However, the specified instruction has multiple
2473 /// uses. Given this, it may actually increase register pressure to fold it
2474 /// into the load. For example, consider this code:
2478 /// use(Y) -> nonload/store
2482 /// In this case, Y has multiple uses, and can be folded into the load of Z
2483 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2484 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2485 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2486 /// number of computations either.
2488 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2489 /// X was live across 'load Z' for other reasons, we actually *would* want to
2490 /// fold the addressing mode in the Z case. This would make Y die earlier.
2491 bool AddressingModeMatcher::
2492 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2493 ExtAddrMode &AMAfter) {
2494 if (IgnoreProfitability) return true;
2496 // AMBefore is the addressing mode before this instruction was folded into it,
2497 // and AMAfter is the addressing mode after the instruction was folded. Get
2498 // the set of registers referenced by AMAfter and subtract out those
2499 // referenced by AMBefore: this is the set of values which folding in this
2500 // address extends the lifetime of.
2502 // Note that there are only two potential values being referenced here,
2503 // BaseReg and ScaleReg (global addresses are always available, as are any
2504 // folded immediates).
2505 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2507 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2508 // lifetime wasn't extended by adding this instruction.
2509 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2511 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2512 ScaledReg = nullptr;
2514 // If folding this instruction (and it's subexprs) didn't extend any live
2515 // ranges, we're ok with it.
2516 if (!BaseReg && !ScaledReg)
2519 // If all uses of this instruction are ultimately load/store/inlineasm's,
2520 // check to see if their addressing modes will include this instruction. If
2521 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2523 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2524 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2525 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2526 return false; // Has a non-memory, non-foldable use!
2528 // Now that we know that all uses of this instruction are part of a chain of
2529 // computation involving only operations that could theoretically be folded
2530 // into a memory use, loop over each of these uses and see if they could
2531 // *actually* fold the instruction.
2532 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2533 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2534 Instruction *User = MemoryUses[i].first;
2535 unsigned OpNo = MemoryUses[i].second;
2537 // Get the access type of this use. If the use isn't a pointer, we don't
2538 // know what it accesses.
2539 Value *Address = User->getOperand(OpNo);
2540 if (!Address->getType()->isPointerTy())
2542 Type *AddressAccessTy = Address->getType()->getPointerElementType();
2544 // Do a match against the root of this address, ignoring profitability. This
2545 // will tell us if the addressing mode for the memory operation will
2546 // *actually* cover the shared instruction.
2548 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2549 TPT.getRestorationPoint();
2550 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2551 MemoryInst, Result, InsertedTruncs,
2552 PromotedInsts, TPT);
2553 Matcher.IgnoreProfitability = true;
2554 bool Success = Matcher.MatchAddr(Address, 0);
2555 (void)Success; assert(Success && "Couldn't select *anything*?");
2557 // The match was to check the profitability, the changes made are not
2558 // part of the original matcher. Therefore, they should be dropped
2559 // otherwise the original matcher will not present the right state.
2560 TPT.rollback(LastKnownGood);
2562 // If the match didn't cover I, then it won't be shared by it.
2563 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2564 I) == MatchedAddrModeInsts.end())
2567 MatchedAddrModeInsts.clear();
2573 } // end anonymous namespace
2575 /// IsNonLocalValue - Return true if the specified values are defined in a
2576 /// different basic block than BB.
2577 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2578 if (Instruction *I = dyn_cast<Instruction>(V))
2579 return I->getParent() != BB;
2583 /// OptimizeMemoryInst - Load and Store Instructions often have
2584 /// addressing modes that can do significant amounts of computation. As such,
2585 /// instruction selection will try to get the load or store to do as much
2586 /// computation as possible for the program. The problem is that isel can only
2587 /// see within a single block. As such, we sink as much legal addressing mode
2588 /// stuff into the block as possible.
2590 /// This method is used to optimize both load/store and inline asms with memory
2592 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2596 // Try to collapse single-value PHI nodes. This is necessary to undo
2597 // unprofitable PRE transformations.
2598 SmallVector<Value*, 8> worklist;
2599 SmallPtrSet<Value*, 16> Visited;
2600 worklist.push_back(Addr);
2602 // Use a worklist to iteratively look through PHI nodes, and ensure that
2603 // the addressing mode obtained from the non-PHI roots of the graph
2605 Value *Consensus = nullptr;
2606 unsigned NumUsesConsensus = 0;
2607 bool IsNumUsesConsensusValid = false;
2608 SmallVector<Instruction*, 16> AddrModeInsts;
2609 ExtAddrMode AddrMode;
2610 TypePromotionTransaction TPT;
2611 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2612 TPT.getRestorationPoint();
2613 while (!worklist.empty()) {
2614 Value *V = worklist.back();
2615 worklist.pop_back();
2617 // Break use-def graph loops.
2618 if (!Visited.insert(V).second) {
2619 Consensus = nullptr;
2623 // For a PHI node, push all of its incoming values.
2624 if (PHINode *P = dyn_cast<PHINode>(V)) {
2625 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2626 worklist.push_back(P->getIncomingValue(i));
2630 // For non-PHIs, determine the addressing mode being computed.
2631 SmallVector<Instruction*, 16> NewAddrModeInsts;
2632 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2633 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2634 PromotedInsts, TPT);
2636 // This check is broken into two cases with very similar code to avoid using
2637 // getNumUses() as much as possible. Some values have a lot of uses, so
2638 // calling getNumUses() unconditionally caused a significant compile-time
2642 AddrMode = NewAddrMode;
2643 AddrModeInsts = NewAddrModeInsts;
2645 } else if (NewAddrMode == AddrMode) {
2646 if (!IsNumUsesConsensusValid) {
2647 NumUsesConsensus = Consensus->getNumUses();
2648 IsNumUsesConsensusValid = true;
2651 // Ensure that the obtained addressing mode is equivalent to that obtained
2652 // for all other roots of the PHI traversal. Also, when choosing one
2653 // such root as representative, select the one with the most uses in order
2654 // to keep the cost modeling heuristics in AddressingModeMatcher
2656 unsigned NumUses = V->getNumUses();
2657 if (NumUses > NumUsesConsensus) {
2659 NumUsesConsensus = NumUses;
2660 AddrModeInsts = NewAddrModeInsts;
2665 Consensus = nullptr;
2669 // If the addressing mode couldn't be determined, or if multiple different
2670 // ones were determined, bail out now.
2672 TPT.rollback(LastKnownGood);
2677 // Check to see if any of the instructions supersumed by this addr mode are
2678 // non-local to I's BB.
2679 bool AnyNonLocal = false;
2680 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2681 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2687 // If all the instructions matched are already in this BB, don't do anything.
2689 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
2693 // Insert this computation right after this user. Since our caller is
2694 // scanning from the top of the BB to the bottom, reuse of the expr are
2695 // guaranteed to happen later.
2696 IRBuilder<> Builder(MemoryInst);
2698 // Now that we determined the addressing expression we want to use and know
2699 // that we have to sink it into this block. Check to see if we have already
2700 // done this for some other load/store instr in this block. If so, reuse the
2702 Value *&SunkAddr = SunkAddrs[Addr];
2704 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2705 << *MemoryInst << "\n");
2706 if (SunkAddr->getType() != Addr->getType())
2707 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2708 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2709 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2710 // By default, we use the GEP-based method when AA is used later. This
2711 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2712 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2713 << *MemoryInst << "\n");
2714 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2715 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2717 // First, find the pointer.
2718 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2719 ResultPtr = AddrMode.BaseReg;
2720 AddrMode.BaseReg = nullptr;
2723 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2724 // We can't add more than one pointer together, nor can we scale a
2725 // pointer (both of which seem meaningless).
2726 if (ResultPtr || AddrMode.Scale != 1)
2729 ResultPtr = AddrMode.ScaledReg;
2733 if (AddrMode.BaseGV) {
2737 ResultPtr = AddrMode.BaseGV;
2740 // If the real base value actually came from an inttoptr, then the matcher
2741 // will look through it and provide only the integer value. In that case,
2743 if (!ResultPtr && AddrMode.BaseReg) {
2745 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2746 AddrMode.BaseReg = nullptr;
2747 } else if (!ResultPtr && AddrMode.Scale == 1) {
2749 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2754 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2755 SunkAddr = Constant::getNullValue(Addr->getType());
2756 } else if (!ResultPtr) {
2760 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2762 // Start with the base register. Do this first so that subsequent address
2763 // matching finds it last, which will prevent it from trying to match it
2764 // as the scaled value in case it happens to be a mul. That would be
2765 // problematic if we've sunk a different mul for the scale, because then
2766 // we'd end up sinking both muls.
2767 if (AddrMode.BaseReg) {
2768 Value *V = AddrMode.BaseReg;
2769 if (V->getType() != IntPtrTy)
2770 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2775 // Add the scale value.
2776 if (AddrMode.Scale) {
2777 Value *V = AddrMode.ScaledReg;
2778 if (V->getType() == IntPtrTy) {
2780 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2781 cast<IntegerType>(V->getType())->getBitWidth()) {
2782 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2784 // It is only safe to sign extend the BaseReg if we know that the math
2785 // required to create it did not overflow before we extend it. Since
2786 // the original IR value was tossed in favor of a constant back when
2787 // the AddrMode was created we need to bail out gracefully if widths
2788 // do not match instead of extending it.
2789 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2790 if (I && (ResultIndex != AddrMode.BaseReg))
2791 I->eraseFromParent();
2795 if (AddrMode.Scale != 1)
2796 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2799 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2804 // Add in the Base Offset if present.
2805 if (AddrMode.BaseOffs) {
2806 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2808 // We need to add this separately from the scale above to help with
2809 // SDAG consecutive load/store merging.
2810 if (ResultPtr->getType() != I8PtrTy)
2811 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2812 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2819 SunkAddr = ResultPtr;
2821 if (ResultPtr->getType() != I8PtrTy)
2822 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2823 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2826 if (SunkAddr->getType() != Addr->getType())
2827 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2830 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2831 << *MemoryInst << "\n");
2832 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2833 Value *Result = nullptr;
2835 // Start with the base register. Do this first so that subsequent address
2836 // matching finds it last, which will prevent it from trying to match it
2837 // as the scaled value in case it happens to be a mul. That would be
2838 // problematic if we've sunk a different mul for the scale, because then
2839 // we'd end up sinking both muls.
2840 if (AddrMode.BaseReg) {
2841 Value *V = AddrMode.BaseReg;
2842 if (V->getType()->isPointerTy())
2843 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2844 if (V->getType() != IntPtrTy)
2845 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2849 // Add the scale value.
2850 if (AddrMode.Scale) {
2851 Value *V = AddrMode.ScaledReg;
2852 if (V->getType() == IntPtrTy) {
2854 } else if (V->getType()->isPointerTy()) {
2855 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2856 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2857 cast<IntegerType>(V->getType())->getBitWidth()) {
2858 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2860 // It is only safe to sign extend the BaseReg if we know that the math
2861 // required to create it did not overflow before we extend it. Since
2862 // the original IR value was tossed in favor of a constant back when
2863 // the AddrMode was created we need to bail out gracefully if widths
2864 // do not match instead of extending it.
2865 Instruction *I = dyn_cast_or_null<Instruction>(Result);
2866 if (I && (Result != AddrMode.BaseReg))
2867 I->eraseFromParent();
2870 if (AddrMode.Scale != 1)
2871 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2874 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2879 // Add in the BaseGV if present.
2880 if (AddrMode.BaseGV) {
2881 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2883 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2888 // Add in the Base Offset if present.
2889 if (AddrMode.BaseOffs) {
2890 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2892 Result = Builder.CreateAdd(Result, V, "sunkaddr");
2898 SunkAddr = Constant::getNullValue(Addr->getType());
2900 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2903 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2905 // If we have no uses, recursively delete the value and all dead instructions
2907 if (Repl->use_empty()) {
2908 // This can cause recursive deletion, which can invalidate our iterator.
2909 // Use a WeakVH to hold onto it in case this happens.
2910 WeakVH IterHandle(CurInstIterator);
2911 BasicBlock *BB = CurInstIterator->getParent();
2913 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2915 if (IterHandle != CurInstIterator) {
2916 // If the iterator instruction was recursively deleted, start over at the
2917 // start of the block.
2918 CurInstIterator = BB->begin();
2926 /// OptimizeInlineAsmInst - If there are any memory operands, use
2927 /// OptimizeMemoryInst to sink their address computing into the block when
2928 /// possible / profitable.
2929 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2930 bool MadeChange = false;
2932 TargetLowering::AsmOperandInfoVector
2933 TargetConstraints = TLI->ParseConstraints(CS);
2935 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2936 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2938 // Compute the constraint code and ConstraintType to use.
2939 TLI->ComputeConstraintToUse(OpInfo, SDValue());
2941 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2942 OpInfo.isIndirect) {
2943 Value *OpVal = CS->getArgOperand(ArgNo++);
2944 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2945 } else if (OpInfo.Type == InlineAsm::isInput)
2952 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2953 /// basic block as the load, unless conditions are unfavorable. This allows
2954 /// SelectionDAG to fold the extend into the load.
2956 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2957 // Look for a load being extended.
2958 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2959 if (!LI) return false;
2961 // If they're already in the same block, there's nothing to do.
2962 if (LI->getParent() == I->getParent())
2965 // If the load has other users and the truncate is not free, this probably
2966 // isn't worthwhile.
2967 if (!LI->hasOneUse() &&
2968 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2969 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2970 !TLI->isTruncateFree(I->getType(), LI->getType()))
2973 // Check whether the target supports casts folded into loads.
2975 if (isa<ZExtInst>(I))
2976 LType = ISD::ZEXTLOAD;
2978 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2979 LType = ISD::SEXTLOAD;
2981 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2984 // Move the extend into the same block as the load, so that SelectionDAG
2986 I->removeFromParent();
2992 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2993 BasicBlock *DefBB = I->getParent();
2995 // If the result of a {s|z}ext and its source are both live out, rewrite all
2996 // other uses of the source with result of extension.
2997 Value *Src = I->getOperand(0);
2998 if (Src->hasOneUse())
3001 // Only do this xform if truncating is free.
3002 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3005 // Only safe to perform the optimization if the source is also defined in
3007 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3010 bool DefIsLiveOut = false;
3011 for (User *U : I->users()) {
3012 Instruction *UI = cast<Instruction>(U);
3014 // Figure out which BB this ext is used in.
3015 BasicBlock *UserBB = UI->getParent();
3016 if (UserBB == DefBB) continue;
3017 DefIsLiveOut = true;
3023 // Make sure none of the uses are PHI nodes.
3024 for (User *U : Src->users()) {
3025 Instruction *UI = cast<Instruction>(U);
3026 BasicBlock *UserBB = UI->getParent();
3027 if (UserBB == DefBB) continue;
3028 // Be conservative. We don't want this xform to end up introducing
3029 // reloads just before load / store instructions.
3030 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3034 // InsertedTruncs - Only insert one trunc in each block once.
3035 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3037 bool MadeChange = false;
3038 for (Use &U : Src->uses()) {
3039 Instruction *User = cast<Instruction>(U.getUser());
3041 // Figure out which BB this ext is used in.
3042 BasicBlock *UserBB = User->getParent();
3043 if (UserBB == DefBB) continue;
3045 // Both src and def are live in this block. Rewrite the use.
3046 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3048 if (!InsertedTrunc) {
3049 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3050 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3051 InsertedTruncsSet.insert(InsertedTrunc);
3054 // Replace a use of the {s|z}ext source with a use of the result.
3063 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3064 /// turned into an explicit branch.
3065 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3066 // FIXME: This should use the same heuristics as IfConversion to determine
3067 // whether a select is better represented as a branch. This requires that
3068 // branch probability metadata is preserved for the select, which is not the
3071 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3073 // If the branch is predicted right, an out of order CPU can avoid blocking on
3074 // the compare. Emit cmovs on compares with a memory operand as branches to
3075 // avoid stalls on the load from memory. If the compare has more than one use
3076 // there's probably another cmov or setcc around so it's not worth emitting a
3081 Value *CmpOp0 = Cmp->getOperand(0);
3082 Value *CmpOp1 = Cmp->getOperand(1);
3084 // We check that the memory operand has one use to avoid uses of the loaded
3085 // value directly after the compare, making branches unprofitable.
3086 return Cmp->hasOneUse() &&
3087 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3088 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3092 /// If we have a SelectInst that will likely profit from branch prediction,
3093 /// turn it into a branch.
3094 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3095 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3097 // Can we convert the 'select' to CF ?
3098 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3101 TargetLowering::SelectSupportKind SelectKind;
3103 SelectKind = TargetLowering::VectorMaskSelect;
3104 else if (SI->getType()->isVectorTy())
3105 SelectKind = TargetLowering::ScalarCondVectorVal;
3107 SelectKind = TargetLowering::ScalarValSelect;
3109 // Do we have efficient codegen support for this kind of 'selects' ?
3110 if (TLI->isSelectSupported(SelectKind)) {
3111 // We have efficient codegen support for the select instruction.
3112 // Check if it is profitable to keep this 'select'.
3113 if (!TLI->isPredictableSelectExpensive() ||
3114 !isFormingBranchFromSelectProfitable(SI))
3120 // First, we split the block containing the select into 2 blocks.
3121 BasicBlock *StartBlock = SI->getParent();
3122 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3123 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3125 // Create a new block serving as the landing pad for the branch.
3126 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3127 NextBlock->getParent(), NextBlock);
3129 // Move the unconditional branch from the block with the select in it into our
3130 // landing pad block.
3131 StartBlock->getTerminator()->eraseFromParent();
3132 BranchInst::Create(NextBlock, SmallBlock);
3134 // Insert the real conditional branch based on the original condition.
3135 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3137 // The select itself is replaced with a PHI Node.
3138 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3140 PN->addIncoming(SI->getTrueValue(), StartBlock);
3141 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3142 SI->replaceAllUsesWith(PN);
3143 SI->eraseFromParent();
3145 // Instruct OptimizeBlock to skip to the next block.
3146 CurInstIterator = StartBlock->end();
3147 ++NumSelectsExpanded;
3151 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3152 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3154 for (unsigned i = 0; i < Mask.size(); ++i) {
3155 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3157 SplatElem = Mask[i];
3163 /// Some targets have expensive vector shifts if the lanes aren't all the same
3164 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3165 /// it's often worth sinking a shufflevector splat down to its use so that
3166 /// codegen can spot all lanes are identical.
3167 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3168 BasicBlock *DefBB = SVI->getParent();
3170 // Only do this xform if variable vector shifts are particularly expensive.
3171 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3174 // We only expect better codegen by sinking a shuffle if we can recognise a
3176 if (!isBroadcastShuffle(SVI))
3179 // InsertedShuffles - Only insert a shuffle in each block once.
3180 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3182 bool MadeChange = false;
3183 for (User *U : SVI->users()) {
3184 Instruction *UI = cast<Instruction>(U);
3186 // Figure out which BB this ext is used in.
3187 BasicBlock *UserBB = UI->getParent();
3188 if (UserBB == DefBB) continue;
3190 // For now only apply this when the splat is used by a shift instruction.
3191 if (!UI->isShift()) continue;
3193 // Everything checks out, sink the shuffle if the user's block doesn't
3194 // already have a copy.
3195 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3197 if (!InsertedShuffle) {
3198 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3199 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3201 SVI->getOperand(2), "", InsertPt);
3204 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3208 // If we removed all uses, nuke the shuffle.
3209 if (SVI->use_empty()) {
3210 SVI->eraseFromParent();
3218 /// \brief Helper class to promote a scalar operation to a vector one.
3219 /// This class is used to move downward extractelement transition.
3221 /// a = vector_op <2 x i32>
3222 /// b = extractelement <2 x i32> a, i32 0
3227 /// a = vector_op <2 x i32>
3228 /// c = vector_op a (equivalent to scalar_op on the related lane)
3229 /// * d = extractelement <2 x i32> c, i32 0
3231 /// Assuming both extractelement and store can be combine, we get rid of the
3233 class VectorPromoteHelper {
3234 /// Used to perform some checks on the legality of vector operations.
3235 const TargetLowering &TLI;
3237 /// Used to estimated the cost of the promoted chain.
3238 const TargetTransformInfo &TTI;
3240 /// The transition being moved downwards.
3241 Instruction *Transition;
3242 /// The sequence of instructions to be promoted.
3243 SmallVector<Instruction *, 4> InstsToBePromoted;
3244 /// Cost of combining a store and an extract.
3245 unsigned StoreExtractCombineCost;
3246 /// Instruction that will be combined with the transition.
3247 Instruction *CombineInst;
3249 /// \brief The instruction that represents the current end of the transition.
3250 /// Since we are faking the promotion until we reach the end of the chain
3251 /// of computation, we need a way to get the current end of the transition.
3252 Instruction *getEndOfTransition() const {
3253 if (InstsToBePromoted.empty())
3255 return InstsToBePromoted.back();
3258 /// \brief Return the index of the original value in the transition.
3259 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3260 /// c, is at index 0.
3261 unsigned getTransitionOriginalValueIdx() const {
3262 assert(isa<ExtractElementInst>(Transition) &&
3263 "Other kind of transitions are not supported yet");
3267 /// \brief Return the index of the index in the transition.
3268 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3270 unsigned getTransitionIdx() const {
3271 assert(isa<ExtractElementInst>(Transition) &&
3272 "Other kind of transitions are not supported yet");
3276 /// \brief Get the type of the transition.
3277 /// This is the type of the original value.
3278 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3279 /// transition is <2 x i32>.
3280 Type *getTransitionType() const {
3281 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3284 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3285 /// I.e., we have the following sequence:
3286 /// Def = Transition <ty1> a to <ty2>
3287 /// b = ToBePromoted <ty2> Def, ...
3289 /// b = ToBePromoted <ty1> a, ...
3290 /// Def = Transition <ty1> ToBePromoted to <ty2>
3291 void promoteImpl(Instruction *ToBePromoted);
3293 /// \brief Check whether or not it is profitable to promote all the
3294 /// instructions enqueued to be promoted.
3295 bool isProfitableToPromote() {
3296 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3297 unsigned Index = isa<ConstantInt>(ValIdx)
3298 ? cast<ConstantInt>(ValIdx)->getZExtValue()
3300 Type *PromotedType = getTransitionType();
3302 StoreInst *ST = cast<StoreInst>(CombineInst);
3303 unsigned AS = ST->getPointerAddressSpace();
3304 unsigned Align = ST->getAlignment();
3305 // Check if this store is supported.
3306 if (!TLI.allowsMisalignedMemoryAccesses(
3307 TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
3308 // If this is not supported, there is no way we can combine
3309 // the extract with the store.
3313 // The scalar chain of computation has to pay for the transition
3314 // scalar to vector.
3315 // The vector chain has to account for the combining cost.
3316 uint64_t ScalarCost =
3317 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3318 uint64_t VectorCost = StoreExtractCombineCost;
3319 for (const auto &Inst : InstsToBePromoted) {
3320 // Compute the cost.
3321 // By construction, all instructions being promoted are arithmetic ones.
3322 // Moreover, one argument is a constant that can be viewed as a splat
3324 Value *Arg0 = Inst->getOperand(0);
3325 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3326 isa<ConstantFP>(Arg0);
3327 TargetTransformInfo::OperandValueKind Arg0OVK =
3328 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3329 : TargetTransformInfo::OK_AnyValue;
3330 TargetTransformInfo::OperandValueKind Arg1OVK =
3331 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3332 : TargetTransformInfo::OK_AnyValue;
3333 ScalarCost += TTI.getArithmeticInstrCost(
3334 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3335 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3338 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3339 << ScalarCost << "\nVector: " << VectorCost << '\n');
3340 return ScalarCost > VectorCost;
3343 /// \brief Generate a constant vector with \p Val with the same
3344 /// number of elements as the transition.
3345 /// \p UseSplat defines whether or not \p Val should be replicated
3346 /// accross the whole vector.
3347 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3348 /// otherwise we generate a vector with as many undef as possible:
3349 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3350 /// used at the index of the extract.
3351 Value *getConstantVector(Constant *Val, bool UseSplat) const {
3352 unsigned ExtractIdx = UINT_MAX;
3354 // If we cannot determine where the constant must be, we have to
3355 // use a splat constant.
3356 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3357 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3358 ExtractIdx = CstVal->getSExtValue();
3363 unsigned End = getTransitionType()->getVectorNumElements();
3365 return ConstantVector::getSplat(End, Val);
3367 SmallVector<Constant *, 4> ConstVec;
3368 UndefValue *UndefVal = UndefValue::get(Val->getType());
3369 for (unsigned Idx = 0; Idx != End; ++Idx) {
3370 if (Idx == ExtractIdx)
3371 ConstVec.push_back(Val);
3373 ConstVec.push_back(UndefVal);
3375 return ConstantVector::get(ConstVec);
3378 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3379 /// in \p Use can trigger undefined behavior.
3380 static bool canCauseUndefinedBehavior(const Instruction *Use,
3381 unsigned OperandIdx) {
3382 // This is not safe to introduce undef when the operand is on
3383 // the right hand side of a division-like instruction.
3384 if (OperandIdx != 1)
3386 switch (Use->getOpcode()) {
3389 case Instruction::SDiv:
3390 case Instruction::UDiv:
3391 case Instruction::SRem:
3392 case Instruction::URem:
3394 case Instruction::FDiv:
3395 case Instruction::FRem:
3396 return !Use->hasNoNaNs();
3398 llvm_unreachable(nullptr);
3402 VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3403 Instruction *Transition, unsigned CombineCost)
3404 : TLI(TLI), TTI(TTI), Transition(Transition),
3405 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3406 assert(Transition && "Do not know how to promote null");
3409 /// \brief Check if we can promote \p ToBePromoted to \p Type.
3410 bool canPromote(const Instruction *ToBePromoted) const {
3411 // We could support CastInst too.
3412 return isa<BinaryOperator>(ToBePromoted);
3415 /// \brief Check if it is profitable to promote \p ToBePromoted
3416 /// by moving downward the transition through.
3417 bool shouldPromote(const Instruction *ToBePromoted) const {
3418 // Promote only if all the operands can be statically expanded.
3419 // Indeed, we do not want to introduce any new kind of transitions.
3420 for (const Use &U : ToBePromoted->operands()) {
3421 const Value *Val = U.get();
3422 if (Val == getEndOfTransition()) {
3423 // If the use is a division and the transition is on the rhs,
3424 // we cannot promote the operation, otherwise we may create a
3425 // division by zero.
3426 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3430 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3431 !isa<ConstantFP>(Val))
3434 // Check that the resulting operation is legal.
3435 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3438 return StressStoreExtract ||
3439 TLI.isOperationLegalOrCustom(
3440 ISDOpcode, TLI.getValueType(getTransitionType(), true));
3443 /// \brief Check whether or not \p Use can be combined
3444 /// with the transition.
3445 /// I.e., is it possible to do Use(Transition) => AnotherUse?
3446 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3448 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3449 void enqueueForPromotion(Instruction *ToBePromoted) {
3450 InstsToBePromoted.push_back(ToBePromoted);
3453 /// \brief Set the instruction that will be combined with the transition.
3454 void recordCombineInstruction(Instruction *ToBeCombined) {
3455 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3456 CombineInst = ToBeCombined;
3459 /// \brief Promote all the instructions enqueued for promotion if it is
3461 /// \return True if the promotion happened, false otherwise.
3463 // Check if there is something to promote.
3464 // Right now, if we do not have anything to combine with,
3465 // we assume the promotion is not profitable.
3466 if (InstsToBePromoted.empty() || !CombineInst)
3470 if (!StressStoreExtract && !isProfitableToPromote())
3474 for (auto &ToBePromoted : InstsToBePromoted)
3475 promoteImpl(ToBePromoted);
3476 InstsToBePromoted.clear();
3480 } // End of anonymous namespace.
3482 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3483 // At this point, we know that all the operands of ToBePromoted but Def
3484 // can be statically promoted.
3485 // For Def, we need to use its parameter in ToBePromoted:
3486 // b = ToBePromoted ty1 a
3487 // Def = Transition ty1 b to ty2
3488 // Move the transition down.
3489 // 1. Replace all uses of the promoted operation by the transition.
3490 // = ... b => = ... Def.
3491 assert(ToBePromoted->getType() == Transition->getType() &&
3492 "The type of the result of the transition does not match "
3494 ToBePromoted->replaceAllUsesWith(Transition);
3495 // 2. Update the type of the uses.
3496 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3497 Type *TransitionTy = getTransitionType();
3498 ToBePromoted->mutateType(TransitionTy);
3499 // 3. Update all the operands of the promoted operation with promoted
3501 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3502 for (Use &U : ToBePromoted->operands()) {
3503 Value *Val = U.get();
3504 Value *NewVal = nullptr;
3505 if (Val == Transition)
3506 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3507 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3508 isa<ConstantFP>(Val)) {
3509 // Use a splat constant if it is not safe to use undef.
3510 NewVal = getConstantVector(
3511 cast<Constant>(Val),
3512 isa<UndefValue>(Val) ||
3513 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3515 assert(0 && "Did you modified shouldPromote and forgot to update this?");
3516 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3518 Transition->removeFromParent();
3519 Transition->insertAfter(ToBePromoted);
3520 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3523 /// Some targets can do store(extractelement) with one instruction.
3524 /// Try to push the extractelement towards the stores when the target
3525 /// has this feature and this is profitable.
3526 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3527 unsigned CombineCost = UINT_MAX;
3528 if (DisableStoreExtract || !TLI ||
3529 (!StressStoreExtract &&
3530 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3531 Inst->getOperand(1), CombineCost)))
3534 // At this point we know that Inst is a vector to scalar transition.
3535 // Try to move it down the def-use chain, until:
3536 // - We can combine the transition with its single use
3537 // => we got rid of the transition.
3538 // - We escape the current basic block
3539 // => we would need to check that we are moving it at a cheaper place and
3540 // we do not do that for now.
3541 BasicBlock *Parent = Inst->getParent();
3542 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3543 VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3544 // If the transition has more than one use, assume this is not going to be
3546 while (Inst->hasOneUse()) {
3547 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3548 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3550 if (ToBePromoted->getParent() != Parent) {
3551 DEBUG(dbgs() << "Instruction to promote is in a different block ("
3552 << ToBePromoted->getParent()->getName()
3553 << ") than the transition (" << Parent->getName() << ").\n");
3557 if (VPH.canCombine(ToBePromoted)) {
3558 DEBUG(dbgs() << "Assume " << *Inst << '\n'
3559 << "will be combined with: " << *ToBePromoted << '\n');
3560 VPH.recordCombineInstruction(ToBePromoted);
3561 bool Changed = VPH.promote();
3562 NumStoreExtractExposed += Changed;
3566 DEBUG(dbgs() << "Try promoting.\n");
3567 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3570 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3572 VPH.enqueueForPromotion(ToBePromoted);
3573 Inst = ToBePromoted;
3578 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3579 if (PHINode *P = dyn_cast<PHINode>(I)) {
3580 // It is possible for very late stage optimizations (such as SimplifyCFG)
3581 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3582 // trivial PHI, go ahead and zap it here.
3583 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3585 P->replaceAllUsesWith(V);
3586 P->eraseFromParent();
3593 if (CastInst *CI = dyn_cast<CastInst>(I)) {
3594 // If the source of the cast is a constant, then this should have
3595 // already been constant folded. The only reason NOT to constant fold
3596 // it is if something (e.g. LSR) was careful to place the constant
3597 // evaluation in a block other than then one that uses it (e.g. to hoist
3598 // the address of globals out of a loop). If this is the case, we don't
3599 // want to forward-subst the cast.
3600 if (isa<Constant>(CI->getOperand(0)))
3603 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3606 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3607 /// Sink a zext or sext into its user blocks if the target type doesn't
3608 /// fit in one register
3609 if (TLI && TLI->getTypeAction(CI->getContext(),
3610 TLI->getValueType(CI->getType())) ==
3611 TargetLowering::TypeExpandInteger) {
3612 return SinkCast(CI);
3614 bool MadeChange = MoveExtToFormExtLoad(I);
3615 return MadeChange | OptimizeExtUses(I);
3621 if (CmpInst *CI = dyn_cast<CmpInst>(I))
3622 if (!TLI || !TLI->hasMultipleConditionRegisters())
3623 return OptimizeCmpExpression(CI);
3625 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3627 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3631 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3633 return OptimizeMemoryInst(I, SI->getOperand(1),
3634 SI->getOperand(0)->getType());
3638 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3640 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3641 BinOp->getOpcode() == Instruction::LShr)) {
3642 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3643 if (TLI && CI && TLI->hasExtractBitsInsn())
3644 return OptimizeExtractBits(BinOp, CI, *TLI);
3649 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3650 if (GEPI->hasAllZeroIndices()) {
3651 /// The GEP operand must be a pointer, so must its result -> BitCast
3652 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3653 GEPI->getName(), GEPI);
3654 GEPI->replaceAllUsesWith(NC);
3655 GEPI->eraseFromParent();
3663 if (CallInst *CI = dyn_cast<CallInst>(I))
3664 return OptimizeCallInst(CI);
3666 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3667 return OptimizeSelectInst(SI);
3669 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3670 return OptimizeShuffleVectorInst(SVI);
3672 if (isa<ExtractElementInst>(I))
3673 return OptimizeExtractElementInst(I);
3678 // In this pass we look for GEP and cast instructions that are used
3679 // across basic blocks and rewrite them to improve basic-block-at-a-time
3681 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3683 bool MadeChange = false;
3685 CurInstIterator = BB.begin();
3686 while (CurInstIterator != BB.end())
3687 MadeChange |= OptimizeInst(CurInstIterator++);
3689 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3694 // llvm.dbg.value is far away from the value then iSel may not be able
3695 // handle it properly. iSel will drop llvm.dbg.value if it can not
3696 // find a node corresponding to the value.
3697 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3698 bool MadeChange = false;
3699 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3700 Instruction *PrevNonDbgInst = nullptr;
3701 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3702 Instruction *Insn = BI; ++BI;
3703 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3704 // Leave dbg.values that refer to an alloca alone. These
3705 // instrinsics describe the address of a variable (= the alloca)
3706 // being taken. They should not be moved next to the alloca
3707 // (and to the beginning of the scope), but rather stay close to
3708 // where said address is used.
3709 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3710 PrevNonDbgInst = Insn;
3714 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3715 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3716 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3717 DVI->removeFromParent();
3718 if (isa<PHINode>(VI))
3719 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3721 DVI->insertAfter(VI);
3730 // If there is a sequence that branches based on comparing a single bit
3731 // against zero that can be combined into a single instruction, and the
3732 // target supports folding these into a single instruction, sink the
3733 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3734 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3736 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3737 if (!EnableAndCmpSinking)
3739 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3741 bool MadeChange = false;
3742 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3743 BasicBlock *BB = I++;
3745 // Does this BB end with the following?
3746 // %andVal = and %val, #single-bit-set
3747 // %icmpVal = icmp %andResult, 0
3748 // br i1 %cmpVal label %dest1, label %dest2"
3749 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3750 if (!Brcc || !Brcc->isConditional())
3752 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3753 if (!Cmp || Cmp->getParent() != BB)
3755 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3756 if (!Zero || !Zero->isZero())
3758 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3759 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3761 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3762 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3764 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3766 // Push the "and; icmp" for any users that are conditional branches.
3767 // Since there can only be one branch use per BB, we don't need to keep
3768 // track of which BBs we insert into.
3769 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3773 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3775 if (!BrccUser || !BrccUser->isConditional())
3777 BasicBlock *UserBB = BrccUser->getParent();
3778 if (UserBB == BB) continue;
3779 DEBUG(dbgs() << "found Brcc use\n");
3781 // Sink the "and; icmp" to use.
3783 BinaryOperator *NewAnd =
3784 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3787 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3791 DEBUG(BrccUser->getParent()->dump());