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/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Statepoint.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/IR/ValueMap.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/BuildLibCalls.h"
47 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
51 using namespace llvm::PatternMatch;
53 #define DEBUG_TYPE "codegenprepare"
55 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
56 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
58 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
60 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
62 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
64 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
67 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
68 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
69 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
70 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
72 static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
80 static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
84 static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
88 static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
92 static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
96 static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
100 static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
105 static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
111 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
115 TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
117 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
118 class TypePromotionTransaction;
120 class CodeGenPrepare : public FunctionPass {
121 /// TLI - Keep a pointer of a TargetLowering to consult for determining
122 /// transformation profitability.
123 const TargetMachine *TM;
124 const TargetLowering *TLI;
125 const TargetTransformInfo *TTI;
126 const TargetLibraryInfo *TLInfo;
128 /// CurInstIterator - As we scan instructions optimizing them, this is the
129 /// next instruction to optimize. Xforms that can invalidate this should
131 BasicBlock::iterator CurInstIterator;
133 /// Keeps track of non-local addresses that have been sunk into a block.
134 /// This allows us to avoid inserting duplicate code for blocks with
135 /// multiple load/stores of the same address.
136 ValueMap<Value*, Value*> SunkAddrs;
138 /// Keeps track of all instructions inserted for the current function.
139 SetOfInstrs InsertedInsts;
140 /// Keeps track of the type of the related instruction before their
141 /// promotion for the current function.
142 InstrToOrigTy PromotedInsts;
144 /// ModifiedDT - If CFG is modified in anyway.
147 /// OptSize - True if optimizing for size.
150 /// DataLayout for the Function being processed.
151 const DataLayout *DL;
154 static char ID; // Pass identification, replacement for typeid
155 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
156 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
157 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
159 bool runOnFunction(Function &F) override;
161 const char *getPassName() const override { return "CodeGen Prepare"; }
163 void getAnalysisUsage(AnalysisUsage &AU) const override {
164 AU.addPreserved<DominatorTreeWrapperPass>();
165 AU.addRequired<TargetLibraryInfoWrapperPass>();
166 AU.addRequired<TargetTransformInfoWrapperPass>();
170 bool EliminateFallThrough(Function &F);
171 bool EliminateMostlyEmptyBlocks(Function &F);
172 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
173 void EliminateMostlyEmptyBlock(BasicBlock *BB);
174 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
175 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
176 bool OptimizeMemoryInst(Instruction *I, Value *Addr,
177 Type *AccessTy, unsigned AS);
178 bool OptimizeInlineAsmInst(CallInst *CS);
179 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
180 bool MoveExtToFormExtLoad(Instruction *&I);
181 bool OptimizeExtUses(Instruction *I);
182 bool OptimizeSelectInst(SelectInst *SI);
183 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
184 bool OptimizeExtractElementInst(Instruction *Inst);
185 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
186 bool PlaceDbgValues(Function &F);
187 bool sinkAndCmp(Function &F);
188 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
190 const SmallVectorImpl<Instruction *> &Exts,
191 unsigned CreatedInstCost);
192 bool splitBranchCondition(Function &F);
193 bool simplifyOffsetableRelocate(Instruction &I);
197 char CodeGenPrepare::ID = 0;
198 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
199 "Optimize for code generation", false, false)
201 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
202 return new CodeGenPrepare(TM);
205 bool CodeGenPrepare::runOnFunction(Function &F) {
206 if (skipOptnoneFunction(F))
209 DL = &F.getParent()->getDataLayout();
211 bool EverMadeChange = false;
212 // Clear per function information.
213 InsertedInsts.clear();
214 PromotedInsts.clear();
218 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
219 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
220 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
221 OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
223 /// This optimization identifies DIV instructions that can be
224 /// profitably bypassed and carried out with a shorter, faster divide.
225 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
226 const DenseMap<unsigned int, unsigned int> &BypassWidths =
227 TLI->getBypassSlowDivWidths();
228 for (Function::iterator I = F.begin(); I != F.end(); I++)
229 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
232 // Eliminate blocks that contain only PHI nodes and an
233 // unconditional branch.
234 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
236 // llvm.dbg.value is far away from the value then iSel may not be able
237 // handle it properly. iSel will drop llvm.dbg.value if it can not
238 // find a node corresponding to the value.
239 EverMadeChange |= PlaceDbgValues(F);
241 // If there is a mask, compare against zero, and branch that can be combined
242 // into a single target instruction, push the mask and compare into branch
243 // users. Do this before OptimizeBlock -> OptimizeInst ->
244 // OptimizeCmpExpression, which perturbs the pattern being searched for.
245 if (!DisableBranchOpts) {
246 EverMadeChange |= sinkAndCmp(F);
247 EverMadeChange |= splitBranchCondition(F);
250 bool MadeChange = true;
253 for (Function::iterator I = F.begin(); I != F.end(); ) {
254 BasicBlock *BB = I++;
255 bool ModifiedDTOnIteration = false;
256 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
258 // Restart BB iteration if the dominator tree of the Function was changed
259 if (ModifiedDTOnIteration)
262 EverMadeChange |= MadeChange;
267 if (!DisableBranchOpts) {
269 SmallPtrSet<BasicBlock*, 8> WorkList;
270 for (BasicBlock &BB : F) {
271 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
272 MadeChange |= ConstantFoldTerminator(&BB, true);
273 if (!MadeChange) continue;
275 for (SmallVectorImpl<BasicBlock*>::iterator
276 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
277 if (pred_begin(*II) == pred_end(*II))
278 WorkList.insert(*II);
281 // Delete the dead blocks and any of their dead successors.
282 MadeChange |= !WorkList.empty();
283 while (!WorkList.empty()) {
284 BasicBlock *BB = *WorkList.begin();
286 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
290 for (SmallVectorImpl<BasicBlock*>::iterator
291 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
292 if (pred_begin(*II) == pred_end(*II))
293 WorkList.insert(*II);
296 // Merge pairs of basic blocks with unconditional branches, connected by
298 if (EverMadeChange || MadeChange)
299 MadeChange |= EliminateFallThrough(F);
301 EverMadeChange |= MadeChange;
304 if (!DisableGCOpts) {
305 SmallVector<Instruction *, 2> Statepoints;
306 for (BasicBlock &BB : F)
307 for (Instruction &I : BB)
309 Statepoints.push_back(&I);
310 for (auto &I : Statepoints)
311 EverMadeChange |= simplifyOffsetableRelocate(*I);
314 return EverMadeChange;
317 /// EliminateFallThrough - Merge basic blocks which are connected
318 /// by a single edge, where one of the basic blocks has a single successor
319 /// pointing to the other basic block, which has a single predecessor.
320 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
321 bool Changed = false;
322 // Scan all of the blocks in the function, except for the entry block.
323 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
324 BasicBlock *BB = I++;
325 // If the destination block has a single pred, then this is a trivial
326 // edge, just collapse it.
327 BasicBlock *SinglePred = BB->getSinglePredecessor();
329 // Don't merge if BB's address is taken.
330 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
332 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
333 if (Term && !Term->isConditional()) {
335 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
336 // Remember if SinglePred was the entry block of the function.
337 // If so, we will need to move BB back to the entry position.
338 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
339 MergeBasicBlockIntoOnlyPred(BB, nullptr);
341 if (isEntry && BB != &BB->getParent()->getEntryBlock())
342 BB->moveBefore(&BB->getParent()->getEntryBlock());
344 // We have erased a block. Update the iterator.
351 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
352 /// debug info directives, and an unconditional branch. Passes before isel
353 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
354 /// isel. Start by eliminating these blocks so we can split them the way we
356 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
357 bool MadeChange = false;
358 // Note that this intentionally skips the entry block.
359 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
360 BasicBlock *BB = I++;
362 // If this block doesn't end with an uncond branch, ignore it.
363 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
364 if (!BI || !BI->isUnconditional())
367 // If the instruction before the branch (skipping debug info) isn't a phi
368 // node, then other stuff is happening here.
369 BasicBlock::iterator BBI = BI;
370 if (BBI != BB->begin()) {
372 while (isa<DbgInfoIntrinsic>(BBI)) {
373 if (BBI == BB->begin())
377 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
381 // Do not break infinite loops.
382 BasicBlock *DestBB = BI->getSuccessor(0);
386 if (!CanMergeBlocks(BB, DestBB))
389 EliminateMostlyEmptyBlock(BB);
395 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
396 /// single uncond branch between them, and BB contains no other non-phi
398 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
399 const BasicBlock *DestBB) const {
400 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
401 // the successor. If there are more complex condition (e.g. preheaders),
402 // don't mess around with them.
403 BasicBlock::const_iterator BBI = BB->begin();
404 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
405 for (const User *U : PN->users()) {
406 const Instruction *UI = cast<Instruction>(U);
407 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
409 // If User is inside DestBB block and it is a PHINode then check
410 // incoming value. If incoming value is not from BB then this is
411 // a complex condition (e.g. preheaders) we want to avoid here.
412 if (UI->getParent() == DestBB) {
413 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
414 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
415 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
416 if (Insn && Insn->getParent() == BB &&
417 Insn->getParent() != UPN->getIncomingBlock(I))
424 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
425 // and DestBB may have conflicting incoming values for the block. If so, we
426 // can't merge the block.
427 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
428 if (!DestBBPN) return true; // no conflict.
430 // Collect the preds of BB.
431 SmallPtrSet<const BasicBlock*, 16> BBPreds;
432 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
433 // It is faster to get preds from a PHI than with pred_iterator.
434 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
435 BBPreds.insert(BBPN->getIncomingBlock(i));
437 BBPreds.insert(pred_begin(BB), pred_end(BB));
440 // Walk the preds of DestBB.
441 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
442 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
443 if (BBPreds.count(Pred)) { // Common predecessor?
444 BBI = DestBB->begin();
445 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
446 const Value *V1 = PN->getIncomingValueForBlock(Pred);
447 const Value *V2 = PN->getIncomingValueForBlock(BB);
449 // If V2 is a phi node in BB, look up what the mapped value will be.
450 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
451 if (V2PN->getParent() == BB)
452 V2 = V2PN->getIncomingValueForBlock(Pred);
454 // If there is a conflict, bail out.
455 if (V1 != V2) return false;
464 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
465 /// an unconditional branch in it.
466 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
467 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
468 BasicBlock *DestBB = BI->getSuccessor(0);
470 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
472 // If the destination block has a single pred, then this is a trivial edge,
474 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
475 if (SinglePred != DestBB) {
476 // Remember if SinglePred was the entry block of the function. If so, we
477 // will need to move BB back to the entry position.
478 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
479 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
481 if (isEntry && BB != &BB->getParent()->getEntryBlock())
482 BB->moveBefore(&BB->getParent()->getEntryBlock());
484 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
489 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
490 // to handle the new incoming edges it is about to have.
492 for (BasicBlock::iterator BBI = DestBB->begin();
493 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
494 // Remove the incoming value for BB, and remember it.
495 Value *InVal = PN->removeIncomingValue(BB, false);
497 // Two options: either the InVal is a phi node defined in BB or it is some
498 // value that dominates BB.
499 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
500 if (InValPhi && InValPhi->getParent() == BB) {
501 // Add all of the input values of the input PHI as inputs of this phi.
502 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
503 PN->addIncoming(InValPhi->getIncomingValue(i),
504 InValPhi->getIncomingBlock(i));
506 // Otherwise, add one instance of the dominating value for each edge that
507 // we will be adding.
508 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
509 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
510 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
512 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
513 PN->addIncoming(InVal, *PI);
518 // The PHIs are now updated, change everything that refers to BB to use
519 // DestBB and remove BB.
520 BB->replaceAllUsesWith(DestBB);
521 BB->eraseFromParent();
524 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
527 // Computes a map of base pointer relocation instructions to corresponding
528 // derived pointer relocation instructions given a vector of all relocate calls
529 static void computeBaseDerivedRelocateMap(
530 const SmallVectorImpl<User *> &AllRelocateCalls,
531 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
533 // Collect information in two maps: one primarily for locating the base object
534 // while filling the second map; the second map is the final structure holding
535 // a mapping between Base and corresponding Derived relocate calls
536 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
537 for (auto &U : AllRelocateCalls) {
538 GCRelocateOperands ThisRelocate(U);
539 IntrinsicInst *I = cast<IntrinsicInst>(U);
540 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
541 ThisRelocate.getDerivedPtrIndex());
542 RelocateIdxMap.insert(std::make_pair(K, I));
544 for (auto &Item : RelocateIdxMap) {
545 std::pair<unsigned, unsigned> Key = Item.first;
546 if (Key.first == Key.second)
547 // Base relocation: nothing to insert
550 IntrinsicInst *I = Item.second;
551 auto BaseKey = std::make_pair(Key.first, Key.first);
553 // We're iterating over RelocateIdxMap so we cannot modify it.
554 auto MaybeBase = RelocateIdxMap.find(BaseKey);
555 if (MaybeBase == RelocateIdxMap.end())
556 // TODO: We might want to insert a new base object relocate and gep off
557 // that, if there are enough derived object relocates.
560 RelocateInstMap[MaybeBase->second].push_back(I);
564 // Accepts a GEP and extracts the operands into a vector provided they're all
565 // small integer constants
566 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
567 SmallVectorImpl<Value *> &OffsetV) {
568 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
569 // Only accept small constant integer operands
570 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
571 if (!Op || Op->getZExtValue() > 20)
575 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
576 OffsetV.push_back(GEP->getOperand(i));
580 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
581 // replace, computes a replacement, and affects it.
583 simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
584 const SmallVectorImpl<IntrinsicInst *> &Targets) {
585 bool MadeChange = false;
586 for (auto &ToReplace : Targets) {
587 GCRelocateOperands MasterRelocate(RelocatedBase);
588 GCRelocateOperands ThisRelocate(ToReplace);
590 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
591 "Not relocating a derived object of the original base object");
592 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
593 // A duplicate relocate call. TODO: coalesce duplicates.
597 Value *Base = ThisRelocate.getBasePtr();
598 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
599 if (!Derived || Derived->getPointerOperand() != Base)
602 SmallVector<Value *, 2> OffsetV;
603 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
606 // Create a Builder and replace the target callsite with a gep
607 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
609 // Insert after RelocatedBase
610 IRBuilder<> Builder(RelocatedBase->getNextNode());
611 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
613 // If gc_relocate does not match the actual type, cast it to the right type.
614 // In theory, there must be a bitcast after gc_relocate if the type does not
615 // match, and we should reuse it to get the derived pointer. But it could be
619 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
624 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
628 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
629 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
631 // In this case, we can not find the bitcast any more. So we insert a new bitcast
632 // no matter there is already one or not. In this way, we can handle all cases, and
633 // the extra bitcast should be optimized away in later passes.
634 Instruction *ActualRelocatedBase = RelocatedBase;
635 if (RelocatedBase->getType() != Base->getType()) {
636 ActualRelocatedBase =
637 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
639 Value *Replacement = Builder.CreateGEP(
640 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
641 Instruction *ReplacementInst = cast<Instruction>(Replacement);
642 Replacement->takeName(ToReplace);
643 // If the newly generated derived pointer's type does not match the original derived
644 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
645 Instruction *ActualReplacement = ReplacementInst;
646 if (ReplacementInst->getType() != ToReplace->getType()) {
648 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
650 ToReplace->replaceAllUsesWith(ActualReplacement);
651 ToReplace->eraseFromParent();
661 // %ptr = gep %base + 15
662 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
663 // %base' = relocate(%tok, i32 4, i32 4)
664 // %ptr' = relocate(%tok, i32 4, i32 5)
670 // %ptr = gep %base + 15
671 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
672 // %base' = gc.relocate(%tok, i32 4, i32 4)
673 // %ptr' = gep %base' + 15
675 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
676 bool MadeChange = false;
677 SmallVector<User *, 2> AllRelocateCalls;
679 for (auto *U : I.users())
680 if (isGCRelocate(dyn_cast<Instruction>(U)))
681 // Collect all the relocate calls associated with a statepoint
682 AllRelocateCalls.push_back(U);
684 // We need atleast one base pointer relocation + one derived pointer
685 // relocation to mangle
686 if (AllRelocateCalls.size() < 2)
689 // RelocateInstMap is a mapping from the base relocate instruction to the
690 // corresponding derived relocate instructions
691 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
692 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
693 if (RelocateInstMap.empty())
696 for (auto &Item : RelocateInstMap)
697 // Item.first is the RelocatedBase to offset against
698 // Item.second is the vector of Targets to replace
699 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
703 /// SinkCast - Sink the specified cast instruction into its user blocks
704 static bool SinkCast(CastInst *CI) {
705 BasicBlock *DefBB = CI->getParent();
707 /// InsertedCasts - Only insert a cast in each block once.
708 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
710 bool MadeChange = false;
711 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
713 Use &TheUse = UI.getUse();
714 Instruction *User = cast<Instruction>(*UI);
716 // Figure out which BB this cast is used in. For PHI's this is the
717 // appropriate predecessor block.
718 BasicBlock *UserBB = User->getParent();
719 if (PHINode *PN = dyn_cast<PHINode>(User)) {
720 UserBB = PN->getIncomingBlock(TheUse);
723 // Preincrement use iterator so we don't invalidate it.
726 // If this user is in the same block as the cast, don't change the cast.
727 if (UserBB == DefBB) continue;
729 // If we have already inserted a cast into this block, use it.
730 CastInst *&InsertedCast = InsertedCasts[UserBB];
733 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
735 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
739 // Replace a use of the cast with a use of the new cast.
740 TheUse = InsertedCast;
745 // If we removed all uses, nuke the cast.
746 if (CI->use_empty()) {
747 CI->eraseFromParent();
754 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
755 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
756 /// sink it into user blocks to reduce the number of virtual
757 /// registers that must be created and coalesced.
759 /// Return true if any changes are made.
761 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
762 const DataLayout &DL) {
763 // If this is a noop copy,
764 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
765 EVT DstVT = TLI.getValueType(DL, CI->getType());
767 // This is an fp<->int conversion?
768 if (SrcVT.isInteger() != DstVT.isInteger())
771 // If this is an extension, it will be a zero or sign extension, which
773 if (SrcVT.bitsLT(DstVT)) return false;
775 // If these values will be promoted, find out what they will be promoted
776 // to. This helps us consider truncates on PPC as noop copies when they
778 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
779 TargetLowering::TypePromoteInteger)
780 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
781 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
782 TargetLowering::TypePromoteInteger)
783 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
785 // If, after promotion, these are the same types, this is a noop copy.
792 /// CombineUAddWithOverflow - try to combine CI into a call to the
793 /// llvm.uadd.with.overflow intrinsic if possible.
795 /// Return true if any changes were made.
796 static bool CombineUAddWithOverflow(CmpInst *CI) {
800 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
803 Type *Ty = AddI->getType();
804 if (!isa<IntegerType>(Ty))
807 // We don't want to move around uses of condition values this late, so we we
808 // check if it is legal to create the call to the intrinsic in the basic
809 // block containing the icmp:
811 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
815 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
817 if (AddI->hasOneUse())
818 assert(*AddI->user_begin() == CI && "expected!");
821 Module *M = CI->getParent()->getParent()->getParent();
822 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
824 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
826 auto *UAddWithOverflow =
827 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
828 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
830 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
832 CI->replaceAllUsesWith(Overflow);
833 AddI->replaceAllUsesWith(UAdd);
834 CI->eraseFromParent();
835 AddI->eraseFromParent();
839 /// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
840 /// the number of virtual registers that must be created and coalesced. This is
841 /// a clear win except on targets with multiple condition code registers
842 /// (PowerPC), where it might lose; some adjustment may be wanted there.
844 /// Return true if any changes are made.
845 static bool SinkCmpExpression(CmpInst *CI) {
846 BasicBlock *DefBB = CI->getParent();
848 /// InsertedCmp - Only insert a cmp in each block once.
849 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
851 bool MadeChange = false;
852 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
854 Use &TheUse = UI.getUse();
855 Instruction *User = cast<Instruction>(*UI);
857 // Preincrement use iterator so we don't invalidate it.
860 // Don't bother for PHI nodes.
861 if (isa<PHINode>(User))
864 // Figure out which BB this cmp is used in.
865 BasicBlock *UserBB = User->getParent();
867 // If this user is in the same block as the cmp, don't change the cmp.
868 if (UserBB == DefBB) continue;
870 // If we have already inserted a cmp into this block, use it.
871 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
874 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
876 CmpInst::Create(CI->getOpcode(),
877 CI->getPredicate(), CI->getOperand(0),
878 CI->getOperand(1), "", InsertPt);
881 // Replace a use of the cmp with a use of the new cmp.
882 TheUse = InsertedCmp;
887 // If we removed all uses, nuke the cmp.
888 if (CI->use_empty()) {
889 CI->eraseFromParent();
896 static bool OptimizeCmpExpression(CmpInst *CI) {
897 if (SinkCmpExpression(CI))
900 if (CombineUAddWithOverflow(CI))
906 /// isExtractBitsCandidateUse - Check if the candidates could
907 /// be combined with shift instruction, which includes:
908 /// 1. Truncate instruction
909 /// 2. And instruction and the imm is a mask of the low bits:
910 /// imm & (imm+1) == 0
911 static bool isExtractBitsCandidateUse(Instruction *User) {
912 if (!isa<TruncInst>(User)) {
913 if (User->getOpcode() != Instruction::And ||
914 !isa<ConstantInt>(User->getOperand(1)))
917 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
919 if ((Cimm & (Cimm + 1)).getBoolValue())
925 /// SinkShiftAndTruncate - sink both shift and truncate instruction
926 /// to the use of truncate's BB.
928 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
929 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
930 const TargetLowering &TLI, const DataLayout &DL) {
931 BasicBlock *UserBB = User->getParent();
932 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
933 TruncInst *TruncI = dyn_cast<TruncInst>(User);
934 bool MadeChange = false;
936 for (Value::user_iterator TruncUI = TruncI->user_begin(),
937 TruncE = TruncI->user_end();
938 TruncUI != TruncE;) {
940 Use &TruncTheUse = TruncUI.getUse();
941 Instruction *TruncUser = cast<Instruction>(*TruncUI);
942 // Preincrement use iterator so we don't invalidate it.
946 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
950 // If the use is actually a legal node, there will not be an
951 // implicit truncate.
952 // FIXME: always querying the result type is just an
953 // approximation; some nodes' legality is determined by the
954 // operand or other means. There's no good way to find out though.
955 if (TLI.isOperationLegalOrCustom(
956 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
959 // Don't bother for PHI nodes.
960 if (isa<PHINode>(TruncUser))
963 BasicBlock *TruncUserBB = TruncUser->getParent();
965 if (UserBB == TruncUserBB)
968 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
969 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
971 if (!InsertedShift && !InsertedTrunc) {
972 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
974 if (ShiftI->getOpcode() == Instruction::AShr)
976 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
979 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
982 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
985 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
986 TruncI->getType(), "", TruncInsertPt);
990 TruncTheUse = InsertedTrunc;
996 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
997 /// the uses could potentially be combined with this shift instruction and
998 /// generate BitExtract instruction. It will only be applied if the architecture
999 /// supports BitExtract instruction. Here is an example:
1001 /// %x.extract.shift = lshr i64 %arg1, 32
1003 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1007 /// %x.extract.shift.1 = lshr i64 %arg1, 32
1008 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1010 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1012 /// Return true if any changes are made.
1013 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1014 const TargetLowering &TLI,
1015 const DataLayout &DL) {
1016 BasicBlock *DefBB = ShiftI->getParent();
1018 /// Only insert instructions in each block once.
1019 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1021 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1023 bool MadeChange = false;
1024 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1026 Use &TheUse = UI.getUse();
1027 Instruction *User = cast<Instruction>(*UI);
1028 // Preincrement use iterator so we don't invalidate it.
1031 // Don't bother for PHI nodes.
1032 if (isa<PHINode>(User))
1035 if (!isExtractBitsCandidateUse(User))
1038 BasicBlock *UserBB = User->getParent();
1040 if (UserBB == DefBB) {
1041 // If the shift and truncate instruction are in the same BB. The use of
1042 // the truncate(TruncUse) may still introduce another truncate if not
1043 // legal. In this case, we would like to sink both shift and truncate
1044 // instruction to the BB of TruncUse.
1047 // i64 shift.result = lshr i64 opnd, imm
1048 // trunc.result = trunc shift.result to i16
1051 // ----> We will have an implicit truncate here if the architecture does
1052 // not have i16 compare.
1053 // cmp i16 trunc.result, opnd2
1055 if (isa<TruncInst>(User) && shiftIsLegal
1056 // If the type of the truncate is legal, no trucate will be
1057 // introduced in other basic blocks.
1059 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1061 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1065 // If we have already inserted a shift into this block, use it.
1066 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1068 if (!InsertedShift) {
1069 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1071 if (ShiftI->getOpcode() == Instruction::AShr)
1073 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
1076 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
1081 // Replace a use of the shift with a use of the new shift.
1082 TheUse = InsertedShift;
1085 // If we removed all uses, nuke the shift.
1086 if (ShiftI->use_empty())
1087 ShiftI->eraseFromParent();
1092 // ScalarizeMaskedLoad() translates masked load intrinsic, like
1093 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1094 // <16 x i1> %mask, <16 x i32> %passthru)
1095 // to a chain of basic blocks, whith loading element one-by-one if
1096 // the appropriate mask bit is set
1098 // %1 = bitcast i8* %addr to i32*
1099 // %2 = extractelement <16 x i1> %mask, i32 0
1100 // %3 = icmp eq i1 %2, true
1101 // br i1 %3, label %cond.load, label %else
1103 //cond.load: ; preds = %0
1104 // %4 = getelementptr i32* %1, i32 0
1105 // %5 = load i32* %4
1106 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1109 //else: ; preds = %0, %cond.load
1110 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1111 // %7 = extractelement <16 x i1> %mask, i32 1
1112 // %8 = icmp eq i1 %7, true
1113 // br i1 %8, label %cond.load1, label %else2
1115 //cond.load1: ; preds = %else
1116 // %9 = getelementptr i32* %1, i32 1
1117 // %10 = load i32* %9
1118 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1121 //else2: ; preds = %else, %cond.load1
1122 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1123 // %12 = extractelement <16 x i1> %mask, i32 2
1124 // %13 = icmp eq i1 %12, true
1125 // br i1 %13, label %cond.load4, label %else5
1127 static void ScalarizeMaskedLoad(CallInst *CI) {
1128 Value *Ptr = CI->getArgOperand(0);
1129 Value *Src0 = CI->getArgOperand(3);
1130 Value *Mask = CI->getArgOperand(2);
1131 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1132 Type *EltTy = VecType->getElementType();
1134 assert(VecType && "Unexpected return type of masked load intrinsic");
1136 IRBuilder<> Builder(CI->getContext());
1137 Instruction *InsertPt = CI;
1138 BasicBlock *IfBlock = CI->getParent();
1139 BasicBlock *CondBlock = nullptr;
1140 BasicBlock *PrevIfBlock = CI->getParent();
1141 Builder.SetInsertPoint(InsertPt);
1143 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1145 // Bitcast %addr fron i8* to EltTy*
1147 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1148 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1149 Value *UndefVal = UndefValue::get(VecType);
1151 // The result vector
1152 Value *VResult = UndefVal;
1154 PHINode *Phi = nullptr;
1155 Value *PrevPhi = UndefVal;
1157 unsigned VectorWidth = VecType->getNumElements();
1158 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1160 // Fill the "else" block, created in the previous iteration
1162 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1163 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1164 // %to_load = icmp eq i1 %mask_1, true
1165 // br i1 %to_load, label %cond.load, label %else
1168 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1169 Phi->addIncoming(VResult, CondBlock);
1170 Phi->addIncoming(PrevPhi, PrevIfBlock);
1175 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1176 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1177 ConstantInt::get(Predicate->getType(), 1));
1179 // Create "cond" block
1181 // %EltAddr = getelementptr i32* %1, i32 0
1182 // %Elt = load i32* %EltAddr
1183 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1185 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1186 Builder.SetInsertPoint(InsertPt);
1189 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1190 LoadInst* Load = Builder.CreateLoad(Gep, false);
1191 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1193 // Create "else" block, fill it in the next iteration
1194 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1195 Builder.SetInsertPoint(InsertPt);
1196 Instruction *OldBr = IfBlock->getTerminator();
1197 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1198 OldBr->eraseFromParent();
1199 PrevIfBlock = IfBlock;
1200 IfBlock = NewIfBlock;
1203 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1204 Phi->addIncoming(VResult, CondBlock);
1205 Phi->addIncoming(PrevPhi, PrevIfBlock);
1206 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1207 CI->replaceAllUsesWith(NewI);
1208 CI->eraseFromParent();
1211 // ScalarizeMaskedStore() translates masked store intrinsic, like
1212 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1214 // to a chain of basic blocks, that stores element one-by-one if
1215 // the appropriate mask bit is set
1217 // %1 = bitcast i8* %addr to i32*
1218 // %2 = extractelement <16 x i1> %mask, i32 0
1219 // %3 = icmp eq i1 %2, true
1220 // br i1 %3, label %cond.store, label %else
1222 // cond.store: ; preds = %0
1223 // %4 = extractelement <16 x i32> %val, i32 0
1224 // %5 = getelementptr i32* %1, i32 0
1225 // store i32 %4, i32* %5
1228 // else: ; preds = %0, %cond.store
1229 // %6 = extractelement <16 x i1> %mask, i32 1
1230 // %7 = icmp eq i1 %6, true
1231 // br i1 %7, label %cond.store1, label %else2
1233 // cond.store1: ; preds = %else
1234 // %8 = extractelement <16 x i32> %val, i32 1
1235 // %9 = getelementptr i32* %1, i32 1
1236 // store i32 %8, i32* %9
1239 static void ScalarizeMaskedStore(CallInst *CI) {
1240 Value *Ptr = CI->getArgOperand(1);
1241 Value *Src = CI->getArgOperand(0);
1242 Value *Mask = CI->getArgOperand(3);
1244 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1245 Type *EltTy = VecType->getElementType();
1247 assert(VecType && "Unexpected data type in masked store intrinsic");
1249 IRBuilder<> Builder(CI->getContext());
1250 Instruction *InsertPt = CI;
1251 BasicBlock *IfBlock = CI->getParent();
1252 Builder.SetInsertPoint(InsertPt);
1253 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1255 // Bitcast %addr fron i8* to EltTy*
1257 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1258 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1260 unsigned VectorWidth = VecType->getNumElements();
1261 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1263 // Fill the "else" block, created in the previous iteration
1265 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1266 // %to_store = icmp eq i1 %mask_1, true
1267 // br i1 %to_load, label %cond.store, label %else
1269 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1270 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1271 ConstantInt::get(Predicate->getType(), 1));
1273 // Create "cond" block
1275 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1276 // %EltAddr = getelementptr i32* %1, i32 0
1277 // %store i32 %OneElt, i32* %EltAddr
1279 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1280 Builder.SetInsertPoint(InsertPt);
1282 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1284 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1285 Builder.CreateStore(OneElt, Gep);
1287 // Create "else" block, fill it in the next iteration
1288 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1289 Builder.SetInsertPoint(InsertPt);
1290 Instruction *OldBr = IfBlock->getTerminator();
1291 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1292 OldBr->eraseFromParent();
1293 IfBlock = NewIfBlock;
1295 CI->eraseFromParent();
1298 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
1299 BasicBlock *BB = CI->getParent();
1301 // Lower inline assembly if we can.
1302 // If we found an inline asm expession, and if the target knows how to
1303 // lower it to normal LLVM code, do so now.
1304 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1305 if (TLI->ExpandInlineAsm(CI)) {
1306 // Avoid invalidating the iterator.
1307 CurInstIterator = BB->begin();
1308 // Avoid processing instructions out of order, which could cause
1309 // reuse before a value is defined.
1313 // Sink address computing for memory operands into the block.
1314 if (OptimizeInlineAsmInst(CI))
1318 // Align the pointer arguments to this call if the target thinks it's a good
1320 unsigned MinSize, PrefAlign;
1321 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1322 for (auto &Arg : CI->arg_operands()) {
1323 // We want to align both objects whose address is used directly and
1324 // objects whose address is used in casts and GEPs, though it only makes
1325 // sense for GEPs if the offset is a multiple of the desired alignment and
1326 // if size - offset meets the size threshold.
1327 if (!Arg->getType()->isPointerTy())
1329 APInt Offset(DL->getPointerSizeInBits(
1330 cast<PointerType>(Arg->getType())->getAddressSpace()),
1332 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
1333 uint64_t Offset2 = Offset.getLimitedValue();
1334 if ((Offset2 & (PrefAlign-1)) != 0)
1337 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1338 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1339 AI->setAlignment(PrefAlign);
1340 // Global variables can only be aligned if they are defined in this
1341 // object (i.e. they are uniquely initialized in this object), and
1342 // over-aligning global variables that have an explicit section is
1345 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1346 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1347 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1349 GV->setAlignment(PrefAlign);
1351 // If this is a memcpy (or similar) then we may be able to improve the
1353 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1354 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
1355 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
1356 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
1357 if (Align > MI->getAlignment())
1358 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1362 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
1364 switch (II->getIntrinsicID()) {
1366 case Intrinsic::objectsize: {
1367 // Lower all uses of llvm.objectsize.*
1368 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1369 Type *ReturnTy = CI->getType();
1370 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
1372 // Substituting this can cause recursive simplifications, which can
1373 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1375 WeakVH IterHandle(CurInstIterator);
1377 replaceAndRecursivelySimplify(CI, RetVal,
1380 // If the iterator instruction was recursively deleted, start over at the
1381 // start of the block.
1382 if (IterHandle != CurInstIterator) {
1383 CurInstIterator = BB->begin();
1388 case Intrinsic::masked_load: {
1389 // Scalarize unsupported vector masked load
1390 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1391 ScalarizeMaskedLoad(CI);
1397 case Intrinsic::masked_store: {
1398 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1399 ScalarizeMaskedStore(CI);
1405 case Intrinsic::aarch64_stlxr:
1406 case Intrinsic::aarch64_stxr: {
1407 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1408 if (!ExtVal || !ExtVal->hasOneUse() ||
1409 ExtVal->getParent() == CI->getParent())
1411 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1412 ExtVal->moveBefore(CI);
1413 // Mark this instruction as "inserted by CGP", so that other
1414 // optimizations don't touch it.
1415 InsertedInsts.insert(ExtVal);
1421 // Unknown address space.
1422 // TODO: Target hook to pick which address space the intrinsic cares
1424 unsigned AddrSpace = ~0u;
1425 SmallVector<Value*, 2> PtrOps;
1427 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
1428 while (!PtrOps.empty())
1429 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
1434 // From here on out we're working with named functions.
1435 if (!CI->getCalledFunction()) return false;
1437 // Lower all default uses of _chk calls. This is very similar
1438 // to what InstCombineCalls does, but here we are only lowering calls
1439 // to fortified library functions (e.g. __memcpy_chk) that have the default
1440 // "don't know" as the objectsize. Anything else should be left alone.
1441 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
1442 if (Value *V = Simplifier.optimizeCall(CI)) {
1443 CI->replaceAllUsesWith(V);
1444 CI->eraseFromParent();
1450 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1451 /// instructions to the predecessor to enable tail call optimizations. The
1452 /// case it is currently looking for is:
1455 /// %tmp0 = tail call i32 @f0()
1456 /// br label %return
1458 /// %tmp1 = tail call i32 @f1()
1459 /// br label %return
1461 /// %tmp2 = tail call i32 @f2()
1462 /// br label %return
1464 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1472 /// %tmp0 = tail call i32 @f0()
1475 /// %tmp1 = tail call i32 @f1()
1478 /// %tmp2 = tail call i32 @f2()
1481 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
1485 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1489 PHINode *PN = nullptr;
1490 BitCastInst *BCI = nullptr;
1491 Value *V = RI->getReturnValue();
1493 BCI = dyn_cast<BitCastInst>(V);
1495 V = BCI->getOperand(0);
1497 PN = dyn_cast<PHINode>(V);
1502 if (PN && PN->getParent() != BB)
1505 // It's not safe to eliminate the sign / zero extension of the return value.
1506 // See llvm::isInTailCallPosition().
1507 const Function *F = BB->getParent();
1508 AttributeSet CallerAttrs = F->getAttributes();
1509 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1510 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1513 // Make sure there are no instructions between the PHI and return, or that the
1514 // return is the first instruction in the block.
1516 BasicBlock::iterator BI = BB->begin();
1517 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
1519 // Also skip over the bitcast.
1524 BasicBlock::iterator BI = BB->begin();
1525 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1530 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1532 SmallVector<CallInst*, 4> TailCalls;
1534 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1535 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1536 // Make sure the phi value is indeed produced by the tail call.
1537 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1538 TLI->mayBeEmittedAsTailCall(CI))
1539 TailCalls.push_back(CI);
1542 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
1543 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1544 if (!VisitedBBs.insert(*PI).second)
1547 BasicBlock::InstListType &InstList = (*PI)->getInstList();
1548 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1549 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1550 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1554 CallInst *CI = dyn_cast<CallInst>(&*RI);
1555 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1556 TailCalls.push_back(CI);
1560 bool Changed = false;
1561 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1562 CallInst *CI = TailCalls[i];
1565 // Conservatively require the attributes of the call to match those of the
1566 // return. Ignore noalias because it doesn't affect the call sequence.
1567 AttributeSet CalleeAttrs = CS.getAttributes();
1568 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1569 removeAttribute(Attribute::NoAlias) !=
1570 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1571 removeAttribute(Attribute::NoAlias))
1574 // Make sure the call instruction is followed by an unconditional branch to
1575 // the return block.
1576 BasicBlock *CallBB = CI->getParent();
1577 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1578 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1581 // Duplicate the return into CallBB.
1582 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1583 ModifiedDT = Changed = true;
1587 // If we eliminated all predecessors of the block, delete the block now.
1588 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1589 BB->eraseFromParent();
1594 //===----------------------------------------------------------------------===//
1595 // Memory Optimization
1596 //===----------------------------------------------------------------------===//
1600 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1601 /// which holds actual Value*'s for register values.
1602 struct ExtAddrMode : public TargetLowering::AddrMode {
1605 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1606 void print(raw_ostream &OS) const;
1609 bool operator==(const ExtAddrMode& O) const {
1610 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1611 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1612 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1617 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1623 void ExtAddrMode::print(raw_ostream &OS) const {
1624 bool NeedPlus = false;
1627 OS << (NeedPlus ? " + " : "")
1629 BaseGV->printAsOperand(OS, /*PrintType=*/false);
1634 OS << (NeedPlus ? " + " : "")
1640 OS << (NeedPlus ? " + " : "")
1642 BaseReg->printAsOperand(OS, /*PrintType=*/false);
1646 OS << (NeedPlus ? " + " : "")
1648 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1654 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1655 void ExtAddrMode::dump() const {
1661 /// \brief This class provides transaction based operation on the IR.
1662 /// Every change made through this class is recorded in the internal state and
1663 /// can be undone (rollback) until commit is called.
1664 class TypePromotionTransaction {
1666 /// \brief This represents the common interface of the individual transaction.
1667 /// Each class implements the logic for doing one specific modification on
1668 /// the IR via the TypePromotionTransaction.
1669 class TypePromotionAction {
1671 /// The Instruction modified.
1675 /// \brief Constructor of the action.
1676 /// The constructor performs the related action on the IR.
1677 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1679 virtual ~TypePromotionAction() {}
1681 /// \brief Undo the modification done by this action.
1682 /// When this method is called, the IR must be in the same state as it was
1683 /// before this action was applied.
1684 /// \pre Undoing the action works if and only if the IR is in the exact same
1685 /// state as it was directly after this action was applied.
1686 virtual void undo() = 0;
1688 /// \brief Advocate every change made by this action.
1689 /// When the results on the IR of the action are to be kept, it is important
1690 /// to call this function, otherwise hidden information may be kept forever.
1691 virtual void commit() {
1692 // Nothing to be done, this action is not doing anything.
1696 /// \brief Utility to remember the position of an instruction.
1697 class InsertionHandler {
1698 /// Position of an instruction.
1699 /// Either an instruction:
1700 /// - Is the first in a basic block: BB is used.
1701 /// - Has a previous instructon: PrevInst is used.
1703 Instruction *PrevInst;
1706 /// Remember whether or not the instruction had a previous instruction.
1707 bool HasPrevInstruction;
1710 /// \brief Record the position of \p Inst.
1711 InsertionHandler(Instruction *Inst) {
1712 BasicBlock::iterator It = Inst;
1713 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1714 if (HasPrevInstruction)
1715 Point.PrevInst = --It;
1717 Point.BB = Inst->getParent();
1720 /// \brief Insert \p Inst at the recorded position.
1721 void insert(Instruction *Inst) {
1722 if (HasPrevInstruction) {
1723 if (Inst->getParent())
1724 Inst->removeFromParent();
1725 Inst->insertAfter(Point.PrevInst);
1727 Instruction *Position = Point.BB->getFirstInsertionPt();
1728 if (Inst->getParent())
1729 Inst->moveBefore(Position);
1731 Inst->insertBefore(Position);
1736 /// \brief Move an instruction before another.
1737 class InstructionMoveBefore : public TypePromotionAction {
1738 /// Original position of the instruction.
1739 InsertionHandler Position;
1742 /// \brief Move \p Inst before \p Before.
1743 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1744 : TypePromotionAction(Inst), Position(Inst) {
1745 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1746 Inst->moveBefore(Before);
1749 /// \brief Move the instruction back to its original position.
1750 void undo() override {
1751 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1752 Position.insert(Inst);
1756 /// \brief Set the operand of an instruction with a new value.
1757 class OperandSetter : public TypePromotionAction {
1758 /// Original operand of the instruction.
1760 /// Index of the modified instruction.
1764 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1765 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1766 : TypePromotionAction(Inst), Idx(Idx) {
1767 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1768 << "for:" << *Inst << "\n"
1769 << "with:" << *NewVal << "\n");
1770 Origin = Inst->getOperand(Idx);
1771 Inst->setOperand(Idx, NewVal);
1774 /// \brief Restore the original value of the instruction.
1775 void undo() override {
1776 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1777 << "for: " << *Inst << "\n"
1778 << "with: " << *Origin << "\n");
1779 Inst->setOperand(Idx, Origin);
1783 /// \brief Hide the operands of an instruction.
1784 /// Do as if this instruction was not using any of its operands.
1785 class OperandsHider : public TypePromotionAction {
1786 /// The list of original operands.
1787 SmallVector<Value *, 4> OriginalValues;
1790 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1791 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1792 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1793 unsigned NumOpnds = Inst->getNumOperands();
1794 OriginalValues.reserve(NumOpnds);
1795 for (unsigned It = 0; It < NumOpnds; ++It) {
1796 // Save the current operand.
1797 Value *Val = Inst->getOperand(It);
1798 OriginalValues.push_back(Val);
1800 // We could use OperandSetter here, but that would implied an overhead
1801 // that we are not willing to pay.
1802 Inst->setOperand(It, UndefValue::get(Val->getType()));
1806 /// \brief Restore the original list of uses.
1807 void undo() override {
1808 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1809 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1810 Inst->setOperand(It, OriginalValues[It]);
1814 /// \brief Build a truncate instruction.
1815 class TruncBuilder : public TypePromotionAction {
1818 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1820 /// trunc Opnd to Ty.
1821 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1822 IRBuilder<> Builder(Opnd);
1823 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1824 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1827 /// \brief Get the built value.
1828 Value *getBuiltValue() { return Val; }
1830 /// \brief Remove the built instruction.
1831 void undo() override {
1832 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1833 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1834 IVal->eraseFromParent();
1838 /// \brief Build a sign extension instruction.
1839 class SExtBuilder : public TypePromotionAction {
1842 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1844 /// sext Opnd to Ty.
1845 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1846 : TypePromotionAction(InsertPt) {
1847 IRBuilder<> Builder(InsertPt);
1848 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1849 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1852 /// \brief Get the built value.
1853 Value *getBuiltValue() { return Val; }
1855 /// \brief Remove the built instruction.
1856 void undo() override {
1857 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1858 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1859 IVal->eraseFromParent();
1863 /// \brief Build a zero extension instruction.
1864 class ZExtBuilder : public TypePromotionAction {
1867 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1869 /// zext Opnd to Ty.
1870 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1871 : TypePromotionAction(InsertPt) {
1872 IRBuilder<> Builder(InsertPt);
1873 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1874 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1877 /// \brief Get the built value.
1878 Value *getBuiltValue() { return Val; }
1880 /// \brief Remove the built instruction.
1881 void undo() override {
1882 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1883 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1884 IVal->eraseFromParent();
1888 /// \brief Mutate an instruction to another type.
1889 class TypeMutator : public TypePromotionAction {
1890 /// Record the original type.
1894 /// \brief Mutate the type of \p Inst into \p NewTy.
1895 TypeMutator(Instruction *Inst, Type *NewTy)
1896 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1897 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1899 Inst->mutateType(NewTy);
1902 /// \brief Mutate the instruction back to its original type.
1903 void undo() override {
1904 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1906 Inst->mutateType(OrigTy);
1910 /// \brief Replace the uses of an instruction by another instruction.
1911 class UsesReplacer : public TypePromotionAction {
1912 /// Helper structure to keep track of the replaced uses.
1913 struct InstructionAndIdx {
1914 /// The instruction using the instruction.
1916 /// The index where this instruction is used for Inst.
1918 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1919 : Inst(Inst), Idx(Idx) {}
1922 /// Keep track of the original uses (pair Instruction, Index).
1923 SmallVector<InstructionAndIdx, 4> OriginalUses;
1924 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1927 /// \brief Replace all the use of \p Inst by \p New.
1928 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1929 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1931 // Record the original uses.
1932 for (Use &U : Inst->uses()) {
1933 Instruction *UserI = cast<Instruction>(U.getUser());
1934 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1936 // Now, we can replace the uses.
1937 Inst->replaceAllUsesWith(New);
1940 /// \brief Reassign the original uses of Inst to Inst.
1941 void undo() override {
1942 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1943 for (use_iterator UseIt = OriginalUses.begin(),
1944 EndIt = OriginalUses.end();
1945 UseIt != EndIt; ++UseIt) {
1946 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1951 /// \brief Remove an instruction from the IR.
1952 class InstructionRemover : public TypePromotionAction {
1953 /// Original position of the instruction.
1954 InsertionHandler Inserter;
1955 /// Helper structure to hide all the link to the instruction. In other
1956 /// words, this helps to do as if the instruction was removed.
1957 OperandsHider Hider;
1958 /// Keep track of the uses replaced, if any.
1959 UsesReplacer *Replacer;
1962 /// \brief Remove all reference of \p Inst and optinally replace all its
1964 /// \pre If !Inst->use_empty(), then New != nullptr
1965 InstructionRemover(Instruction *Inst, Value *New = nullptr)
1966 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1969 Replacer = new UsesReplacer(Inst, New);
1970 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1971 Inst->removeFromParent();
1974 ~InstructionRemover() override { delete Replacer; }
1976 /// \brief Really remove the instruction.
1977 void commit() override { delete Inst; }
1979 /// \brief Resurrect the instruction and reassign it to the proper uses if
1980 /// new value was provided when build this action.
1981 void undo() override {
1982 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1983 Inserter.insert(Inst);
1991 /// Restoration point.
1992 /// The restoration point is a pointer to an action instead of an iterator
1993 /// because the iterator may be invalidated but not the pointer.
1994 typedef const TypePromotionAction *ConstRestorationPt;
1995 /// Advocate every changes made in that transaction.
1997 /// Undo all the changes made after the given point.
1998 void rollback(ConstRestorationPt Point);
1999 /// Get the current restoration point.
2000 ConstRestorationPt getRestorationPoint() const;
2002 /// \name API for IR modification with state keeping to support rollback.
2004 /// Same as Instruction::setOperand.
2005 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2006 /// Same as Instruction::eraseFromParent.
2007 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2008 /// Same as Value::replaceAllUsesWith.
2009 void replaceAllUsesWith(Instruction *Inst, Value *New);
2010 /// Same as Value::mutateType.
2011 void mutateType(Instruction *Inst, Type *NewTy);
2012 /// Same as IRBuilder::createTrunc.
2013 Value *createTrunc(Instruction *Opnd, Type *Ty);
2014 /// Same as IRBuilder::createSExt.
2015 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
2016 /// Same as IRBuilder::createZExt.
2017 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
2018 /// Same as Instruction::moveBefore.
2019 void moveBefore(Instruction *Inst, Instruction *Before);
2023 /// The ordered list of actions made so far.
2024 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2025 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
2028 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2031 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
2034 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2037 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
2040 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2042 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2045 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
2046 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2049 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2051 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
2052 Value *Val = Ptr->getBuiltValue();
2053 Actions.push_back(std::move(Ptr));
2057 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2058 Value *Opnd, Type *Ty) {
2059 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
2060 Value *Val = Ptr->getBuiltValue();
2061 Actions.push_back(std::move(Ptr));
2065 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2066 Value *Opnd, Type *Ty) {
2067 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
2068 Value *Val = Ptr->getBuiltValue();
2069 Actions.push_back(std::move(Ptr));
2073 void TypePromotionTransaction::moveBefore(Instruction *Inst,
2074 Instruction *Before) {
2076 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
2079 TypePromotionTransaction::ConstRestorationPt
2080 TypePromotionTransaction::getRestorationPoint() const {
2081 return !Actions.empty() ? Actions.back().get() : nullptr;
2084 void TypePromotionTransaction::commit() {
2085 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2091 void TypePromotionTransaction::rollback(
2092 TypePromotionTransaction::ConstRestorationPt Point) {
2093 while (!Actions.empty() && Point != Actions.back().get()) {
2094 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2099 /// \brief A helper class for matching addressing modes.
2101 /// This encapsulates the logic for matching the target-legal addressing modes.
2102 class AddressingModeMatcher {
2103 SmallVectorImpl<Instruction*> &AddrModeInsts;
2104 const TargetMachine &TM;
2105 const TargetLowering &TLI;
2106 const DataLayout &DL;
2108 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2109 /// the memory instruction that we're computing this address for.
2112 Instruction *MemoryInst;
2114 /// AddrMode - This is the addressing mode that we're building up. This is
2115 /// part of the return value of this addressing mode matching stuff.
2116 ExtAddrMode &AddrMode;
2118 /// The instructions inserted by other CodeGenPrepare optimizations.
2119 const SetOfInstrs &InsertedInsts;
2120 /// A map from the instructions to their type before promotion.
2121 InstrToOrigTy &PromotedInsts;
2122 /// The ongoing transaction where every action should be registered.
2123 TypePromotionTransaction &TPT;
2125 /// IgnoreProfitability - This is set to true when we should not do
2126 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
2127 /// always returns true.
2128 bool IgnoreProfitability;
2130 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
2131 const TargetMachine &TM, Type *AT, unsigned AS,
2132 Instruction *MI, ExtAddrMode &AM,
2133 const SetOfInstrs &InsertedInsts,
2134 InstrToOrigTy &PromotedInsts,
2135 TypePromotionTransaction &TPT)
2136 : AddrModeInsts(AMI), TM(TM),
2137 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2138 ->getTargetLowering()),
2139 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2140 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2141 PromotedInsts(PromotedInsts), TPT(TPT) {
2142 IgnoreProfitability = false;
2146 /// Match - Find the maximal addressing mode that a load/store of V can fold,
2147 /// give an access type of AccessTy. This returns a list of involved
2148 /// instructions in AddrModeInsts.
2149 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
2151 /// \p PromotedInsts maps the instructions to their type before promotion.
2152 /// \p The ongoing transaction where every action should be registered.
2153 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
2154 Instruction *MemoryInst,
2155 SmallVectorImpl<Instruction*> &AddrModeInsts,
2156 const TargetMachine &TM,
2157 const SetOfInstrs &InsertedInsts,
2158 InstrToOrigTy &PromotedInsts,
2159 TypePromotionTransaction &TPT) {
2162 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
2163 MemoryInst, Result, InsertedInsts,
2164 PromotedInsts, TPT).MatchAddr(V, 0);
2165 (void)Success; assert(Success && "Couldn't select *anything*?");
2169 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2170 bool MatchAddr(Value *V, unsigned Depth);
2171 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
2172 bool *MovedAway = nullptr);
2173 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2174 ExtAddrMode &AMBefore,
2175 ExtAddrMode &AMAfter);
2176 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2177 bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
2178 Value *PromotedOperand) const;
2181 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2182 /// Return true and update AddrMode if this addr mode is legal for the target,
2184 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2186 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2187 // mode. Just process that directly.
2189 return MatchAddr(ScaleReg, Depth);
2191 // If the scale is 0, it takes nothing to add this.
2195 // If we already have a scale of this value, we can add to it, otherwise, we
2196 // need an available scale field.
2197 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2200 ExtAddrMode TestAddrMode = AddrMode;
2202 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2203 // [A+B + A*7] -> [B+A*8].
2204 TestAddrMode.Scale += Scale;
2205 TestAddrMode.ScaledReg = ScaleReg;
2207 // If the new address isn't legal, bail out.
2208 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
2211 // It was legal, so commit it.
2212 AddrMode = TestAddrMode;
2214 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2215 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2216 // X*Scale + C*Scale to addr mode.
2217 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
2218 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2219 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2220 TestAddrMode.ScaledReg = AddLHS;
2221 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
2223 // If this addressing mode is legal, commit it and remember that we folded
2224 // this instruction.
2225 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
2226 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2227 AddrMode = TestAddrMode;
2232 // Otherwise, not (x+c)*scale, just return what we have.
2236 /// MightBeFoldableInst - This is a little filter, which returns true if an
2237 /// addressing computation involving I might be folded into a load/store
2238 /// accessing it. This doesn't need to be perfect, but needs to accept at least
2239 /// the set of instructions that MatchOperationAddr can.
2240 static bool MightBeFoldableInst(Instruction *I) {
2241 switch (I->getOpcode()) {
2242 case Instruction::BitCast:
2243 case Instruction::AddrSpaceCast:
2244 // Don't touch identity bitcasts.
2245 if (I->getType() == I->getOperand(0)->getType())
2247 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2248 case Instruction::PtrToInt:
2249 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2251 case Instruction::IntToPtr:
2252 // We know the input is intptr_t, so this is foldable.
2254 case Instruction::Add:
2256 case Instruction::Mul:
2257 case Instruction::Shl:
2258 // Can only handle X*C and X << C.
2259 return isa<ConstantInt>(I->getOperand(1));
2260 case Instruction::GetElementPtr:
2267 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2268 /// \note \p Val is assumed to be the product of some type promotion.
2269 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2270 /// to be legal, as the non-promoted value would have had the same state.
2271 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2272 const DataLayout &DL, Value *Val) {
2273 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2276 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2277 // If the ISDOpcode is undefined, it was undefined before the promotion.
2280 // Otherwise, check if the promoted instruction is legal or not.
2281 return TLI.isOperationLegalOrCustom(
2282 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
2285 /// \brief Hepler class to perform type promotion.
2286 class TypePromotionHelper {
2287 /// \brief Utility function to check whether or not a sign or zero extension
2288 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2289 /// either using the operands of \p Inst or promoting \p Inst.
2290 /// The type of the extension is defined by \p IsSExt.
2291 /// In other words, check if:
2292 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
2293 /// #1 Promotion applies:
2294 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
2295 /// #2 Operand reuses:
2296 /// ext opnd1 to ConsideredExtType.
2297 /// \p PromotedInsts maps the instructions to their type before promotion.
2298 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2299 const InstrToOrigTy &PromotedInsts, bool IsSExt);
2301 /// \brief Utility function to determine if \p OpIdx should be promoted when
2302 /// promoting \p Inst.
2303 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
2304 if (isa<SelectInst>(Inst) && OpIdx == 0)
2309 /// \brief Utility function to promote the operand of \p Ext when this
2310 /// operand is a promotable trunc or sext or zext.
2311 /// \p PromotedInsts maps the instructions to their type before promotion.
2312 /// \p CreatedInstsCost[out] contains the cost of all instructions
2313 /// created to promote the operand of Ext.
2314 /// Newly added extensions are inserted in \p Exts.
2315 /// Newly added truncates are inserted in \p Truncs.
2316 /// Should never be called directly.
2317 /// \return The promoted value which is used instead of Ext.
2318 static Value *promoteOperandForTruncAndAnyExt(
2319 Instruction *Ext, TypePromotionTransaction &TPT,
2320 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2321 SmallVectorImpl<Instruction *> *Exts,
2322 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
2324 /// \brief Utility function to promote the operand of \p Ext when this
2325 /// operand is promotable and is not a supported trunc or sext.
2326 /// \p PromotedInsts maps the instructions to their type before promotion.
2327 /// \p CreatedInstsCost[out] contains the cost of all the instructions
2328 /// created to promote the operand of Ext.
2329 /// Newly added extensions are inserted in \p Exts.
2330 /// Newly added truncates are inserted in \p Truncs.
2331 /// Should never be called directly.
2332 /// \return The promoted value which is used instead of Ext.
2333 static Value *promoteOperandForOther(Instruction *Ext,
2334 TypePromotionTransaction &TPT,
2335 InstrToOrigTy &PromotedInsts,
2336 unsigned &CreatedInstsCost,
2337 SmallVectorImpl<Instruction *> *Exts,
2338 SmallVectorImpl<Instruction *> *Truncs,
2339 const TargetLowering &TLI, bool IsSExt);
2341 /// \see promoteOperandForOther.
2342 static Value *signExtendOperandForOther(
2343 Instruction *Ext, TypePromotionTransaction &TPT,
2344 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2345 SmallVectorImpl<Instruction *> *Exts,
2346 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2347 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2348 Exts, Truncs, TLI, true);
2351 /// \see promoteOperandForOther.
2352 static Value *zeroExtendOperandForOther(
2353 Instruction *Ext, TypePromotionTransaction &TPT,
2354 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2355 SmallVectorImpl<Instruction *> *Exts,
2356 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2357 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2358 Exts, Truncs, TLI, false);
2362 /// Type for the utility function that promotes the operand of Ext.
2363 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2364 InstrToOrigTy &PromotedInsts,
2365 unsigned &CreatedInstsCost,
2366 SmallVectorImpl<Instruction *> *Exts,
2367 SmallVectorImpl<Instruction *> *Truncs,
2368 const TargetLowering &TLI);
2369 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2370 /// action to promote the operand of \p Ext instead of using Ext.
2371 /// \return NULL if no promotable action is possible with the current
2373 /// \p InsertedInsts keeps track of all the instructions inserted by the
2374 /// other CodeGenPrepare optimizations. This information is important
2375 /// because we do not want to promote these instructions as CodeGenPrepare
2376 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2377 /// \p PromotedInsts maps the instructions to their type before promotion.
2378 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
2379 const TargetLowering &TLI,
2380 const InstrToOrigTy &PromotedInsts);
2383 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2384 Type *ConsideredExtType,
2385 const InstrToOrigTy &PromotedInsts,
2387 // The promotion helper does not know how to deal with vector types yet.
2388 // To be able to fix that, we would need to fix the places where we
2389 // statically extend, e.g., constants and such.
2390 if (Inst->getType()->isVectorTy())
2393 // We can always get through zext.
2394 if (isa<ZExtInst>(Inst))
2397 // sext(sext) is ok too.
2398 if (IsSExt && isa<SExtInst>(Inst))
2401 // We can get through binary operator, if it is legal. In other words, the
2402 // binary operator must have a nuw or nsw flag.
2403 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2404 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
2405 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2406 (IsSExt && BinOp->hasNoSignedWrap())))
2409 // Check if we can do the following simplification.
2410 // ext(trunc(opnd)) --> ext(opnd)
2411 if (!isa<TruncInst>(Inst))
2414 Value *OpndVal = Inst->getOperand(0);
2415 // Check if we can use this operand in the extension.
2416 // If the type is larger than the result type of the extension,
2418 if (!OpndVal->getType()->isIntegerTy() ||
2419 OpndVal->getType()->getIntegerBitWidth() >
2420 ConsideredExtType->getIntegerBitWidth())
2423 // If the operand of the truncate is not an instruction, we will not have
2424 // any information on the dropped bits.
2425 // (Actually we could for constant but it is not worth the extra logic).
2426 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2430 // Check if the source of the type is narrow enough.
2431 // I.e., check that trunc just drops extended bits of the same kind of
2433 // #1 get the type of the operand and check the kind of the extended bits.
2434 const Type *OpndType;
2435 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
2436 if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
2437 OpndType = It->second.Ty;
2438 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2439 OpndType = Opnd->getOperand(0)->getType();
2443 // #2 check that the truncate just drop extended bits.
2444 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2450 TypePromotionHelper::Action TypePromotionHelper::getAction(
2451 Instruction *Ext, const SetOfInstrs &InsertedInsts,
2452 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
2453 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2454 "Unexpected instruction type");
2455 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2456 Type *ExtTy = Ext->getType();
2457 bool IsSExt = isa<SExtInst>(Ext);
2458 // If the operand of the extension is not an instruction, we cannot
2460 // If it, check we can get through.
2461 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
2464 // Do not promote if the operand has been added by codegenprepare.
2465 // Otherwise, it means we are undoing an optimization that is likely to be
2466 // redone, thus causing potential infinite loop.
2467 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
2470 // SExt or Trunc instructions.
2471 // Return the related handler.
2472 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2473 isa<ZExtInst>(ExtOpnd))
2474 return promoteOperandForTruncAndAnyExt;
2476 // Regular instruction.
2477 // Abort early if we will have to insert non-free instructions.
2478 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
2480 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
2483 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
2484 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2485 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2486 SmallVectorImpl<Instruction *> *Exts,
2487 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2488 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2489 // get through it and this method should not be called.
2490 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
2491 Value *ExtVal = SExt;
2492 bool HasMergedNonFreeExt = false;
2493 if (isa<ZExtInst>(SExtOpnd)) {
2494 // Replace s|zext(zext(opnd))
2496 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
2498 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2499 TPT.replaceAllUsesWith(SExt, ZExt);
2500 TPT.eraseInstruction(SExt);
2503 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2505 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2507 CreatedInstsCost = 0;
2509 // Remove dead code.
2510 if (SExtOpnd->use_empty())
2511 TPT.eraseInstruction(SExtOpnd);
2513 // Check if the extension is still needed.
2514 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
2515 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2518 Exts->push_back(ExtInst);
2519 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2524 // At this point we have: ext ty opnd to ty.
2525 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2526 Value *NextVal = ExtInst->getOperand(0);
2527 TPT.eraseInstruction(ExtInst, NextVal);
2531 Value *TypePromotionHelper::promoteOperandForOther(
2532 Instruction *Ext, TypePromotionTransaction &TPT,
2533 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2534 SmallVectorImpl<Instruction *> *Exts,
2535 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2537 // By construction, the operand of Ext is an instruction. Otherwise we cannot
2538 // get through it and this method should not be called.
2539 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2540 CreatedInstsCost = 0;
2541 if (!ExtOpnd->hasOneUse()) {
2542 // ExtOpnd will be promoted.
2543 // All its uses, but Ext, will need to use a truncated value of the
2544 // promoted version.
2545 // Create the truncate now.
2546 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2547 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2548 ITrunc->removeFromParent();
2549 // Insert it just after the definition.
2550 ITrunc->insertAfter(ExtOpnd);
2552 Truncs->push_back(ITrunc);
2555 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2556 // Restore the operand of Ext (which has been replace by the previous call
2557 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2558 TPT.setOperand(Ext, 0, ExtOpnd);
2561 // Get through the Instruction:
2562 // 1. Update its type.
2563 // 2. Replace the uses of Ext by Inst.
2564 // 3. Extend each operand that needs to be extended.
2566 // Remember the original type of the instruction before promotion.
2567 // This is useful to know that the high bits are sign extended bits.
2568 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2569 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2571 TPT.mutateType(ExtOpnd, Ext->getType());
2573 TPT.replaceAllUsesWith(Ext, ExtOpnd);
2575 Instruction *ExtForOpnd = Ext;
2577 DEBUG(dbgs() << "Propagate Ext to operands\n");
2578 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2580 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2581 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2582 !shouldExtOperand(ExtOpnd, OpIdx)) {
2583 DEBUG(dbgs() << "No need to propagate\n");
2586 // Check if we can statically extend the operand.
2587 Value *Opnd = ExtOpnd->getOperand(OpIdx);
2588 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2589 DEBUG(dbgs() << "Statically extend\n");
2590 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2591 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2592 : Cst->getValue().zext(BitWidth);
2593 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2596 // UndefValue are typed, so we have to statically sign extend them.
2597 if (isa<UndefValue>(Opnd)) {
2598 DEBUG(dbgs() << "Statically extend\n");
2599 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2603 // Otherwise we have to explicity sign extend the operand.
2604 // Check if Ext was reused to extend an operand.
2606 // If yes, create a new one.
2607 DEBUG(dbgs() << "More operands to ext\n");
2608 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2609 : TPT.createZExt(Ext, Opnd, Ext->getType());
2610 if (!isa<Instruction>(ValForExtOpnd)) {
2611 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2614 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
2617 Exts->push_back(ExtForOpnd);
2618 TPT.setOperand(ExtForOpnd, 0, Opnd);
2620 // Move the sign extension before the insertion point.
2621 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2622 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2623 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
2624 // If more sext are required, new instructions will have to be created.
2625 ExtForOpnd = nullptr;
2627 if (ExtForOpnd == Ext) {
2628 DEBUG(dbgs() << "Extension is useless now\n");
2629 TPT.eraseInstruction(Ext);
2634 /// IsPromotionProfitable - Check whether or not promoting an instruction
2635 /// to a wider type was profitable.
2636 /// \p NewCost gives the cost of extension instructions created by the
2638 /// \p OldCost gives the cost of extension instructions before the promotion
2639 /// plus the number of instructions that have been
2640 /// matched in the addressing mode the promotion.
2641 /// \p PromotedOperand is the value that has been promoted.
2642 /// \return True if the promotion is profitable, false otherwise.
2643 bool AddressingModeMatcher::IsPromotionProfitable(
2644 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2645 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2646 // The cost of the new extensions is greater than the cost of the
2647 // old extension plus what we folded.
2648 // This is not profitable.
2649 if (NewCost > OldCost)
2651 if (NewCost < OldCost)
2653 // The promotion is neutral but it may help folding the sign extension in
2654 // loads for instance.
2655 // Check that we did not create an illegal instruction.
2656 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
2659 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2660 /// fold the operation into the addressing mode. If so, update the addressing
2661 /// mode and return true, otherwise return false without modifying AddrMode.
2662 /// If \p MovedAway is not NULL, it contains the information of whether or
2663 /// not AddrInst has to be folded into the addressing mode on success.
2664 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2665 /// because it has been moved away.
2666 /// Thus AddrInst must not be added in the matched instructions.
2667 /// This state can happen when AddrInst is a sext, since it may be moved away.
2668 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2669 /// not be referenced anymore.
2670 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2673 // Avoid exponential behavior on extremely deep expression trees.
2674 if (Depth >= 5) return false;
2676 // By default, all matched instructions stay in place.
2681 case Instruction::PtrToInt:
2682 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2683 return MatchAddr(AddrInst->getOperand(0), Depth);
2684 case Instruction::IntToPtr: {
2685 auto AS = AddrInst->getType()->getPointerAddressSpace();
2686 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
2687 // This inttoptr is a no-op if the integer type is pointer sized.
2688 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
2689 return MatchAddr(AddrInst->getOperand(0), Depth);
2692 case Instruction::BitCast:
2693 // BitCast is always a noop, and we can handle it as long as it is
2694 // int->int or pointer->pointer (we don't want int<->fp or something).
2695 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2696 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2697 // Don't touch identity bitcasts. These were probably put here by LSR,
2698 // and we don't want to mess around with them. Assume it knows what it
2700 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2701 return MatchAddr(AddrInst->getOperand(0), Depth);
2703 case Instruction::AddrSpaceCast: {
2705 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2706 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2707 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2708 return MatchAddr(AddrInst->getOperand(0), Depth);
2711 case Instruction::Add: {
2712 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2713 ExtAddrMode BackupAddrMode = AddrMode;
2714 unsigned OldSize = AddrModeInsts.size();
2715 // Start a transaction at this point.
2716 // The LHS may match but not the RHS.
2717 // Therefore, we need a higher level restoration point to undo partially
2718 // matched operation.
2719 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2720 TPT.getRestorationPoint();
2722 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2723 MatchAddr(AddrInst->getOperand(0), Depth+1))
2726 // Restore the old addr mode info.
2727 AddrMode = BackupAddrMode;
2728 AddrModeInsts.resize(OldSize);
2729 TPT.rollback(LastKnownGood);
2731 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2732 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2733 MatchAddr(AddrInst->getOperand(1), Depth+1))
2736 // Otherwise we definitely can't merge the ADD in.
2737 AddrMode = BackupAddrMode;
2738 AddrModeInsts.resize(OldSize);
2739 TPT.rollback(LastKnownGood);
2742 //case Instruction::Or:
2743 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2745 case Instruction::Mul:
2746 case Instruction::Shl: {
2747 // Can only handle X*C and X << C.
2748 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2751 int64_t Scale = RHS->getSExtValue();
2752 if (Opcode == Instruction::Shl)
2753 Scale = 1LL << Scale;
2755 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2757 case Instruction::GetElementPtr: {
2758 // Scan the GEP. We check it if it contains constant offsets and at most
2759 // one variable offset.
2760 int VariableOperand = -1;
2761 unsigned VariableScale = 0;
2763 int64_t ConstantOffset = 0;
2764 gep_type_iterator GTI = gep_type_begin(AddrInst);
2765 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2766 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2767 const StructLayout *SL = DL.getStructLayout(STy);
2769 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2770 ConstantOffset += SL->getElementOffset(Idx);
2772 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
2773 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2774 ConstantOffset += CI->getSExtValue()*TypeSize;
2775 } else if (TypeSize) { // Scales of zero don't do anything.
2776 // We only allow one variable index at the moment.
2777 if (VariableOperand != -1)
2780 // Remember the variable index.
2781 VariableOperand = i;
2782 VariableScale = TypeSize;
2787 // A common case is for the GEP to only do a constant offset. In this case,
2788 // just add it to the disp field and check validity.
2789 if (VariableOperand == -1) {
2790 AddrMode.BaseOffs += ConstantOffset;
2791 if (ConstantOffset == 0 ||
2792 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
2793 // Check to see if we can fold the base pointer in too.
2794 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2797 AddrMode.BaseOffs -= ConstantOffset;
2801 // Save the valid addressing mode in case we can't match.
2802 ExtAddrMode BackupAddrMode = AddrMode;
2803 unsigned OldSize = AddrModeInsts.size();
2805 // See if the scale and offset amount is valid for this target.
2806 AddrMode.BaseOffs += ConstantOffset;
2808 // Match the base operand of the GEP.
2809 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2810 // If it couldn't be matched, just stuff the value in a register.
2811 if (AddrMode.HasBaseReg) {
2812 AddrMode = BackupAddrMode;
2813 AddrModeInsts.resize(OldSize);
2816 AddrMode.HasBaseReg = true;
2817 AddrMode.BaseReg = AddrInst->getOperand(0);
2820 // Match the remaining variable portion of the GEP.
2821 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2823 // If it couldn't be matched, try stuffing the base into a register
2824 // instead of matching it, and retrying the match of the scale.
2825 AddrMode = BackupAddrMode;
2826 AddrModeInsts.resize(OldSize);
2827 if (AddrMode.HasBaseReg)
2829 AddrMode.HasBaseReg = true;
2830 AddrMode.BaseReg = AddrInst->getOperand(0);
2831 AddrMode.BaseOffs += ConstantOffset;
2832 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2833 VariableScale, Depth)) {
2834 // If even that didn't work, bail.
2835 AddrMode = BackupAddrMode;
2836 AddrModeInsts.resize(OldSize);
2843 case Instruction::SExt:
2844 case Instruction::ZExt: {
2845 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2849 // Try to move this ext out of the way of the addressing mode.
2850 // Ask for a method for doing so.
2851 TypePromotionHelper::Action TPH =
2852 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
2856 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2857 TPT.getRestorationPoint();
2858 unsigned CreatedInstsCost = 0;
2859 unsigned ExtCost = !TLI.isExtFree(Ext);
2860 Value *PromotedOperand =
2861 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
2862 // SExt has been moved away.
2863 // Thus either it will be rematched later in the recursive calls or it is
2864 // gone. Anyway, we must not fold it into the addressing mode at this point.
2868 // addr = gep base, idx
2870 // promotedOpnd = ext opnd <- no match here
2871 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2872 // addr = gep base, op <- match
2876 assert(PromotedOperand &&
2877 "TypePromotionHelper should have filtered out those cases");
2879 ExtAddrMode BackupAddrMode = AddrMode;
2880 unsigned OldSize = AddrModeInsts.size();
2882 if (!MatchAddr(PromotedOperand, Depth) ||
2883 // The total of the new cost is equals to the cost of the created
2885 // The total of the old cost is equals to the cost of the extension plus
2886 // what we have saved in the addressing mode.
2887 !IsPromotionProfitable(CreatedInstsCost,
2888 ExtCost + (AddrModeInsts.size() - OldSize),
2890 AddrMode = BackupAddrMode;
2891 AddrModeInsts.resize(OldSize);
2892 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2893 TPT.rollback(LastKnownGood);
2902 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2903 /// addressing mode. If Addr can't be added to AddrMode this returns false and
2904 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2905 /// or intptr_t for the target.
2907 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2908 // Start a transaction at this point that we will rollback if the matching
2910 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2911 TPT.getRestorationPoint();
2912 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2913 // Fold in immediates if legal for the target.
2914 AddrMode.BaseOffs += CI->getSExtValue();
2915 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2917 AddrMode.BaseOffs -= CI->getSExtValue();
2918 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2919 // If this is a global variable, try to fold it into the addressing mode.
2920 if (!AddrMode.BaseGV) {
2921 AddrMode.BaseGV = GV;
2922 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2924 AddrMode.BaseGV = nullptr;
2926 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2927 ExtAddrMode BackupAddrMode = AddrMode;
2928 unsigned OldSize = AddrModeInsts.size();
2930 // Check to see if it is possible to fold this operation.
2931 bool MovedAway = false;
2932 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2933 // This instruction may have been move away. If so, there is nothing
2937 // Okay, it's possible to fold this. Check to see if it is actually
2938 // *profitable* to do so. We use a simple cost model to avoid increasing
2939 // register pressure too much.
2940 if (I->hasOneUse() ||
2941 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2942 AddrModeInsts.push_back(I);
2946 // It isn't profitable to do this, roll back.
2947 //cerr << "NOT FOLDING: " << *I;
2948 AddrMode = BackupAddrMode;
2949 AddrModeInsts.resize(OldSize);
2950 TPT.rollback(LastKnownGood);
2952 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2953 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2955 TPT.rollback(LastKnownGood);
2956 } else if (isa<ConstantPointerNull>(Addr)) {
2957 // Null pointer gets folded without affecting the addressing mode.
2961 // Worse case, the target should support [reg] addressing modes. :)
2962 if (!AddrMode.HasBaseReg) {
2963 AddrMode.HasBaseReg = true;
2964 AddrMode.BaseReg = Addr;
2965 // Still check for legality in case the target supports [imm] but not [i+r].
2966 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2968 AddrMode.HasBaseReg = false;
2969 AddrMode.BaseReg = nullptr;
2972 // If the base register is already taken, see if we can do [r+r].
2973 if (AddrMode.Scale == 0) {
2975 AddrMode.ScaledReg = Addr;
2976 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2979 AddrMode.ScaledReg = nullptr;
2982 TPT.rollback(LastKnownGood);
2986 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2987 /// inline asm call are due to memory operands. If so, return true, otherwise
2989 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2990 const TargetMachine &TM) {
2991 const Function *F = CI->getParent()->getParent();
2992 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2993 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
2994 TargetLowering::AsmOperandInfoVector TargetConstraints =
2995 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2996 ImmutableCallSite(CI));
2997 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2998 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3000 // Compute the constraint code and ConstraintType to use.
3001 TLI->ComputeConstraintToUse(OpInfo, SDValue());
3003 // If this asm operand is our Value*, and if it isn't an indirect memory
3004 // operand, we can't fold it!
3005 if (OpInfo.CallOperandVal == OpVal &&
3006 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3007 !OpInfo.isIndirect))
3014 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
3015 /// memory use. If we find an obviously non-foldable instruction, return true.
3016 /// Add the ultimately found memory instructions to MemoryUses.
3017 static bool FindAllMemoryUses(
3019 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3020 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
3021 // If we already considered this instruction, we're done.
3022 if (!ConsideredInsts.insert(I).second)
3025 // If this is an obviously unfoldable instruction, bail out.
3026 if (!MightBeFoldableInst(I))
3029 // Loop over all the uses, recursively processing them.
3030 for (Use &U : I->uses()) {
3031 Instruction *UserI = cast<Instruction>(U.getUser());
3033 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3034 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
3038 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3039 unsigned opNo = U.getOperandNo();
3040 if (opNo == 0) return true; // Storing addr, not into addr.
3041 MemoryUses.push_back(std::make_pair(SI, opNo));
3045 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
3046 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3047 if (!IA) return true;
3049 // If this is a memory operand, we're cool, otherwise bail out.
3050 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
3055 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
3062 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3063 /// the use site that we're folding it into. If so, there is no cost to
3064 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
3065 /// that we know are live at the instruction already.
3066 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3067 Value *KnownLive2) {
3068 // If Val is either of the known-live values, we know it is live!
3069 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
3072 // All values other than instructions and arguments (e.g. constants) are live.
3073 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
3075 // If Val is a constant sized alloca in the entry block, it is live, this is
3076 // true because it is just a reference to the stack/frame pointer, which is
3077 // live for the whole function.
3078 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3079 if (AI->isStaticAlloca())
3082 // Check to see if this value is already used in the memory instruction's
3083 // block. If so, it's already live into the block at the very least, so we
3084 // can reasonably fold it.
3085 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3088 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3089 /// mode of the machine to fold the specified instruction into a load or store
3090 /// that ultimately uses it. However, the specified instruction has multiple
3091 /// uses. Given this, it may actually increase register pressure to fold it
3092 /// into the load. For example, consider this code:
3096 /// use(Y) -> nonload/store
3100 /// In this case, Y has multiple uses, and can be folded into the load of Z
3101 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3102 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3103 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3104 /// number of computations either.
3106 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3107 /// X was live across 'load Z' for other reasons, we actually *would* want to
3108 /// fold the addressing mode in the Z case. This would make Y die earlier.
3109 bool AddressingModeMatcher::
3110 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3111 ExtAddrMode &AMAfter) {
3112 if (IgnoreProfitability) return true;
3114 // AMBefore is the addressing mode before this instruction was folded into it,
3115 // and AMAfter is the addressing mode after the instruction was folded. Get
3116 // the set of registers referenced by AMAfter and subtract out those
3117 // referenced by AMBefore: this is the set of values which folding in this
3118 // address extends the lifetime of.
3120 // Note that there are only two potential values being referenced here,
3121 // BaseReg and ScaleReg (global addresses are always available, as are any
3122 // folded immediates).
3123 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
3125 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3126 // lifetime wasn't extended by adding this instruction.
3127 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3129 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3130 ScaledReg = nullptr;
3132 // If folding this instruction (and it's subexprs) didn't extend any live
3133 // ranges, we're ok with it.
3134 if (!BaseReg && !ScaledReg)
3137 // If all uses of this instruction are ultimately load/store/inlineasm's,
3138 // check to see if their addressing modes will include this instruction. If
3139 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3141 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3142 SmallPtrSet<Instruction*, 16> ConsideredInsts;
3143 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
3144 return false; // Has a non-memory, non-foldable use!
3146 // Now that we know that all uses of this instruction are part of a chain of
3147 // computation involving only operations that could theoretically be folded
3148 // into a memory use, loop over each of these uses and see if they could
3149 // *actually* fold the instruction.
3150 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3151 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3152 Instruction *User = MemoryUses[i].first;
3153 unsigned OpNo = MemoryUses[i].second;
3155 // Get the access type of this use. If the use isn't a pointer, we don't
3156 // know what it accesses.
3157 Value *Address = User->getOperand(OpNo);
3158 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3161 Type *AddressAccessTy = AddrTy->getElementType();
3162 unsigned AS = AddrTy->getAddressSpace();
3164 // Do a match against the root of this address, ignoring profitability. This
3165 // will tell us if the addressing mode for the memory operation will
3166 // *actually* cover the shared instruction.
3168 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3169 TPT.getRestorationPoint();
3170 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
3171 MemoryInst, Result, InsertedInsts,
3172 PromotedInsts, TPT);
3173 Matcher.IgnoreProfitability = true;
3174 bool Success = Matcher.MatchAddr(Address, 0);
3175 (void)Success; assert(Success && "Couldn't select *anything*?");
3177 // The match was to check the profitability, the changes made are not
3178 // part of the original matcher. Therefore, they should be dropped
3179 // otherwise the original matcher will not present the right state.
3180 TPT.rollback(LastKnownGood);
3182 // If the match didn't cover I, then it won't be shared by it.
3183 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3184 I) == MatchedAddrModeInsts.end())
3187 MatchedAddrModeInsts.clear();
3193 } // end anonymous namespace
3195 /// IsNonLocalValue - Return true if the specified values are defined in a
3196 /// different basic block than BB.
3197 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3198 if (Instruction *I = dyn_cast<Instruction>(V))
3199 return I->getParent() != BB;
3203 /// OptimizeMemoryInst - Load and Store Instructions often have
3204 /// addressing modes that can do significant amounts of computation. As such,
3205 /// instruction selection will try to get the load or store to do as much
3206 /// computation as possible for the program. The problem is that isel can only
3207 /// see within a single block. As such, we sink as much legal addressing mode
3208 /// stuff into the block as possible.
3210 /// This method is used to optimize both load/store and inline asms with memory
3212 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
3213 Type *AccessTy, unsigned AddrSpace) {
3216 // Try to collapse single-value PHI nodes. This is necessary to undo
3217 // unprofitable PRE transformations.
3218 SmallVector<Value*, 8> worklist;
3219 SmallPtrSet<Value*, 16> Visited;
3220 worklist.push_back(Addr);
3222 // Use a worklist to iteratively look through PHI nodes, and ensure that
3223 // the addressing mode obtained from the non-PHI roots of the graph
3225 Value *Consensus = nullptr;
3226 unsigned NumUsesConsensus = 0;
3227 bool IsNumUsesConsensusValid = false;
3228 SmallVector<Instruction*, 16> AddrModeInsts;
3229 ExtAddrMode AddrMode;
3230 TypePromotionTransaction TPT;
3231 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3232 TPT.getRestorationPoint();
3233 while (!worklist.empty()) {
3234 Value *V = worklist.back();
3235 worklist.pop_back();
3237 // Break use-def graph loops.
3238 if (!Visited.insert(V).second) {
3239 Consensus = nullptr;
3243 // For a PHI node, push all of its incoming values.
3244 if (PHINode *P = dyn_cast<PHINode>(V)) {
3245 for (Value *IncValue : P->incoming_values())
3246 worklist.push_back(IncValue);
3250 // For non-PHIs, determine the addressing mode being computed.
3251 SmallVector<Instruction*, 16> NewAddrModeInsts;
3252 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
3253 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
3254 InsertedInsts, PromotedInsts, TPT);
3256 // This check is broken into two cases with very similar code to avoid using
3257 // getNumUses() as much as possible. Some values have a lot of uses, so
3258 // calling getNumUses() unconditionally caused a significant compile-time
3262 AddrMode = NewAddrMode;
3263 AddrModeInsts = NewAddrModeInsts;
3265 } else if (NewAddrMode == AddrMode) {
3266 if (!IsNumUsesConsensusValid) {
3267 NumUsesConsensus = Consensus->getNumUses();
3268 IsNumUsesConsensusValid = true;
3271 // Ensure that the obtained addressing mode is equivalent to that obtained
3272 // for all other roots of the PHI traversal. Also, when choosing one
3273 // such root as representative, select the one with the most uses in order
3274 // to keep the cost modeling heuristics in AddressingModeMatcher
3276 unsigned NumUses = V->getNumUses();
3277 if (NumUses > NumUsesConsensus) {
3279 NumUsesConsensus = NumUses;
3280 AddrModeInsts = NewAddrModeInsts;
3285 Consensus = nullptr;
3289 // If the addressing mode couldn't be determined, or if multiple different
3290 // ones were determined, bail out now.
3292 TPT.rollback(LastKnownGood);
3297 // Check to see if any of the instructions supersumed by this addr mode are
3298 // non-local to I's BB.
3299 bool AnyNonLocal = false;
3300 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
3301 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
3307 // If all the instructions matched are already in this BB, don't do anything.
3309 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
3313 // Insert this computation right after this user. Since our caller is
3314 // scanning from the top of the BB to the bottom, reuse of the expr are
3315 // guaranteed to happen later.
3316 IRBuilder<> Builder(MemoryInst);
3318 // Now that we determined the addressing expression we want to use and know
3319 // that we have to sink it into this block. Check to see if we have already
3320 // done this for some other load/store instr in this block. If so, reuse the
3322 Value *&SunkAddr = SunkAddrs[Addr];
3324 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
3325 << *MemoryInst << "\n");
3326 if (SunkAddr->getType() != Addr->getType())
3327 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3328 } else if (AddrSinkUsingGEPs ||
3329 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
3330 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3332 // By default, we use the GEP-based method when AA is used later. This
3333 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3334 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3335 << *MemoryInst << "\n");
3336 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
3337 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3339 // First, find the pointer.
3340 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3341 ResultPtr = AddrMode.BaseReg;
3342 AddrMode.BaseReg = nullptr;
3345 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3346 // We can't add more than one pointer together, nor can we scale a
3347 // pointer (both of which seem meaningless).
3348 if (ResultPtr || AddrMode.Scale != 1)
3351 ResultPtr = AddrMode.ScaledReg;
3355 if (AddrMode.BaseGV) {
3359 ResultPtr = AddrMode.BaseGV;
3362 // If the real base value actually came from an inttoptr, then the matcher
3363 // will look through it and provide only the integer value. In that case,
3365 if (!ResultPtr && AddrMode.BaseReg) {
3367 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3368 AddrMode.BaseReg = nullptr;
3369 } else if (!ResultPtr && AddrMode.Scale == 1) {
3371 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3376 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3377 SunkAddr = Constant::getNullValue(Addr->getType());
3378 } else if (!ResultPtr) {
3382 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3383 Type *I8Ty = Builder.getInt8Ty();
3385 // Start with the base register. Do this first so that subsequent address
3386 // matching finds it last, which will prevent it from trying to match it
3387 // as the scaled value in case it happens to be a mul. That would be
3388 // problematic if we've sunk a different mul for the scale, because then
3389 // we'd end up sinking both muls.
3390 if (AddrMode.BaseReg) {
3391 Value *V = AddrMode.BaseReg;
3392 if (V->getType() != IntPtrTy)
3393 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3398 // Add the scale value.
3399 if (AddrMode.Scale) {
3400 Value *V = AddrMode.ScaledReg;
3401 if (V->getType() == IntPtrTy) {
3403 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3404 cast<IntegerType>(V->getType())->getBitWidth()) {
3405 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3407 // It is only safe to sign extend the BaseReg if we know that the math
3408 // required to create it did not overflow before we extend it. Since
3409 // the original IR value was tossed in favor of a constant back when
3410 // the AddrMode was created we need to bail out gracefully if widths
3411 // do not match instead of extending it.
3412 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3413 if (I && (ResultIndex != AddrMode.BaseReg))
3414 I->eraseFromParent();
3418 if (AddrMode.Scale != 1)
3419 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3422 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3427 // Add in the Base Offset if present.
3428 if (AddrMode.BaseOffs) {
3429 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3431 // We need to add this separately from the scale above to help with
3432 // SDAG consecutive load/store merging.
3433 if (ResultPtr->getType() != I8PtrTy)
3434 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3435 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
3442 SunkAddr = ResultPtr;
3444 if (ResultPtr->getType() != I8PtrTy)
3445 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3446 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
3449 if (SunkAddr->getType() != Addr->getType())
3450 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3453 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3454 << *MemoryInst << "\n");
3455 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
3456 Value *Result = nullptr;
3458 // Start with the base register. Do this first so that subsequent address
3459 // matching finds it last, which will prevent it from trying to match it
3460 // as the scaled value in case it happens to be a mul. That would be
3461 // problematic if we've sunk a different mul for the scale, because then
3462 // we'd end up sinking both muls.
3463 if (AddrMode.BaseReg) {
3464 Value *V = AddrMode.BaseReg;
3465 if (V->getType()->isPointerTy())
3466 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3467 if (V->getType() != IntPtrTy)
3468 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3472 // Add the scale value.
3473 if (AddrMode.Scale) {
3474 Value *V = AddrMode.ScaledReg;
3475 if (V->getType() == IntPtrTy) {
3477 } else if (V->getType()->isPointerTy()) {
3478 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3479 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3480 cast<IntegerType>(V->getType())->getBitWidth()) {
3481 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3483 // It is only safe to sign extend the BaseReg if we know that the math
3484 // required to create it did not overflow before we extend it. Since
3485 // the original IR value was tossed in favor of a constant back when
3486 // the AddrMode was created we need to bail out gracefully if widths
3487 // do not match instead of extending it.
3488 Instruction *I = dyn_cast_or_null<Instruction>(Result);
3489 if (I && (Result != AddrMode.BaseReg))
3490 I->eraseFromParent();
3493 if (AddrMode.Scale != 1)
3494 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3497 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3502 // Add in the BaseGV if present.
3503 if (AddrMode.BaseGV) {
3504 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
3506 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3511 // Add in the Base Offset if present.
3512 if (AddrMode.BaseOffs) {
3513 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3515 Result = Builder.CreateAdd(Result, V, "sunkaddr");
3521 SunkAddr = Constant::getNullValue(Addr->getType());
3523 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
3526 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
3528 // If we have no uses, recursively delete the value and all dead instructions
3530 if (Repl->use_empty()) {
3531 // This can cause recursive deletion, which can invalidate our iterator.
3532 // Use a WeakVH to hold onto it in case this happens.
3533 WeakVH IterHandle(CurInstIterator);
3534 BasicBlock *BB = CurInstIterator->getParent();
3536 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
3538 if (IterHandle != CurInstIterator) {
3539 // If the iterator instruction was recursively deleted, start over at the
3540 // start of the block.
3541 CurInstIterator = BB->begin();
3549 /// OptimizeInlineAsmInst - If there are any memory operands, use
3550 /// OptimizeMemoryInst to sink their address computing into the block when
3551 /// possible / profitable.
3552 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
3553 bool MadeChange = false;
3555 const TargetRegisterInfo *TRI =
3556 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
3557 TargetLowering::AsmOperandInfoVector TargetConstraints =
3558 TLI->ParseConstraints(*DL, TRI, CS);
3560 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3561 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3563 // Compute the constraint code and ConstraintType to use.
3564 TLI->ComputeConstraintToUse(OpInfo, SDValue());
3566 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3567 OpInfo.isIndirect) {
3568 Value *OpVal = CS->getArgOperand(ArgNo++);
3569 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
3570 } else if (OpInfo.Type == InlineAsm::isInput)
3577 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3578 /// sign extensions.
3579 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3580 assert(!Inst->use_empty() && "Input must have at least one use");
3581 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3582 bool IsSExt = isa<SExtInst>(FirstUser);
3583 Type *ExtTy = FirstUser->getType();
3584 for (const User *U : Inst->users()) {
3585 const Instruction *UI = cast<Instruction>(U);
3586 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3588 Type *CurTy = UI->getType();
3589 // Same input and output types: Same instruction after CSE.
3593 // If IsSExt is true, we are in this situation:
3595 // b = sext ty1 a to ty2
3596 // c = sext ty1 a to ty3
3597 // Assuming ty2 is shorter than ty3, this could be turned into:
3599 // b = sext ty1 a to ty2
3600 // c = sext ty2 b to ty3
3601 // However, the last sext is not free.
3605 // This is a ZExt, maybe this is free to extend from one type to another.
3606 // In that case, we would not account for a different use.
3609 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3610 CurTy->getScalarType()->getIntegerBitWidth()) {
3618 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3621 // All uses are the same or can be derived from one another for free.
3625 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3626 /// load instruction.
3627 /// If an ext(load) can be formed, it is returned via \p LI for the load
3628 /// and \p Inst for the extension.
3629 /// Otherwise LI == nullptr and Inst == nullptr.
3630 /// When some promotion happened, \p TPT contains the proper state to
3633 /// \return true when promoting was necessary to expose the ext(load)
3634 /// opportunity, false otherwise.
3638 /// %ld = load i32* %addr
3639 /// %add = add nuw i32 %ld, 4
3640 /// %zext = zext i32 %add to i64
3644 /// %ld = load i32* %addr
3645 /// %zext = zext i32 %ld to i64
3646 /// %add = add nuw i64 %zext, 4
3648 /// Thanks to the promotion, we can match zext(load i32*) to i64.
3649 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3650 LoadInst *&LI, Instruction *&Inst,
3651 const SmallVectorImpl<Instruction *> &Exts,
3652 unsigned CreatedInstsCost = 0) {
3653 // Iterate over all the extensions to see if one form an ext(load).
3654 for (auto I : Exts) {
3655 // Check if we directly have ext(load).
3656 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3658 // No promotion happened here.
3661 // Check whether or not we want to do any promotion.
3662 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3664 // Get the action to perform the promotion.
3665 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3666 I, InsertedInsts, *TLI, PromotedInsts);
3667 // Check if we can promote.
3670 // Save the current state.
3671 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3672 TPT.getRestorationPoint();
3673 SmallVector<Instruction *, 4> NewExts;
3674 unsigned NewCreatedInstsCost = 0;
3675 unsigned ExtCost = !TLI->isExtFree(I);
3677 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3678 &NewExts, nullptr, *TLI);
3679 assert(PromotedVal &&
3680 "TypePromotionHelper should have filtered out those cases");
3682 // We would be able to merge only one extension in a load.
3683 // Therefore, if we have more than 1 new extension we heuristically
3684 // cut this search path, because it means we degrade the code quality.
3685 // With exactly 2, the transformation is neutral, because we will merge
3686 // one extension but leave one. However, we optimistically keep going,
3687 // because the new extension may be removed too.
3688 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3689 TotalCreatedInstsCost -= ExtCost;
3690 if (!StressExtLdPromotion &&
3691 (TotalCreatedInstsCost > 1 ||
3692 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
3693 // The promotion is not profitable, rollback to the previous state.
3694 TPT.rollback(LastKnownGood);
3697 // The promotion is profitable.
3698 // Check if it exposes an ext(load).
3699 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3700 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
3701 // If we have created a new extension, i.e., now we have two
3702 // extensions. We must make sure one of them is merged with
3703 // the load, otherwise we may degrade the code quality.
3704 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3705 // Promotion happened.
3707 // If this does not help to expose an ext(load) then, rollback.
3708 TPT.rollback(LastKnownGood);
3710 // None of the extension can form an ext(load).
3716 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3717 /// basic block as the load, unless conditions are unfavorable. This allows
3718 /// SelectionDAG to fold the extend into the load.
3719 /// \p I[in/out] the extension may be modified during the process if some
3720 /// promotions apply.
3722 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3723 // Try to promote a chain of computation if it allows to form
3724 // an extended load.
3725 TypePromotionTransaction TPT;
3726 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3727 TPT.getRestorationPoint();
3728 SmallVector<Instruction *, 1> Exts;
3730 // Look for a load being extended.
3731 LoadInst *LI = nullptr;
3732 Instruction *OldExt = I;
3733 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3735 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3736 "the code must remain the same");
3741 // If they're already in the same block, there's nothing to do.
3742 // Make the cheap checks first if we did not promote.
3743 // If we promoted, we need to check if it is indeed profitable.
3744 if (!HasPromoted && LI->getParent() == I->getParent())
3747 EVT VT = TLI->getValueType(*DL, I->getType());
3748 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
3750 // If the load has other users and the truncate is not free, this probably
3751 // isn't worthwhile.
3752 if (!LI->hasOneUse() && TLI &&
3753 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3754 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3756 TPT.rollback(LastKnownGood);
3760 // Check whether the target supports casts folded into loads.
3762 if (isa<ZExtInst>(I))
3763 LType = ISD::ZEXTLOAD;
3765 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3766 LType = ISD::SEXTLOAD;
3768 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
3770 TPT.rollback(LastKnownGood);
3774 // Move the extend into the same block as the load, so that SelectionDAG
3777 I->removeFromParent();
3783 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3784 BasicBlock *DefBB = I->getParent();
3786 // If the result of a {s|z}ext and its source are both live out, rewrite all
3787 // other uses of the source with result of extension.
3788 Value *Src = I->getOperand(0);
3789 if (Src->hasOneUse())
3792 // Only do this xform if truncating is free.
3793 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3796 // Only safe to perform the optimization if the source is also defined in
3798 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3801 bool DefIsLiveOut = false;
3802 for (User *U : I->users()) {
3803 Instruction *UI = cast<Instruction>(U);
3805 // Figure out which BB this ext is used in.
3806 BasicBlock *UserBB = UI->getParent();
3807 if (UserBB == DefBB) continue;
3808 DefIsLiveOut = true;
3814 // Make sure none of the uses are PHI nodes.
3815 for (User *U : Src->users()) {
3816 Instruction *UI = cast<Instruction>(U);
3817 BasicBlock *UserBB = UI->getParent();
3818 if (UserBB == DefBB) continue;
3819 // Be conservative. We don't want this xform to end up introducing
3820 // reloads just before load / store instructions.
3821 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3825 // InsertedTruncs - Only insert one trunc in each block once.
3826 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3828 bool MadeChange = false;
3829 for (Use &U : Src->uses()) {
3830 Instruction *User = cast<Instruction>(U.getUser());
3832 // Figure out which BB this ext is used in.
3833 BasicBlock *UserBB = User->getParent();
3834 if (UserBB == DefBB) continue;
3836 // Both src and def are live in this block. Rewrite the use.
3837 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3839 if (!InsertedTrunc) {
3840 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3841 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3842 InsertedInsts.insert(InsertedTrunc);
3845 // Replace a use of the {s|z}ext source with a use of the result.
3854 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3855 /// turned into an explicit branch.
3856 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3857 // FIXME: This should use the same heuristics as IfConversion to determine
3858 // whether a select is better represented as a branch. This requires that
3859 // branch probability metadata is preserved for the select, which is not the
3862 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3864 // If the branch is predicted right, an out of order CPU can avoid blocking on
3865 // the compare. Emit cmovs on compares with a memory operand as branches to
3866 // avoid stalls on the load from memory. If the compare has more than one use
3867 // there's probably another cmov or setcc around so it's not worth emitting a
3872 Value *CmpOp0 = Cmp->getOperand(0);
3873 Value *CmpOp1 = Cmp->getOperand(1);
3875 // We check that the memory operand has one use to avoid uses of the loaded
3876 // value directly after the compare, making branches unprofitable.
3877 return Cmp->hasOneUse() &&
3878 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3879 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3883 /// If we have a SelectInst that will likely profit from branch prediction,
3884 /// turn it into a branch.
3885 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3886 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3888 // Can we convert the 'select' to CF ?
3889 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3892 TargetLowering::SelectSupportKind SelectKind;
3894 SelectKind = TargetLowering::VectorMaskSelect;
3895 else if (SI->getType()->isVectorTy())
3896 SelectKind = TargetLowering::ScalarCondVectorVal;
3898 SelectKind = TargetLowering::ScalarValSelect;
3900 // Do we have efficient codegen support for this kind of 'selects' ?
3901 if (TLI->isSelectSupported(SelectKind)) {
3902 // We have efficient codegen support for the select instruction.
3903 // Check if it is profitable to keep this 'select'.
3904 if (!TLI->isPredictableSelectExpensive() ||
3905 !isFormingBranchFromSelectProfitable(SI))
3911 // First, we split the block containing the select into 2 blocks.
3912 BasicBlock *StartBlock = SI->getParent();
3913 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3914 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3916 // Create a new block serving as the landing pad for the branch.
3917 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3918 NextBlock->getParent(), NextBlock);
3920 // Move the unconditional branch from the block with the select in it into our
3921 // landing pad block.
3922 StartBlock->getTerminator()->eraseFromParent();
3923 BranchInst::Create(NextBlock, SmallBlock);
3925 // Insert the real conditional branch based on the original condition.
3926 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3928 // The select itself is replaced with a PHI Node.
3929 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3931 PN->addIncoming(SI->getTrueValue(), StartBlock);
3932 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3933 SI->replaceAllUsesWith(PN);
3934 SI->eraseFromParent();
3936 // Instruct OptimizeBlock to skip to the next block.
3937 CurInstIterator = StartBlock->end();
3938 ++NumSelectsExpanded;
3942 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3943 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3945 for (unsigned i = 0; i < Mask.size(); ++i) {
3946 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3948 SplatElem = Mask[i];
3954 /// Some targets have expensive vector shifts if the lanes aren't all the same
3955 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3956 /// it's often worth sinking a shufflevector splat down to its use so that
3957 /// codegen can spot all lanes are identical.
3958 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3959 BasicBlock *DefBB = SVI->getParent();
3961 // Only do this xform if variable vector shifts are particularly expensive.
3962 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3965 // We only expect better codegen by sinking a shuffle if we can recognise a
3967 if (!isBroadcastShuffle(SVI))
3970 // InsertedShuffles - Only insert a shuffle in each block once.
3971 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3973 bool MadeChange = false;
3974 for (User *U : SVI->users()) {
3975 Instruction *UI = cast<Instruction>(U);
3977 // Figure out which BB this ext is used in.
3978 BasicBlock *UserBB = UI->getParent();
3979 if (UserBB == DefBB) continue;
3981 // For now only apply this when the splat is used by a shift instruction.
3982 if (!UI->isShift()) continue;
3984 // Everything checks out, sink the shuffle if the user's block doesn't
3985 // already have a copy.
3986 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3988 if (!InsertedShuffle) {
3989 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3990 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3992 SVI->getOperand(2), "", InsertPt);
3995 UI->replaceUsesOfWith(SVI, InsertedShuffle);
3999 // If we removed all uses, nuke the shuffle.
4000 if (SVI->use_empty()) {
4001 SVI->eraseFromParent();
4009 /// \brief Helper class to promote a scalar operation to a vector one.
4010 /// This class is used to move downward extractelement transition.
4012 /// a = vector_op <2 x i32>
4013 /// b = extractelement <2 x i32> a, i32 0
4018 /// a = vector_op <2 x i32>
4019 /// c = vector_op a (equivalent to scalar_op on the related lane)
4020 /// * d = extractelement <2 x i32> c, i32 0
4022 /// Assuming both extractelement and store can be combine, we get rid of the
4024 class VectorPromoteHelper {
4025 /// DataLayout associated with the current module.
4026 const DataLayout &DL;
4028 /// Used to perform some checks on the legality of vector operations.
4029 const TargetLowering &TLI;
4031 /// Used to estimated the cost of the promoted chain.
4032 const TargetTransformInfo &TTI;
4034 /// The transition being moved downwards.
4035 Instruction *Transition;
4036 /// The sequence of instructions to be promoted.
4037 SmallVector<Instruction *, 4> InstsToBePromoted;
4038 /// Cost of combining a store and an extract.
4039 unsigned StoreExtractCombineCost;
4040 /// Instruction that will be combined with the transition.
4041 Instruction *CombineInst;
4043 /// \brief The instruction that represents the current end of the transition.
4044 /// Since we are faking the promotion until we reach the end of the chain
4045 /// of computation, we need a way to get the current end of the transition.
4046 Instruction *getEndOfTransition() const {
4047 if (InstsToBePromoted.empty())
4049 return InstsToBePromoted.back();
4052 /// \brief Return the index of the original value in the transition.
4053 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4054 /// c, is at index 0.
4055 unsigned getTransitionOriginalValueIdx() const {
4056 assert(isa<ExtractElementInst>(Transition) &&
4057 "Other kind of transitions are not supported yet");
4061 /// \brief Return the index of the index in the transition.
4062 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4064 unsigned getTransitionIdx() const {
4065 assert(isa<ExtractElementInst>(Transition) &&
4066 "Other kind of transitions are not supported yet");
4070 /// \brief Get the type of the transition.
4071 /// This is the type of the original value.
4072 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4073 /// transition is <2 x i32>.
4074 Type *getTransitionType() const {
4075 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4078 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4079 /// I.e., we have the following sequence:
4080 /// Def = Transition <ty1> a to <ty2>
4081 /// b = ToBePromoted <ty2> Def, ...
4083 /// b = ToBePromoted <ty1> a, ...
4084 /// Def = Transition <ty1> ToBePromoted to <ty2>
4085 void promoteImpl(Instruction *ToBePromoted);
4087 /// \brief Check whether or not it is profitable to promote all the
4088 /// instructions enqueued to be promoted.
4089 bool isProfitableToPromote() {
4090 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4091 unsigned Index = isa<ConstantInt>(ValIdx)
4092 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4094 Type *PromotedType = getTransitionType();
4096 StoreInst *ST = cast<StoreInst>(CombineInst);
4097 unsigned AS = ST->getPointerAddressSpace();
4098 unsigned Align = ST->getAlignment();
4099 // Check if this store is supported.
4100 if (!TLI.allowsMisalignedMemoryAccesses(
4101 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4103 // If this is not supported, there is no way we can combine
4104 // the extract with the store.
4108 // The scalar chain of computation has to pay for the transition
4109 // scalar to vector.
4110 // The vector chain has to account for the combining cost.
4111 uint64_t ScalarCost =
4112 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4113 uint64_t VectorCost = StoreExtractCombineCost;
4114 for (const auto &Inst : InstsToBePromoted) {
4115 // Compute the cost.
4116 // By construction, all instructions being promoted are arithmetic ones.
4117 // Moreover, one argument is a constant that can be viewed as a splat
4119 Value *Arg0 = Inst->getOperand(0);
4120 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4121 isa<ConstantFP>(Arg0);
4122 TargetTransformInfo::OperandValueKind Arg0OVK =
4123 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4124 : TargetTransformInfo::OK_AnyValue;
4125 TargetTransformInfo::OperandValueKind Arg1OVK =
4126 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4127 : TargetTransformInfo::OK_AnyValue;
4128 ScalarCost += TTI.getArithmeticInstrCost(
4129 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4130 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4133 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4134 << ScalarCost << "\nVector: " << VectorCost << '\n');
4135 return ScalarCost > VectorCost;
4138 /// \brief Generate a constant vector with \p Val with the same
4139 /// number of elements as the transition.
4140 /// \p UseSplat defines whether or not \p Val should be replicated
4141 /// accross the whole vector.
4142 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4143 /// otherwise we generate a vector with as many undef as possible:
4144 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4145 /// used at the index of the extract.
4146 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4147 unsigned ExtractIdx = UINT_MAX;
4149 // If we cannot determine where the constant must be, we have to
4150 // use a splat constant.
4151 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4152 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4153 ExtractIdx = CstVal->getSExtValue();
4158 unsigned End = getTransitionType()->getVectorNumElements();
4160 return ConstantVector::getSplat(End, Val);
4162 SmallVector<Constant *, 4> ConstVec;
4163 UndefValue *UndefVal = UndefValue::get(Val->getType());
4164 for (unsigned Idx = 0; Idx != End; ++Idx) {
4165 if (Idx == ExtractIdx)
4166 ConstVec.push_back(Val);
4168 ConstVec.push_back(UndefVal);
4170 return ConstantVector::get(ConstVec);
4173 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4174 /// in \p Use can trigger undefined behavior.
4175 static bool canCauseUndefinedBehavior(const Instruction *Use,
4176 unsigned OperandIdx) {
4177 // This is not safe to introduce undef when the operand is on
4178 // the right hand side of a division-like instruction.
4179 if (OperandIdx != 1)
4181 switch (Use->getOpcode()) {
4184 case Instruction::SDiv:
4185 case Instruction::UDiv:
4186 case Instruction::SRem:
4187 case Instruction::URem:
4189 case Instruction::FDiv:
4190 case Instruction::FRem:
4191 return !Use->hasNoNaNs();
4193 llvm_unreachable(nullptr);
4197 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4198 const TargetTransformInfo &TTI, Instruction *Transition,
4199 unsigned CombineCost)
4200 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
4201 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4202 assert(Transition && "Do not know how to promote null");
4205 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4206 bool canPromote(const Instruction *ToBePromoted) const {
4207 // We could support CastInst too.
4208 return isa<BinaryOperator>(ToBePromoted);
4211 /// \brief Check if it is profitable to promote \p ToBePromoted
4212 /// by moving downward the transition through.
4213 bool shouldPromote(const Instruction *ToBePromoted) const {
4214 // Promote only if all the operands can be statically expanded.
4215 // Indeed, we do not want to introduce any new kind of transitions.
4216 for (const Use &U : ToBePromoted->operands()) {
4217 const Value *Val = U.get();
4218 if (Val == getEndOfTransition()) {
4219 // If the use is a division and the transition is on the rhs,
4220 // we cannot promote the operation, otherwise we may create a
4221 // division by zero.
4222 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4226 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4227 !isa<ConstantFP>(Val))
4230 // Check that the resulting operation is legal.
4231 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4234 return StressStoreExtract ||
4235 TLI.isOperationLegalOrCustom(
4236 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
4239 /// \brief Check whether or not \p Use can be combined
4240 /// with the transition.
4241 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4242 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4244 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4245 void enqueueForPromotion(Instruction *ToBePromoted) {
4246 InstsToBePromoted.push_back(ToBePromoted);
4249 /// \brief Set the instruction that will be combined with the transition.
4250 void recordCombineInstruction(Instruction *ToBeCombined) {
4251 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4252 CombineInst = ToBeCombined;
4255 /// \brief Promote all the instructions enqueued for promotion if it is
4257 /// \return True if the promotion happened, false otherwise.
4259 // Check if there is something to promote.
4260 // Right now, if we do not have anything to combine with,
4261 // we assume the promotion is not profitable.
4262 if (InstsToBePromoted.empty() || !CombineInst)
4266 if (!StressStoreExtract && !isProfitableToPromote())
4270 for (auto &ToBePromoted : InstsToBePromoted)
4271 promoteImpl(ToBePromoted);
4272 InstsToBePromoted.clear();
4276 } // End of anonymous namespace.
4278 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4279 // At this point, we know that all the operands of ToBePromoted but Def
4280 // can be statically promoted.
4281 // For Def, we need to use its parameter in ToBePromoted:
4282 // b = ToBePromoted ty1 a
4283 // Def = Transition ty1 b to ty2
4284 // Move the transition down.
4285 // 1. Replace all uses of the promoted operation by the transition.
4286 // = ... b => = ... Def.
4287 assert(ToBePromoted->getType() == Transition->getType() &&
4288 "The type of the result of the transition does not match "
4290 ToBePromoted->replaceAllUsesWith(Transition);
4291 // 2. Update the type of the uses.
4292 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4293 Type *TransitionTy = getTransitionType();
4294 ToBePromoted->mutateType(TransitionTy);
4295 // 3. Update all the operands of the promoted operation with promoted
4297 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4298 for (Use &U : ToBePromoted->operands()) {
4299 Value *Val = U.get();
4300 Value *NewVal = nullptr;
4301 if (Val == Transition)
4302 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4303 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4304 isa<ConstantFP>(Val)) {
4305 // Use a splat constant if it is not safe to use undef.
4306 NewVal = getConstantVector(
4307 cast<Constant>(Val),
4308 isa<UndefValue>(Val) ||
4309 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4311 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4313 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4315 Transition->removeFromParent();
4316 Transition->insertAfter(ToBePromoted);
4317 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4320 /// Some targets can do store(extractelement) with one instruction.
4321 /// Try to push the extractelement towards the stores when the target
4322 /// has this feature and this is profitable.
4323 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4324 unsigned CombineCost = UINT_MAX;
4325 if (DisableStoreExtract || !TLI ||
4326 (!StressStoreExtract &&
4327 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4328 Inst->getOperand(1), CombineCost)))
4331 // At this point we know that Inst is a vector to scalar transition.
4332 // Try to move it down the def-use chain, until:
4333 // - We can combine the transition with its single use
4334 // => we got rid of the transition.
4335 // - We escape the current basic block
4336 // => we would need to check that we are moving it at a cheaper place and
4337 // we do not do that for now.
4338 BasicBlock *Parent = Inst->getParent();
4339 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4340 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
4341 // If the transition has more than one use, assume this is not going to be
4343 while (Inst->hasOneUse()) {
4344 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4345 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4347 if (ToBePromoted->getParent() != Parent) {
4348 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4349 << ToBePromoted->getParent()->getName()
4350 << ") than the transition (" << Parent->getName() << ").\n");
4354 if (VPH.canCombine(ToBePromoted)) {
4355 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4356 << "will be combined with: " << *ToBePromoted << '\n');
4357 VPH.recordCombineInstruction(ToBePromoted);
4358 bool Changed = VPH.promote();
4359 NumStoreExtractExposed += Changed;
4363 DEBUG(dbgs() << "Try promoting.\n");
4364 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4367 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4369 VPH.enqueueForPromotion(ToBePromoted);
4370 Inst = ToBePromoted;
4375 bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
4376 // Bail out if we inserted the instruction to prevent optimizations from
4377 // stepping on each other's toes.
4378 if (InsertedInsts.count(I))
4381 if (PHINode *P = dyn_cast<PHINode>(I)) {
4382 // It is possible for very late stage optimizations (such as SimplifyCFG)
4383 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4384 // trivial PHI, go ahead and zap it here.
4385 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
4386 P->replaceAllUsesWith(V);
4387 P->eraseFromParent();
4394 if (CastInst *CI = dyn_cast<CastInst>(I)) {
4395 // If the source of the cast is a constant, then this should have
4396 // already been constant folded. The only reason NOT to constant fold
4397 // it is if something (e.g. LSR) was careful to place the constant
4398 // evaluation in a block other than then one that uses it (e.g. to hoist
4399 // the address of globals out of a loop). If this is the case, we don't
4400 // want to forward-subst the cast.
4401 if (isa<Constant>(CI->getOperand(0)))
4404 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
4407 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4408 /// Sink a zext or sext into its user blocks if the target type doesn't
4409 /// fit in one register
4411 TLI->getTypeAction(CI->getContext(),
4412 TLI->getValueType(*DL, CI->getType())) ==
4413 TargetLowering::TypeExpandInteger) {
4414 return SinkCast(CI);
4416 bool MadeChange = MoveExtToFormExtLoad(I);
4417 return MadeChange | OptimizeExtUses(I);
4423 if (CmpInst *CI = dyn_cast<CmpInst>(I))
4424 if (!TLI || !TLI->hasMultipleConditionRegisters())
4425 return OptimizeCmpExpression(CI);
4427 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4429 unsigned AS = LI->getPointerAddressSpace();
4430 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
4435 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4437 unsigned AS = SI->getPointerAddressSpace();
4438 return OptimizeMemoryInst(I, SI->getOperand(1),
4439 SI->getOperand(0)->getType(), AS);
4444 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4446 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4447 BinOp->getOpcode() == Instruction::LShr)) {
4448 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4449 if (TLI && CI && TLI->hasExtractBitsInsn())
4450 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
4455 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4456 if (GEPI->hasAllZeroIndices()) {
4457 /// The GEP operand must be a pointer, so must its result -> BitCast
4458 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4459 GEPI->getName(), GEPI);
4460 GEPI->replaceAllUsesWith(NC);
4461 GEPI->eraseFromParent();
4463 OptimizeInst(NC, ModifiedDT);
4469 if (CallInst *CI = dyn_cast<CallInst>(I))
4470 return OptimizeCallInst(CI, ModifiedDT);
4472 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4473 return OptimizeSelectInst(SI);
4475 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4476 return OptimizeShuffleVectorInst(SVI);
4478 if (isa<ExtractElementInst>(I))
4479 return OptimizeExtractElementInst(I);
4484 // In this pass we look for GEP and cast instructions that are used
4485 // across basic blocks and rewrite them to improve basic-block-at-a-time
4487 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
4489 bool MadeChange = false;
4491 CurInstIterator = BB.begin();
4492 while (CurInstIterator != BB.end()) {
4493 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4497 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4502 // llvm.dbg.value is far away from the value then iSel may not be able
4503 // handle it properly. iSel will drop llvm.dbg.value if it can not
4504 // find a node corresponding to the value.
4505 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4506 bool MadeChange = false;
4507 for (BasicBlock &BB : F) {
4508 Instruction *PrevNonDbgInst = nullptr;
4509 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
4510 Instruction *Insn = BI++;
4511 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
4512 // Leave dbg.values that refer to an alloca alone. These
4513 // instrinsics describe the address of a variable (= the alloca)
4514 // being taken. They should not be moved next to the alloca
4515 // (and to the beginning of the scope), but rather stay close to
4516 // where said address is used.
4517 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
4518 PrevNonDbgInst = Insn;
4522 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4523 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4524 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4525 DVI->removeFromParent();
4526 if (isa<PHINode>(VI))
4527 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4529 DVI->insertAfter(VI);
4538 // If there is a sequence that branches based on comparing a single bit
4539 // against zero that can be combined into a single instruction, and the
4540 // target supports folding these into a single instruction, sink the
4541 // mask and compare into the branch uses. Do this before OptimizeBlock ->
4542 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4544 bool CodeGenPrepare::sinkAndCmp(Function &F) {
4545 if (!EnableAndCmpSinking)
4547 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4549 bool MadeChange = false;
4550 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4551 BasicBlock *BB = I++;
4553 // Does this BB end with the following?
4554 // %andVal = and %val, #single-bit-set
4555 // %icmpVal = icmp %andResult, 0
4556 // br i1 %cmpVal label %dest1, label %dest2"
4557 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4558 if (!Brcc || !Brcc->isConditional())
4560 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4561 if (!Cmp || Cmp->getParent() != BB)
4563 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4564 if (!Zero || !Zero->isZero())
4566 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4567 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4569 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4570 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4572 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4574 // Push the "and; icmp" for any users that are conditional branches.
4575 // Since there can only be one branch use per BB, we don't need to keep
4576 // track of which BBs we insert into.
4577 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4581 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4583 if (!BrccUser || !BrccUser->isConditional())
4585 BasicBlock *UserBB = BrccUser->getParent();
4586 if (UserBB == BB) continue;
4587 DEBUG(dbgs() << "found Brcc use\n");
4589 // Sink the "and; icmp" to use.
4591 BinaryOperator *NewAnd =
4592 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4595 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4599 DEBUG(BrccUser->getParent()->dump());
4605 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4606 /// success, or returns false if no or invalid metadata was found.
4607 static bool extractBranchMetadata(BranchInst *BI,
4608 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4609 assert(BI->isConditional() &&
4610 "Looking for probabilities on unconditional branch?");
4611 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4612 if (!ProfileData || ProfileData->getNumOperands() != 3)
4615 const auto *CITrue =
4616 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4617 const auto *CIFalse =
4618 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4619 if (!CITrue || !CIFalse)
4622 ProbTrue = CITrue->getValue().getZExtValue();
4623 ProbFalse = CIFalse->getValue().getZExtValue();
4628 /// \brief Scale down both weights to fit into uint32_t.
4629 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4630 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4631 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4632 NewTrue = NewTrue / Scale;
4633 NewFalse = NewFalse / Scale;
4636 /// \brief Some targets prefer to split a conditional branch like:
4638 /// %0 = icmp ne i32 %a, 0
4639 /// %1 = icmp ne i32 %b, 0
4640 /// %or.cond = or i1 %0, %1
4641 /// br i1 %or.cond, label %TrueBB, label %FalseBB
4643 /// into multiple branch instructions like:
4646 /// %0 = icmp ne i32 %a, 0
4647 /// br i1 %0, label %TrueBB, label %bb2
4649 /// %1 = icmp ne i32 %b, 0
4650 /// br i1 %1, label %TrueBB, label %FalseBB
4652 /// This usually allows instruction selection to do even further optimizations
4653 /// and combine the compare with the branch instruction. Currently this is
4654 /// applied for targets which have "cheap" jump instructions.
4656 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4658 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4659 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
4662 bool MadeChange = false;
4663 for (auto &BB : F) {
4664 // Does this BB end with the following?
4665 // %cond1 = icmp|fcmp|binary instruction ...
4666 // %cond2 = icmp|fcmp|binary instruction ...
4667 // %cond.or = or|and i1 %cond1, cond2
4668 // br i1 %cond.or label %dest1, label %dest2"
4669 BinaryOperator *LogicOp;
4670 BasicBlock *TBB, *FBB;
4671 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4675 Value *Cond1, *Cond2;
4676 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4677 m_OneUse(m_Value(Cond2)))))
4678 Opc = Instruction::And;
4679 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4680 m_OneUse(m_Value(Cond2)))))
4681 Opc = Instruction::Or;
4685 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4686 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4689 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4692 auto *InsertBefore = std::next(Function::iterator(BB))
4693 .getNodePtrUnchecked();
4694 auto TmpBB = BasicBlock::Create(BB.getContext(),
4695 BB.getName() + ".cond.split",
4696 BB.getParent(), InsertBefore);
4698 // Update original basic block by using the first condition directly by the
4699 // branch instruction and removing the no longer needed and/or instruction.
4700 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4701 Br1->setCondition(Cond1);
4702 LogicOp->eraseFromParent();
4704 // Depending on the conditon we have to either replace the true or the false
4705 // successor of the original branch instruction.
4706 if (Opc == Instruction::And)
4707 Br1->setSuccessor(0, TmpBB);
4709 Br1->setSuccessor(1, TmpBB);
4711 // Fill in the new basic block.
4712 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4713 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4714 I->removeFromParent();
4715 I->insertBefore(Br2);
4718 // Update PHI nodes in both successors. The original BB needs to be
4719 // replaced in one succesor's PHI nodes, because the branch comes now from
4720 // the newly generated BB (NewBB). In the other successor we need to add one
4721 // incoming edge to the PHI nodes, because both branch instructions target
4722 // now the same successor. Depending on the original branch condition
4723 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4724 // we perfrom the correct update for the PHI nodes.
4725 // This doesn't change the successor order of the just created branch
4726 // instruction (or any other instruction).
4727 if (Opc == Instruction::Or)
4728 std::swap(TBB, FBB);
4730 // Replace the old BB with the new BB.
4731 for (auto &I : *TBB) {
4732 PHINode *PN = dyn_cast<PHINode>(&I);
4736 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4737 PN->setIncomingBlock(i, TmpBB);
4740 // Add another incoming edge form the new BB.
4741 for (auto &I : *FBB) {
4742 PHINode *PN = dyn_cast<PHINode>(&I);
4745 auto *Val = PN->getIncomingValueForBlock(&BB);
4746 PN->addIncoming(Val, TmpBB);
4749 // Update the branch weights (from SelectionDAGBuilder::
4750 // FindMergedConditions).
4751 if (Opc == Instruction::Or) {
4752 // Codegen X | Y as:
4761 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4762 // The requirement is that
4763 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4764 // = TrueProb for orignal BB.
4765 // Assuming the orignal weights are A and B, one choice is to set BB1's
4766 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4768 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4769 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4770 // TmpBB, but the math is more complicated.
4771 uint64_t TrueWeight, FalseWeight;
4772 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4773 uint64_t NewTrueWeight = TrueWeight;
4774 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4775 scaleWeights(NewTrueWeight, NewFalseWeight);
4776 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4777 .createBranchWeights(TrueWeight, FalseWeight));
4779 NewTrueWeight = TrueWeight;
4780 NewFalseWeight = 2 * FalseWeight;
4781 scaleWeights(NewTrueWeight, NewFalseWeight);
4782 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4783 .createBranchWeights(TrueWeight, FalseWeight));
4786 // Codegen X & Y as:
4794 // This requires creation of TmpBB after CurBB.
4796 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4797 // The requirement is that
4798 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4799 // = FalseProb for orignal BB.
4800 // Assuming the orignal weights are A and B, one choice is to set BB1's
4801 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4803 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4804 uint64_t TrueWeight, FalseWeight;
4805 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4806 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4807 uint64_t NewFalseWeight = FalseWeight;
4808 scaleWeights(NewTrueWeight, NewFalseWeight);
4809 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4810 .createBranchWeights(TrueWeight, FalseWeight));
4812 NewTrueWeight = 2 * TrueWeight;
4813 NewFalseWeight = FalseWeight;
4814 scaleWeights(NewTrueWeight, NewFalseWeight);
4815 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4816 .createBranchWeights(TrueWeight, FalseWeight));
4820 // Note: No point in getting fancy here, since the DT info is never
4821 // available to CodeGenPrepare.
4826 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();