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/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/MemoryLocation.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstIterator.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/NoFolder.h"
43 #include "llvm/IR/PatternMatch.h"
44 #include "llvm/IR/Statepoint.h"
45 #include "llvm/IR/ValueHandle.h"
46 #include "llvm/IR/ValueMap.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
54 #include "llvm/Transforms/Utils/BuildLibCalls.h"
55 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
59 using namespace llvm::PatternMatch;
61 #define DEBUG_TYPE "codegenprepare"
63 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
64 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
65 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
66 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
68 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
70 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
71 "computations were sunk");
72 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
73 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
74 STATISTIC(NumAndsAdded,
75 "Number of and mask instructions added to form ext loads");
76 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
77 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
78 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
79 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
80 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
81 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
83 static cl::opt<bool> DisableBranchOpts(
84 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
85 cl::desc("Disable branch optimizations in CodeGenPrepare"));
88 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
89 cl::desc("Disable GC optimizations in CodeGenPrepare"));
91 static cl::opt<bool> DisableSelectToBranch(
92 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
93 cl::desc("Disable select to branch conversion."));
95 static cl::opt<bool> AddrSinkUsingGEPs(
96 "addr-sink-using-gep", cl::Hidden, cl::init(false),
97 cl::desc("Address sinking in CGP using GEPs."));
99 static cl::opt<bool> EnableAndCmpSinking(
100 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
101 cl::desc("Enable sinkinig and/cmp into branches."));
103 static cl::opt<bool> DisableStoreExtract(
104 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
105 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
107 static cl::opt<bool> StressStoreExtract(
108 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
109 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
111 static cl::opt<bool> DisableExtLdPromotion(
112 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
113 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
116 static cl::opt<bool> StressExtLdPromotion(
117 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
118 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
119 "optimization in CodeGenPrepare"));
122 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
123 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
124 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
125 class TypePromotionTransaction;
127 class CodeGenPrepare : public FunctionPass {
128 const TargetMachine *TM;
129 const TargetLowering *TLI;
130 const TargetTransformInfo *TTI;
131 const TargetLibraryInfo *TLInfo;
133 /// As we scan instructions optimizing them, this is the next instruction
134 /// to optimize. Transforms that can invalidate this should update it.
135 BasicBlock::iterator CurInstIterator;
137 /// Keeps track of non-local addresses that have been sunk into a block.
138 /// This allows us to avoid inserting duplicate code for blocks with
139 /// multiple load/stores of the same address.
140 ValueMap<Value*, Value*> SunkAddrs;
142 /// Keeps track of all instructions inserted for the current function.
143 SetOfInstrs InsertedInsts;
144 /// Keeps track of the type of the related instruction before their
145 /// promotion for the current function.
146 InstrToOrigTy PromotedInsts;
148 /// True if CFG is modified in any way.
151 /// True if optimizing for size.
154 /// DataLayout for the Function being processed.
155 const DataLayout *DL;
157 // XXX-comment:We need DominatorTree to figure out which instruction to
162 static char ID; // Pass identification, replacement for typeid
163 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
164 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr),
166 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
168 bool runOnFunction(Function &F) override;
170 const char *getPassName() const override { return "CodeGen Prepare"; }
172 void getAnalysisUsage(AnalysisUsage &AU) const override {
173 AU.addPreserved<DominatorTreeWrapperPass>();
174 AU.addRequired<TargetLibraryInfoWrapperPass>();
175 AU.addRequired<TargetTransformInfoWrapperPass>();
176 AU.addRequired<DominatorTreeWrapperPass>();
180 bool eliminateFallThrough(Function &F);
181 bool eliminateMostlyEmptyBlocks(Function &F);
182 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
183 void eliminateMostlyEmptyBlock(BasicBlock *BB);
184 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
185 bool optimizeInst(Instruction *I, bool& ModifiedDT);
186 bool optimizeMemoryInst(Instruction *I, Value *Addr,
187 Type *AccessTy, unsigned AS);
188 bool optimizeInlineAsmInst(CallInst *CS);
189 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
190 bool moveExtToFormExtLoad(Instruction *&I);
191 bool optimizeExtUses(Instruction *I);
192 bool optimizeLoadExt(LoadInst *I);
193 bool optimizeSelectInst(SelectInst *SI);
194 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
195 bool optimizeSwitchInst(SwitchInst *CI);
196 bool optimizeExtractElementInst(Instruction *Inst);
197 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
198 bool placeDbgValues(Function &F);
199 bool sinkAndCmp(Function &F);
200 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
202 const SmallVectorImpl<Instruction *> &Exts,
203 unsigned CreatedInstCost);
204 bool splitBranchCondition(Function &F);
205 bool simplifyOffsetableRelocate(Instruction &I);
206 void stripInvariantGroupMetadata(Instruction &I);
210 char CodeGenPrepare::ID = 0;
211 INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
212 "Optimize for code generation", false, false)
213 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
214 INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
215 "Optimize for code generation", false, false)
217 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
218 return new CodeGenPrepare(TM);
223 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
224 Value* GetUntaintedAddress(Value* CurrentAddress);
226 // The depth we trace down a variable to look for its dependence set.
227 const unsigned kDependenceDepth = 4;
229 // Recursively looks for variables that 'Val' depends on at the given depth
230 // 'Depth', and adds them in 'DepSet'. If 'InsertOnlyLeafNodes' is true, only
231 // inserts the leaf node values; otherwise, all visited nodes are included in
232 // 'DepSet'. Note that constants will be ignored.
233 template <typename SetType>
234 void recursivelyFindDependence(SetType* DepSet, Value* Val,
235 bool InsertOnlyLeafNodes = false,
236 unsigned Depth = kDependenceDepth) {
237 if (Val == nullptr) {
240 if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
244 // Cannot go deeper. Insert the leaf nodes.
245 if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
251 // Go one step further to explore the dependence of the operands.
252 Instruction* I = nullptr;
253 if ((I = dyn_cast<Instruction>(Val))) {
254 if (isa<LoadInst>(I)) {
255 // A load is considerd the leaf load of the dependence tree. Done.
258 } else if (I->isBinaryOp()) {
259 BinaryOperator* I = dyn_cast<BinaryOperator>(Val);
260 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
261 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
262 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes, Depth - 1);
263 } else if (I->isCast()) {
264 Value* Op0 = I->getOperand(0);
265 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
266 } else if (I->getOpcode() == Instruction::Select) {
267 Value* Op0 = I->getOperand(0);
268 Value* Op1 = I->getOperand(1);
269 Value* Op2 = I->getOperand(2);
270 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes, Depth - 1);
271 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes, Depth - 1);
272 recursivelyFindDependence(DepSet, Op2, InsertOnlyLeafNodes, Depth - 1);
273 } else if (I->getOpcode() == Instruction::GetElementPtr) {
274 for (unsigned i = 0; i < I->getNumOperands(); i++) {
275 recursivelyFindDependence(DepSet, I->getOperand(i), InsertOnlyLeafNodes,
278 } else if (I->getOpcode() == Instruction::Store) {
279 auto* SI = dyn_cast<StoreInst>(Val);
280 recursivelyFindDependence(DepSet, SI->getPointerOperand(),
281 InsertOnlyLeafNodes, Depth - 1);
282 recursivelyFindDependence(DepSet, SI->getValueOperand(),
283 InsertOnlyLeafNodes, Depth - 1);
285 Value* Op0 = nullptr;
286 Value* Op1 = nullptr;
287 switch (I->getOpcode()) {
288 case Instruction::ICmp:
289 case Instruction::FCmp: {
290 Op0 = I->getOperand(0);
291 Op1 = I->getOperand(1);
292 recursivelyFindDependence(DepSet, Op0, InsertOnlyLeafNodes,
294 recursivelyFindDependence(DepSet, Op1, InsertOnlyLeafNodes,
298 case Instruction::PHI: {
299 for (int i = 0; i < I->getNumOperands(); i++) {
300 auto* op = I->getOperand(i);
301 if (DepSet->count(op) == 0) {
302 recursivelyFindDependence(DepSet, I->getOperand(i),
303 InsertOnlyLeafNodes, Depth - 1);
309 // Be conservative. Add it and be done with it.
315 } else if (isa<Constant>(Val)) {
316 // Not interested in constant values. Done.
319 // Be conservative. Add it and be done with it.
325 // Helper function to create a Cast instruction.
326 Value* createCast(IRBuilder<true, NoFolder>& Builder, Value* DepVal,
327 Type* TargetIntegerType) {
328 Instruction::CastOps CastOp = Instruction::BitCast;
329 switch (DepVal->getType()->getTypeID()) {
330 case Type::IntegerTyID: {
331 CastOp = Instruction::SExt;
334 case Type::FloatTyID:
335 case Type::DoubleTyID: {
336 CastOp = Instruction::FPToSI;
339 case Type::PointerTyID: {
340 CastOp = Instruction::PtrToInt;
346 return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
349 // Given a value, if it's a tainted address, this function returns the
350 // instruction that ORs the "dependence value" with the "original address".
351 // Otherwise, returns nullptr. This instruction is the first OR instruction
352 // where one of its operand is an AND instruction with an operand being 0.
354 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
355 // %0 = load i32, i32* @y, align 4, !tbaa !1
356 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
357 // %1 = sext i1 %cmp to i32
358 // %2 = ptrtoint i32* @x to i32
359 // %3 = and i32 %1, 0
360 // %4 = or i32 %3, %2
361 // %5 = inttoptr i32 %4 to i32*
362 // store i32 1, i32* %5, align 4
363 Instruction* getOrAddress(Value* CurrentAddress) {
364 // Is it a cast from integer to pointer type.
365 Instruction* OrAddress = nullptr;
366 Instruction* AndDep = nullptr;
367 Instruction* CastToInt = nullptr;
368 Value* ActualAddress = nullptr;
369 Constant* ZeroConst = nullptr;
371 const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
372 if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
373 // Is it an OR instruction: %1 = or %and, %actualAddress.
374 if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
375 OrAddress->getOpcode() == Instruction::Or) {
376 // The first operand should be and AND instruction.
377 AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
378 if (AndDep && AndDep->getOpcode() == Instruction::And) {
379 // Also make sure its first operand of the "AND" is 0, or the "AND" is
380 // marked explicitly by "NoInstCombine".
381 if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
382 ZeroConst->isNullValue()) {
388 // Looks like it's not been tainted.
392 // Given a value, if it's a tainted address, this function returns the
393 // instruction that taints the "dependence value". Otherwise, returns nullptr.
394 // This instruction is the last AND instruction where one of its operand is 0.
395 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
396 // %0 = load i32, i32* @y, align 4, !tbaa !1
397 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
398 // %1 = sext i1 %cmp to i32
399 // %2 = ptrtoint i32* @x to i32
400 // %3 = and i32 %1, 0
401 // %4 = or i32 %3, %2
402 // %5 = inttoptr i32 %4 to i32*
403 // store i32 1, i32* %5, align 4
404 Instruction* getAndDependence(Value* CurrentAddress) {
405 // If 'CurrentAddress' is tainted, get the OR instruction.
406 auto* OrAddress = getOrAddress(CurrentAddress);
407 if (OrAddress == nullptr) {
411 // No need to check the operands.
412 auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
417 // Given a value, if it's a tainted address, this function returns
418 // the "dependence value", which is the first operand in the AND instruction.
419 // E.g., it returns '%1' given 'CurrentAddress' is '%5'.
420 // %0 = load i32, i32* @y, align 4, !tbaa !1
421 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
422 // %1 = sext i1 %cmp to i32
423 // %2 = ptrtoint i32* @x to i32
424 // %3 = and i32 %1, 0
425 // %4 = or i32 %3, %2
426 // %5 = inttoptr i32 %4 to i32*
427 // store i32 1, i32* %5, align 4
428 Value* getDependence(Value* CurrentAddress) {
429 auto* AndInst = getAndDependence(CurrentAddress);
430 if (AndInst == nullptr) {
433 return AndInst->getOperand(0);
436 // Given an address that has been tainted, returns the only condition it depends
437 // on, if any; otherwise, returns nullptr.
438 Value* getConditionDependence(Value* Address) {
439 auto* Dep = getDependence(Address);
440 if (Dep == nullptr) {
441 // 'Address' has not been dependence-tainted.
445 Value* Operand = Dep;
447 auto* Inst = dyn_cast<Instruction>(Operand);
448 if (Inst == nullptr) {
449 // Non-instruction type does not have condition dependence.
452 if (Inst->getOpcode() == Instruction::ICmp) {
455 if (Inst->getNumOperands() != 1) {
458 Operand = Inst->getOperand(0);
464 // Conservatively decides whether the dependence set of 'Val1' includes the
465 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
466 // 'Val2' and use that single value as its dependence set.
467 // If it returns true, it means the dependence set of 'Val1' includes that of
468 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
469 bool dependenceSetInclusion(Value* Val1, Value* Val2,
470 int Val1ExpandLevel = 2 * kDependenceDepth,
471 int Val2ExpandLevel = kDependenceDepth) {
472 typedef SmallSet<Value*, 8> IncludingSet;
473 typedef SmallSet<Value*, 4> IncludedSet;
475 IncludingSet DepSet1;
477 // Look for more depths for the including set.
478 recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
480 recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
483 auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
484 for (auto* Dep : Subset) {
485 if (0 == FullSet.count(Dep)) {
491 bool inclusion = set_inclusion(DepSet1, DepSet2);
492 DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
493 DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
494 DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
495 DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
496 DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
501 // Recursively iterates through the operands spawned from 'DepVal'. If there
502 // exists a single value that 'DepVal' only depends on, we call that value the
503 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
504 Value* getRootDependence(Value* DepVal) {
505 SmallSet<Value*, 8> DepSet;
506 for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
507 recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
509 if (DepSet.size() == 1) {
510 return *DepSet.begin();
517 // This function actually taints 'DepVal' to the address to 'SI'. If the
519 // of 'SI' already depends on whatever 'DepVal' depends on, this function
520 // doesn't do anything and returns false. Otherwise, returns true.
522 // This effect forces the store and any stores that comes later to depend on
523 // 'DepVal'. For example, we have a condition "cond", and a store instruction
524 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
525 // "cond", we do the following:
526 // %conv = sext i1 %cond to i32
527 // %addrVal = ptrtoint i32* %addr to i32
528 // %andCond = and i32 conv, 0;
529 // %orAddr = or i32 %andCond, %addrVal;
530 // %NewAddr = inttoptr i32 %orAddr to i32*;
532 // This is a more concrete example:
534 // %0 = load i32, i32* @y, align 4, !tbaa !1
535 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
536 // %1 = sext i1 %cmp to i32
537 // %2 = ptrtoint i32* @x to i32
538 // %3 = and i32 %1, 0
539 // %4 = or i32 %3, %2
540 // %5 = inttoptr i32 %4 to i32*
541 // store i32 1, i32* %5, align 4
542 bool taintStoreAddress(StoreInst* SI, Value* DepVal) {
543 // Set the insertion point right after the 'DepVal'.
544 Instruction* Inst = nullptr;
545 IRBuilder<true, NoFolder> Builder(SI);
546 BasicBlock* BB = SI->getParent();
547 Value* Address = SI->getPointerOperand();
548 Type* TargetIntegerType =
549 IntegerType::get(Address->getContext(),
550 BB->getModule()->getDataLayout().getPointerSizeInBits());
552 // Does SI's address already depends on whatever 'DepVal' depends on?
553 if (StoreAddressDependOnValue(SI, DepVal)) {
557 // Figure out if there's a root variable 'DepVal' depends on. For example, we
558 // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
559 // to be "%struct* %0" since all other operands are constant.
560 auto* RootVal = getRootDependence(DepVal);
561 auto* RootInst = dyn_cast<Instruction>(RootVal);
562 auto* DepValInst = dyn_cast<Instruction>(DepVal);
563 if (RootInst && DepValInst &&
564 RootInst->getParent() == DepValInst->getParent()) {
568 // Is this already a dependence-tainted store?
569 Value* OldDep = getDependence(Address);
571 // The address of 'SI' has already been tainted. Just need to absorb the
572 // DepVal to the existing dependence in the address of SI.
573 Instruction* AndDep = getAndDependence(Address);
574 IRBuilder<true, NoFolder> Builder(AndDep);
575 Value* NewDep = nullptr;
576 if (DepVal->getType() == AndDep->getType()) {
577 NewDep = Builder.CreateAnd(OldDep, DepVal);
579 NewDep = Builder.CreateAnd(
580 OldDep, createCast(Builder, DepVal, TargetIntegerType));
583 auto* NewDepInst = dyn_cast<Instruction>(NewDep);
585 // Use the new AND instruction as the dependence
586 AndDep->setOperand(0, NewDep);
590 // SI's address has not been tainted. Now taint it with 'DepVal'.
591 Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
592 Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
594 Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
595 auto AndInst = dyn_cast<Instruction>(AndDepVal);
596 // XXX-comment: The original IR InstCombiner would change our and instruction
597 // to a select and then the back end optimize the condition out. We attach a
598 // flag to instructions and set it here to inform the InstCombiner to not to
599 // touch this and instruction at all.
600 Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
601 Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
603 DEBUG(dbgs() << "[taintStoreAddress]\n"
604 << "Original store: " << *SI << '\n');
605 SI->setOperand(1, NewAddr);
608 DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
609 << "\tCast dependence value to integer: " << *CastDepToInt
611 << "\tCast address to integer: " << *PtrToIntCast << '\n'
612 << "\tAnd dependence value: " << *AndDepVal << '\n'
613 << "\tOr address: " << *OrAddr << '\n'
614 << "\tCast or instruction to address: " << *NewAddr << "\n\n");
619 // Looks for the previous store in the if block --- 'BrBB', which makes the
620 // speculative store 'StoreToHoist' safe.
621 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
622 assert(StoreToHoist && "StoreToHoist must be a real store");
624 Value* StorePtr = StoreToHoist->getPointerOperand();
626 // Look for a store to the same pointer in BrBB.
627 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
629 Instruction* CurI = &*RI;
631 StoreInst* SI = dyn_cast<StoreInst>(CurI);
632 // Found the previous store make sure it stores to the same location.
633 // XXX-update: If the previous store's original untainted address are the
634 // same as 'StorePtr', we are also good to hoist the store.
635 if (SI && (SI->getPointerOperand() == StorePtr ||
636 GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
637 // Found the previous store, return its value operand.
643 "We should not reach here since this store is safe to speculate");
646 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
647 // condition already depends on 'DepVal'.
648 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
649 assert(BI->isConditional());
650 auto* Cond = BI->getOperand(0);
651 if (dependenceSetInclusion(Cond, DepVal)) {
652 // The dependence/ordering is self-evident.
656 IRBuilder<true, NoFolder> Builder(BI);
658 Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
660 Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
661 auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
662 BI->setOperand(0, OrCond);
665 DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
670 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
671 assert(BI->isConditional());
672 auto* Cond = BI->getOperand(0);
673 return dependenceSetInclusion(Cond, DepVal);
676 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
677 // the first conditional branch. Returns nullptr if there's no such immediately
678 // following store/branch instructions, which we can only enforce the load with
679 // 'acquire'. 'ChainedBB' contains all the blocks chained together with
680 // unconditional branches from 'BB' to the block with the first store/cond
682 template <typename Vector>
683 Instruction* findFirstStoreCondBranchInst(LoadInst* LI, Vector* ChainedBB) {
684 // In some situations, relaxed loads can be left as is:
685 // 1. The relaxed load is used to calculate the address of the immediate
687 // 2. The relaxed load is used as a condition in the immediate following
688 // condition, and there are no stores in between. This is actually quite
690 // int r1 = x.load(relaxed);
692 // y.store(1, relaxed);
694 // However, in this function, we don't deal with them directly. Instead, we
695 // just find the immediate following store/condition branch and return it.
697 assert(ChainedBB != nullptr && "Chained BB should not be nullptr");
698 auto* BB = LI->getParent();
699 ChainedBB->push_back(BB);
701 auto BBI = BasicBlock::iterator(LI);
704 for (; BBI != BE; BBI++) {
705 auto* Inst = dyn_cast<Instruction>(&*BBI);
706 if (Inst == nullptr) {
709 if (Inst->getOpcode() == Instruction::Store) {
711 } else if (Inst->getOpcode() == Instruction::Br) {
712 auto* BrInst = dyn_cast<BranchInst>(Inst);
713 if (BrInst->isConditional()) {
716 // Reinitialize iterators with the destination of the unconditional
718 BB = BrInst->getSuccessor(0);
719 ChainedBB->push_back(BB);
732 // XXX-comment: Returns whether the code has been changed.
733 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
734 bool Changed = false;
735 for (auto* LI : MonotonicLoadInsts) {
736 SmallVector<BasicBlock*, 2> ChainedBB;
737 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
738 if (FirstInst == nullptr) {
739 // We don't seem to be able to taint a following store/conditional branch
740 // instruction. Simply make it acquire.
741 DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
743 LI->setOrdering(Acquire);
747 // Taint 'FirstInst', which could be a store or a condition branch
749 if (FirstInst->getOpcode() == Instruction::Store) {
750 Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
751 } else if (FirstInst->getOpcode() == Instruction::Br) {
752 Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
754 assert(false && "findFirstStoreCondBranchInst() should return a "
755 "store/condition branch instruction");
761 // Inserts a fake conditional branch right after the instruction 'SplitInst',
762 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
763 // newly created block.
764 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
765 auto* BB = SplitInst->getParent();
766 TerminatorInst* ThenTerm = nullptr;
767 TerminatorInst* ElseTerm = nullptr;
768 SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
769 assert(ThenTerm && ElseTerm &&
770 "Then/Else terminators cannot be empty after basic block spliting");
771 auto* ThenBB = ThenTerm->getParent();
772 auto* ElseBB = ElseTerm->getParent();
773 auto* TailBB = ThenBB->getSingleSuccessor();
774 assert(TailBB && "Tail block cannot be empty after basic block spliting");
776 ThenBB->disableCanEliminateBlock();
777 ThenBB->disableCanEliminateBlock();
778 TailBB->disableCanEliminateBlock();
779 ThenBB->setName(BB->getName() + "Then.Fake");
780 ElseBB->setName(BB->getName() + "Else.Fake");
781 DEBUG(dbgs() << "Add fake conditional branch:\n"
783 << *ThenBB << "Else Block:\n"
787 // Returns true if the code is changed, and false otherwise.
788 void TaintRelaxedLoads(Instruction* UsageInst) {
789 // For better performance, we can add a "AND X 0" instruction before the
791 auto* BB = UsageInst->getParent();
792 auto* InsertPoint = UsageInst->getNextNode();
793 while (dyn_cast<PHINode>(InsertPoint)) {
794 InsertPoint = InsertPoint->getNextNode();
796 IRBuilder<true, NoFolder> Builder(InsertPoint);
797 // First thing is to cast 'UsageInst' to an integer type if necessary.
798 Value* AndTarget = nullptr;
799 if (IntegerType::classof(UsageInst->getType())) {
800 AndTarget = UsageInst;
802 Type* TargetIntegerType = IntegerType::get(
803 UsageInst->getContext(),
804 BB->getModule()->getDataLayout().getPointerSizeInBits());
805 AndTarget = createCast(Builder, UsageInst, TargetIntegerType);
808 auto* AndZero = dyn_cast<Instruction>(
809 Builder.CreateAnd(AndTarget, Constant::getNullValue(AndTarget->getType())));
810 auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
811 CmpInst::ICMP_NE, AndZero, Constant::getNullValue(AndTarget->getType())));
812 AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
815 // XXX-comment: Finds the appropriate Value derived from an atomic load.
816 // 'ChainedBB' contains all the blocks chained together with unconditional
817 // branches from LI's parent BB to the block with the first store/cond branch.
818 // If we don't find any, it means 'LI' is not used at all (which should not
819 // happen in practice). We can simply set 'LI' to be acquire just to be safe.
820 template <typename Vector>
821 Instruction* findMostRecentDependenceUsage(LoadInst* LI, Instruction* LaterInst,
824 typedef SmallSet<Instruction*, 8> UsageSet;
825 typedef DenseMap<BasicBlock*, std::unique_ptr<UsageSet>> UsageMap;
826 assert(ChainedBB->size() >= 1 && "ChainedBB must have >=1 size");
827 // Mapping from basic block in 'ChainedBB' to the set of dependence usage of
828 // 'LI' in each block.
830 auto* LoadBB = LI->getParent();
831 usage_map[LoadBB] = make_unique<UsageSet>();
832 usage_map[LoadBB]->insert(LI);
834 for (auto* BB : *ChainedBB) {
835 if (usage_map[BB] == nullptr) {
836 usage_map[BB] = make_unique<UsageSet>();
838 auto& usage_set = usage_map[BB];
839 if (usage_set->size() == 0) {
840 // The value has not been used.
843 // Calculate the usage in the current BB first.
844 std::list<Value*> bb_usage_list;
845 std::copy(usage_set->begin(), usage_set->end(),
846 std::back_inserter(bb_usage_list));
847 for (auto list_iter = bb_usage_list.begin();
848 list_iter != bb_usage_list.end(); list_iter++) {
849 auto* val = *list_iter;
850 for (auto* U : val->users()) {
851 Instruction* Inst = nullptr;
852 if (!(Inst = dyn_cast<Instruction>(U))) {
855 assert(Inst && "Usage value must be an instruction");
857 std::find(ChainedBB->begin(), ChainedBB->end(), Inst->getParent());
858 if (iter == ChainedBB->end()) {
859 // Only care about usage within ChainedBB.
862 auto* UsageBB = *iter;
865 if (!usage_set->count(Inst)) {
866 bb_usage_list.push_back(Inst);
867 usage_set->insert(Inst);
871 if (usage_map[UsageBB] == nullptr) {
872 usage_map[UsageBB] = make_unique<UsageSet>();
874 usage_map[UsageBB]->insert(Inst);
880 // Pick one usage that is in LaterInst's block and that dominates 'LaterInst'.
881 auto* LaterBB = LaterInst->getParent();
882 auto& usage_set = usage_map[LaterBB];
883 Instruction* usage_inst = nullptr;
884 for (auto* inst : *usage_set) {
885 if (DT->dominates(inst, LaterInst)) {
891 assert(usage_inst && "The usage instruction in the same block but after the "
892 "later instruction");
896 // XXX-comment: Returns whether the code has been changed.
897 bool AddFakeConditionalBranchAfterMonotonicLoads(
898 const SmallVector<LoadInst*, 1>& MonotonicLoadInsts, DominatorTree* DT) {
899 bool Changed = false;
900 for (auto* LI : MonotonicLoadInsts) {
901 SmallVector<BasicBlock*, 2> ChainedBB;
902 auto* FirstInst = findFirstStoreCondBranchInst(LI, &ChainedBB);
903 if (FirstInst != nullptr) {
904 if (FirstInst->getOpcode() == Instruction::Store) {
905 if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
908 } else if (FirstInst->getOpcode() == Instruction::Br) {
909 if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
914 dbgs() << "FirstInst=" << *FirstInst << "\n";
915 assert(false && "findFirstStoreCondBranchInst() should return a "
916 "store/condition branch instruction");
920 // We really need to process the relaxed load now.
921 StoreInst* SI = nullptr;;
922 if (FirstInst && (SI = dyn_cast<StoreInst>(FirstInst))) {
923 // For immediately coming stores, taint the address of the store.
924 if (SI->getParent() == LI->getParent() || DT->dominates(LI, SI)) {
925 Changed |= taintStoreAddress(SI, LI);
928 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
930 LI->setOrdering(Acquire);
933 Changed |= taintStoreAddress(SI, Inst);
937 // No upcoming branch
939 TaintRelaxedLoads(LI);
942 // For immediately coming branch, directly add a fake branch.
943 if (FirstInst->getParent() == LI->getParent() ||
944 DT->dominates(LI, FirstInst)) {
945 TaintRelaxedLoads(LI);
949 findMostRecentDependenceUsage(LI, FirstInst, &ChainedBB, DT);
951 TaintRelaxedLoads(Inst);
953 LI->setOrdering(Acquire);
963 /**** Implementations of public methods for dependence tainting ****/
964 Value* GetUntaintedAddress(Value* CurrentAddress) {
965 auto* OrAddress = getOrAddress(CurrentAddress);
966 if (OrAddress == nullptr) {
967 // Is it tainted by a select instruction?
968 auto* Inst = dyn_cast<Instruction>(CurrentAddress);
969 if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
970 // A selection instruction.
971 if (Inst->getOperand(1) == Inst->getOperand(2)) {
972 return Inst->getOperand(1);
976 return CurrentAddress;
978 Value* ActualAddress = nullptr;
980 auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
981 if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
982 return CastToInt->getOperand(0);
984 // This should be a IntToPtr constant expression.
985 ConstantExpr* PtrToIntExpr =
986 dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
987 if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
988 return PtrToIntExpr->getOperand(0);
992 // Looks like it's not been dependence-tainted. Returns itself.
993 return CurrentAddress;
996 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
998 SI->getAAMetadata(AATags);
999 const auto& DL = SI->getModule()->getDataLayout();
1000 const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
1001 DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
1002 dbgs() << "[GetUntaintedMemoryLocation]\n"
1003 << "Storing address: " << *SI->getPointerOperand()
1004 << "\nUntainted address: " << *OriginalAddr << "\n";
1006 return MemoryLocation(OriginalAddr,
1007 DL.getTypeStoreSize(SI->getValueOperand()->getType()),
1011 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
1012 if (dependenceSetInclusion(SI, DepVal)) {
1016 bool tainted = taintStoreAddress(SI, DepVal);
1021 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
1022 if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
1026 bool tainted = taintStoreAddress(SI, DepVal);
1031 bool CompressTaintedStore(BasicBlock* BB) {
1032 // This function looks for windows of adajcent stores in 'BB' that satisfy the
1033 // following condition (and then do optimization):
1034 // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
1035 // address depends on && Dep(v1) includes Dep(d1);
1036 // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
1037 // address depends on && Dep(v2) includes Dep(d2) &&
1038 // Dep(d2) includes Dep(d1);
1040 // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
1041 // address depends on && Dep(dN) includes Dep(d"N-1").
1043 // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
1044 // safely transform the above to the following. In between these stores, we
1045 // can omit untainted stores to the same address 'Addr' since they internally
1046 // have dependence on the previous stores on the same address.
1051 for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
1052 // Look for the first store in such a window of adajacent stores.
1053 auto* FirstSI = dyn_cast<StoreInst>(&*BI);
1058 // The first store in the window must be tainted.
1059 auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
1060 if (UntaintedAddress == FirstSI->getPointerOperand()) {
1064 // The first store's address must directly depend on and only depend on a
1066 auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
1067 if (nullptr == FirstSIDepCond) {
1071 // Dep(first store's storing value) includes Dep(tainted dependence).
1072 if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
1076 // Look for subsequent stores to the same address that satisfy the condition
1077 // of "compressing the dependence".
1078 SmallVector<StoreInst*, 8> AdajacentStores;
1079 AdajacentStores.push_back(FirstSI);
1080 auto BII = BasicBlock::iterator(FirstSI);
1081 for (BII++; BII != BE; BII++) {
1082 auto* CurrSI = dyn_cast<StoreInst>(&*BII);
1084 if (BII->mayHaveSideEffects()) {
1085 // Be conservative. Instructions with side effects are similar to
1092 auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
1093 auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
1094 // All other stores must satisfy either:
1095 // A. 'CurrSI' is an untainted store to the same address, or
1096 // B. the combination of the following 5 subconditions:
1098 // 2. Untainted address is the same as the group's address;
1099 // 3. The address is tainted with a sole value which is a condition;
1100 // 4. The storing value depends on the condition in 3.
1101 // 5. The condition in 3 depends on the previous stores dependence
1104 // Condition A. Should ignore this store directly.
1105 if (OrigAddress == CurrSI->getPointerOperand() &&
1106 OrigAddress == UntaintedAddress) {
1109 // Check condition B.
1110 Value* Cond = nullptr;
1111 if (OrigAddress == CurrSI->getPointerOperand() ||
1112 OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
1113 !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
1114 // Check condition 1, 2, 3 & 4.
1118 // Check condition 5.
1119 StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
1120 auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
1121 assert(PrevSIDepCond &&
1122 "Store in the group must already depend on a condtion");
1123 if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
1127 AdajacentStores.push_back(CurrSI);
1130 if (AdajacentStores.size() == 1) {
1131 // The outer loop should keep looking from the next store.
1135 // Now we have such a group of tainted stores to the same address.
1136 DEBUG(dbgs() << "[CompressTaintedStore]\n");
1137 DEBUG(dbgs() << "Original BB\n");
1138 DEBUG(dbgs() << *BB << '\n');
1139 auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
1140 for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
1141 auto* SI = AdajacentStores[i];
1143 // Use the original address for stores before the last one.
1144 SI->setOperand(1, UntaintedAddress);
1146 DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
1148 // XXX-comment: Try to make the last store use fewer registers.
1149 // If LastSI's storing value is a select based on the condition with which
1150 // its address is tainted, transform the tainted address to a select
1151 // instruction, as follows:
1152 // r1 = Select Cond ? A : B
1157 // r1 = Select Cond ? A : B
1158 // r2 = Select Cond ? Addr : Addr
1160 // The idea is that both Select instructions depend on the same condition,
1161 // so hopefully the backend can generate two cmov instructions for them (and
1162 // this saves the number of registers needed).
1163 auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
1164 auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
1165 if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
1166 LastSIValue->getOperand(0) == LastSIDep) {
1167 // XXX-comment: Maybe it's better for us to just leave it as an and/or
1168 // dependence pattern.
1170 IRBuilder<true, NoFolder> Builder(LastSI);
1172 Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
1173 LastSI->setOperand(1, Address);
1174 DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1182 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1183 Value* OldDep = getDependence(OldAddress);
1184 // Return false when there's no dependence to pass from the OldAddress.
1189 // No need to pass the dependence to NewStore's address if it already depends
1190 // on whatever 'OldAddress' depends on.
1191 if (StoreAddressDependOnValue(NewStore, OldDep)) {
1194 return taintStoreAddress(NewStore, OldAddress);
1197 SmallSet<Value*, 8> FindDependence(Value* Val) {
1198 SmallSet<Value*, 8> DepSet;
1199 recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1203 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1204 return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1207 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1208 return dependenceSetInclusion(SI, Dep);
1215 bool CodeGenPrepare::runOnFunction(Function &F) {
1216 bool EverMadeChange = false;
1218 if (skipOptnoneFunction(F))
1221 DL = &F.getParent()->getDataLayout();
1223 // Clear per function information.
1224 InsertedInsts.clear();
1225 PromotedInsts.clear();
1229 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1230 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1231 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1232 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1233 OptSize = F.optForSize();
1235 /// This optimization identifies DIV instructions that can be
1236 /// profitably bypassed and carried out with a shorter, faster divide.
1237 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1238 const DenseMap<unsigned int, unsigned int> &BypassWidths =
1239 TLI->getBypassSlowDivWidths();
1240 BasicBlock* BB = &*F.begin();
1241 while (BB != nullptr) {
1242 // bypassSlowDivision may create new BBs, but we don't want to reapply the
1243 // optimization to those blocks.
1244 BasicBlock* Next = BB->getNextNode();
1245 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1250 // Eliminate blocks that contain only PHI nodes and an
1251 // unconditional branch.
1252 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1254 // llvm.dbg.value is far away from the value then iSel may not be able
1255 // handle it properly. iSel will drop llvm.dbg.value if it can not
1256 // find a node corresponding to the value.
1257 EverMadeChange |= placeDbgValues(F);
1259 // If there is a mask, compare against zero, and branch that can be combined
1260 // into a single target instruction, push the mask and compare into branch
1261 // users. Do this before OptimizeBlock -> OptimizeInst ->
1262 // OptimizeCmpExpression, which perturbs the pattern being searched for.
1263 if (!DisableBranchOpts) {
1264 EverMadeChange |= sinkAndCmp(F);
1265 EverMadeChange |= splitBranchCondition(F);
1268 bool MadeChange = true;
1269 while (MadeChange) {
1271 for (Function::iterator I = F.begin(); I != F.end(); ) {
1272 BasicBlock *BB = &*I++;
1273 bool ModifiedDTOnIteration = false;
1274 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1276 // Restart BB iteration if the dominator tree of the Function was changed
1277 if (ModifiedDTOnIteration)
1280 EverMadeChange |= MadeChange;
1285 if (!DisableBranchOpts) {
1287 SmallPtrSet<BasicBlock*, 8> WorkList;
1288 for (BasicBlock &BB : F) {
1289 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1290 MadeChange |= ConstantFoldTerminator(&BB, true);
1291 if (!MadeChange) continue;
1293 for (SmallVectorImpl<BasicBlock*>::iterator
1294 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1295 if (pred_begin(*II) == pred_end(*II))
1296 WorkList.insert(*II);
1299 // Delete the dead blocks and any of their dead successors.
1300 MadeChange |= !WorkList.empty();
1301 while (!WorkList.empty()) {
1302 BasicBlock *BB = *WorkList.begin();
1304 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1306 DeleteDeadBlock(BB);
1308 for (SmallVectorImpl<BasicBlock*>::iterator
1309 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1310 if (pred_begin(*II) == pred_end(*II))
1311 WorkList.insert(*II);
1314 // Merge pairs of basic blocks with unconditional branches, connected by
1316 if (EverMadeChange || MadeChange)
1317 MadeChange |= eliminateFallThrough(F);
1319 EverMadeChange |= MadeChange;
1322 if (!DisableGCOpts) {
1323 SmallVector<Instruction *, 2> Statepoints;
1324 for (BasicBlock &BB : F)
1325 for (Instruction &I : BB)
1326 if (isStatepoint(I))
1327 Statepoints.push_back(&I);
1328 for (auto &I : Statepoints)
1329 EverMadeChange |= simplifyOffsetableRelocate(*I);
1332 // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1333 // further changes done by other passes (e.g., SimplifyCFG).
1334 // Collect all the relaxed loads.
1335 SmallVector<LoadInst*, 1> MonotonicLoadInsts;
1336 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1337 if (I->isAtomic()) {
1338 switch (I->getOpcode()) {
1339 case Instruction::Load: {
1340 auto* LI = dyn_cast<LoadInst>(&*I);
1341 if (LI->getOrdering() == Monotonic) {
1342 MonotonicLoadInsts.push_back(LI);
1353 AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts, DT);
1355 return EverMadeChange;
1358 /// Merge basic blocks which are connected by a single edge, where one of the
1359 /// basic blocks has a single successor pointing to the other basic block,
1360 /// which has a single predecessor.
1361 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1362 bool Changed = false;
1363 // Scan all of the blocks in the function, except for the entry block.
1364 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1365 BasicBlock *BB = &*I++;
1366 // If the destination block has a single pred, then this is a trivial
1367 // edge, just collapse it.
1368 BasicBlock *SinglePred = BB->getSinglePredecessor();
1370 // Don't merge if BB's address is taken.
1371 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1373 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1374 if (Term && !Term->isConditional()) {
1376 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1377 // Remember if SinglePred was the entry block of the function.
1378 // If so, we will need to move BB back to the entry position.
1379 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1380 MergeBasicBlockIntoOnlyPred(BB, nullptr);
1382 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1383 BB->moveBefore(&BB->getParent()->getEntryBlock());
1385 // We have erased a block. Update the iterator.
1386 I = BB->getIterator();
1392 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1393 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1394 /// edges in ways that are non-optimal for isel. Start by eliminating these
1395 /// blocks so we can split them the way we want them.
1396 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1397 bool MadeChange = false;
1398 // Note that this intentionally skips the entry block.
1399 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1400 BasicBlock *BB = &*I++;
1401 // If this block doesn't end with an uncond branch, ignore it.
1402 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1403 if (!BI || !BI->isUnconditional())
1406 // If the instruction before the branch (skipping debug info) isn't a phi
1407 // node, then other stuff is happening here.
1408 BasicBlock::iterator BBI = BI->getIterator();
1409 if (BBI != BB->begin()) {
1411 while (isa<DbgInfoIntrinsic>(BBI)) {
1412 if (BBI == BB->begin())
1416 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1420 // Do not break infinite loops.
1421 BasicBlock *DestBB = BI->getSuccessor(0);
1425 if (!canMergeBlocks(BB, DestBB))
1428 eliminateMostlyEmptyBlock(BB);
1434 /// Return true if we can merge BB into DestBB if there is a single
1435 /// unconditional branch between them, and BB contains no other non-phi
1437 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1438 const BasicBlock *DestBB) const {
1439 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1440 // the successor. If there are more complex condition (e.g. preheaders),
1441 // don't mess around with them.
1442 BasicBlock::const_iterator BBI = BB->begin();
1443 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1444 for (const User *U : PN->users()) {
1445 const Instruction *UI = cast<Instruction>(U);
1446 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1448 // IfUser is inside DestBB block and it is a PHINode then check
1449 // incoming value. If incoming value is not from BB then this is
1450 // a complex condition (e.g. preheaders) we want to avoid here.
1451 if (UI->getParent() == DestBB) {
1452 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1453 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1454 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1455 if (Insn && Insn->getParent() == BB &&
1456 Insn->getParent() != UPN->getIncomingBlock(I))
1463 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1464 // and DestBB may have conflicting incoming values for the block. If so, we
1465 // can't merge the block.
1466 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1467 if (!DestBBPN) return true; // no conflict.
1469 // Collect the preds of BB.
1470 SmallPtrSet<const BasicBlock*, 16> BBPreds;
1471 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1472 // It is faster to get preds from a PHI than with pred_iterator.
1473 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1474 BBPreds.insert(BBPN->getIncomingBlock(i));
1476 BBPreds.insert(pred_begin(BB), pred_end(BB));
1479 // Walk the preds of DestBB.
1480 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1481 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1482 if (BBPreds.count(Pred)) { // Common predecessor?
1483 BBI = DestBB->begin();
1484 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1485 const Value *V1 = PN->getIncomingValueForBlock(Pred);
1486 const Value *V2 = PN->getIncomingValueForBlock(BB);
1488 // If V2 is a phi node in BB, look up what the mapped value will be.
1489 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1490 if (V2PN->getParent() == BB)
1491 V2 = V2PN->getIncomingValueForBlock(Pred);
1493 // If there is a conflict, bail out.
1494 if (V1 != V2) return false;
1503 /// Eliminate a basic block that has only phi's and an unconditional branch in
1505 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1506 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1507 BasicBlock *DestBB = BI->getSuccessor(0);
1509 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1511 // If the destination block has a single pred, then this is a trivial edge,
1512 // just collapse it.
1513 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1514 if (SinglePred != DestBB) {
1515 // Remember if SinglePred was the entry block of the function. If so, we
1516 // will need to move BB back to the entry position.
1517 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1518 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1520 if (isEntry && BB != &BB->getParent()->getEntryBlock())
1521 BB->moveBefore(&BB->getParent()->getEntryBlock());
1523 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1528 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1529 // to handle the new incoming edges it is about to have.
1531 for (BasicBlock::iterator BBI = DestBB->begin();
1532 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1533 // Remove the incoming value for BB, and remember it.
1534 Value *InVal = PN->removeIncomingValue(BB, false);
1536 // Two options: either the InVal is a phi node defined in BB or it is some
1537 // value that dominates BB.
1538 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1539 if (InValPhi && InValPhi->getParent() == BB) {
1540 // Add all of the input values of the input PHI as inputs of this phi.
1541 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1542 PN->addIncoming(InValPhi->getIncomingValue(i),
1543 InValPhi->getIncomingBlock(i));
1545 // Otherwise, add one instance of the dominating value for each edge that
1546 // we will be adding.
1547 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1548 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1549 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1551 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1552 PN->addIncoming(InVal, *PI);
1557 // The PHIs are now updated, change everything that refers to BB to use
1558 // DestBB and remove BB.
1559 BB->replaceAllUsesWith(DestBB);
1560 BB->eraseFromParent();
1563 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1566 // Computes a map of base pointer relocation instructions to corresponding
1567 // derived pointer relocation instructions given a vector of all relocate calls
1568 static void computeBaseDerivedRelocateMap(
1569 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1570 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1572 // Collect information in two maps: one primarily for locating the base object
1573 // while filling the second map; the second map is the final structure holding
1574 // a mapping between Base and corresponding Derived relocate calls
1575 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1576 for (auto *ThisRelocate : AllRelocateCalls) {
1577 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1578 ThisRelocate->getDerivedPtrIndex());
1579 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1581 for (auto &Item : RelocateIdxMap) {
1582 std::pair<unsigned, unsigned> Key = Item.first;
1583 if (Key.first == Key.second)
1584 // Base relocation: nothing to insert
1587 GCRelocateInst *I = Item.second;
1588 auto BaseKey = std::make_pair(Key.first, Key.first);
1590 // We're iterating over RelocateIdxMap so we cannot modify it.
1591 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1592 if (MaybeBase == RelocateIdxMap.end())
1593 // TODO: We might want to insert a new base object relocate and gep off
1594 // that, if there are enough derived object relocates.
1597 RelocateInstMap[MaybeBase->second].push_back(I);
1601 // Accepts a GEP and extracts the operands into a vector provided they're all
1602 // small integer constants
1603 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1604 SmallVectorImpl<Value *> &OffsetV) {
1605 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1606 // Only accept small constant integer operands
1607 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1608 if (!Op || Op->getZExtValue() > 20)
1612 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1613 OffsetV.push_back(GEP->getOperand(i));
1617 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1618 // replace, computes a replacement, and affects it.
1620 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1621 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1622 bool MadeChange = false;
1623 for (GCRelocateInst *ToReplace : Targets) {
1624 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1625 "Not relocating a derived object of the original base object");
1626 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1627 // A duplicate relocate call. TODO: coalesce duplicates.
1631 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1632 // Base and derived relocates are in different basic blocks.
1633 // In this case transform is only valid when base dominates derived
1634 // relocate. However it would be too expensive to check dominance
1635 // for each such relocate, so we skip the whole transformation.
1639 Value *Base = ToReplace->getBasePtr();
1640 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1641 if (!Derived || Derived->getPointerOperand() != Base)
1644 SmallVector<Value *, 2> OffsetV;
1645 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1648 // Create a Builder and replace the target callsite with a gep
1649 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1651 // Insert after RelocatedBase
1652 IRBuilder<> Builder(RelocatedBase->getNextNode());
1653 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1655 // If gc_relocate does not match the actual type, cast it to the right type.
1656 // In theory, there must be a bitcast after gc_relocate if the type does not
1657 // match, and we should reuse it to get the derived pointer. But it could be
1661 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1666 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1670 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1671 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1673 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1674 // no matter there is already one or not. In this way, we can handle all cases, and
1675 // the extra bitcast should be optimized away in later passes.
1676 Value *ActualRelocatedBase = RelocatedBase;
1677 if (RelocatedBase->getType() != Base->getType()) {
1678 ActualRelocatedBase =
1679 Builder.CreateBitCast(RelocatedBase, Base->getType());
1681 Value *Replacement = Builder.CreateGEP(
1682 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1683 Replacement->takeName(ToReplace);
1684 // If the newly generated derived pointer's type does not match the original derived
1685 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1686 Value *ActualReplacement = Replacement;
1687 if (Replacement->getType() != ToReplace->getType()) {
1689 Builder.CreateBitCast(Replacement, ToReplace->getType());
1691 ToReplace->replaceAllUsesWith(ActualReplacement);
1692 ToReplace->eraseFromParent();
1702 // %ptr = gep %base + 15
1703 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1704 // %base' = relocate(%tok, i32 4, i32 4)
1705 // %ptr' = relocate(%tok, i32 4, i32 5)
1706 // %val = load %ptr'
1711 // %ptr = gep %base + 15
1712 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1713 // %base' = gc.relocate(%tok, i32 4, i32 4)
1714 // %ptr' = gep %base' + 15
1715 // %val = load %ptr'
1716 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1717 bool MadeChange = false;
1718 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1720 for (auto *U : I.users())
1721 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1722 // Collect all the relocate calls associated with a statepoint
1723 AllRelocateCalls.push_back(Relocate);
1725 // We need atleast one base pointer relocation + one derived pointer
1726 // relocation to mangle
1727 if (AllRelocateCalls.size() < 2)
1730 // RelocateInstMap is a mapping from the base relocate instruction to the
1731 // corresponding derived relocate instructions
1732 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1733 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1734 if (RelocateInstMap.empty())
1737 for (auto &Item : RelocateInstMap)
1738 // Item.first is the RelocatedBase to offset against
1739 // Item.second is the vector of Targets to replace
1740 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1744 /// SinkCast - Sink the specified cast instruction into its user blocks
1745 static bool SinkCast(CastInst *CI) {
1746 BasicBlock *DefBB = CI->getParent();
1748 /// InsertedCasts - Only insert a cast in each block once.
1749 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1751 bool MadeChange = false;
1752 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1754 Use &TheUse = UI.getUse();
1755 Instruction *User = cast<Instruction>(*UI);
1757 // Figure out which BB this cast is used in. For PHI's this is the
1758 // appropriate predecessor block.
1759 BasicBlock *UserBB = User->getParent();
1760 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1761 UserBB = PN->getIncomingBlock(TheUse);
1764 // Preincrement use iterator so we don't invalidate it.
1767 // If the block selected to receive the cast is an EH pad that does not
1768 // allow non-PHI instructions before the terminator, we can't sink the
1770 if (UserBB->getTerminator()->isEHPad())
1773 // If this user is in the same block as the cast, don't change the cast.
1774 if (UserBB == DefBB) continue;
1776 // If we have already inserted a cast into this block, use it.
1777 CastInst *&InsertedCast = InsertedCasts[UserBB];
1779 if (!InsertedCast) {
1780 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1781 assert(InsertPt != UserBB->end());
1782 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1783 CI->getType(), "", &*InsertPt);
1786 // Replace a use of the cast with a use of the new cast.
1787 TheUse = InsertedCast;
1792 // If we removed all uses, nuke the cast.
1793 if (CI->use_empty()) {
1794 CI->eraseFromParent();
1801 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1802 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1803 /// reduce the number of virtual registers that must be created and coalesced.
1805 /// Return true if any changes are made.
1807 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1808 const DataLayout &DL) {
1809 // If this is a noop copy,
1810 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1811 EVT DstVT = TLI.getValueType(DL, CI->getType());
1813 // This is an fp<->int conversion?
1814 if (SrcVT.isInteger() != DstVT.isInteger())
1817 // If this is an extension, it will be a zero or sign extension, which
1819 if (SrcVT.bitsLT(DstVT)) return false;
1821 // If these values will be promoted, find out what they will be promoted
1822 // to. This helps us consider truncates on PPC as noop copies when they
1824 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1825 TargetLowering::TypePromoteInteger)
1826 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1827 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1828 TargetLowering::TypePromoteInteger)
1829 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1831 // If, after promotion, these are the same types, this is a noop copy.
1835 return SinkCast(CI);
1838 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1841 /// Return true if any changes were made.
1842 static bool CombineUAddWithOverflow(CmpInst *CI) {
1846 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1849 Type *Ty = AddI->getType();
1850 if (!isa<IntegerType>(Ty))
1853 // We don't want to move around uses of condition values this late, so we we
1854 // check if it is legal to create the call to the intrinsic in the basic
1855 // block containing the icmp:
1857 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1861 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1863 if (AddI->hasOneUse())
1864 assert(*AddI->user_begin() == CI && "expected!");
1867 Module *M = CI->getModule();
1868 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1870 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1872 auto *UAddWithOverflow =
1873 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1874 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1876 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1878 CI->replaceAllUsesWith(Overflow);
1879 AddI->replaceAllUsesWith(UAdd);
1880 CI->eraseFromParent();
1881 AddI->eraseFromParent();
1885 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1886 /// registers that must be created and coalesced. This is a clear win except on
1887 /// targets with multiple condition code registers (PowerPC), where it might
1888 /// lose; some adjustment may be wanted there.
1890 /// Return true if any changes are made.
1891 static bool SinkCmpExpression(CmpInst *CI) {
1892 BasicBlock *DefBB = CI->getParent();
1894 /// Only insert a cmp in each block once.
1895 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1897 bool MadeChange = false;
1898 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1900 Use &TheUse = UI.getUse();
1901 Instruction *User = cast<Instruction>(*UI);
1903 // Preincrement use iterator so we don't invalidate it.
1906 // Don't bother for PHI nodes.
1907 if (isa<PHINode>(User))
1910 // Figure out which BB this cmp is used in.
1911 BasicBlock *UserBB = User->getParent();
1913 // If this user is in the same block as the cmp, don't change the cmp.
1914 if (UserBB == DefBB) continue;
1916 // If we have already inserted a cmp into this block, use it.
1917 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1920 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1921 assert(InsertPt != UserBB->end());
1923 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1924 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1927 // Replace a use of the cmp with a use of the new cmp.
1928 TheUse = InsertedCmp;
1933 // If we removed all uses, nuke the cmp.
1934 if (CI->use_empty()) {
1935 CI->eraseFromParent();
1942 static bool OptimizeCmpExpression(CmpInst *CI) {
1943 if (SinkCmpExpression(CI))
1946 if (CombineUAddWithOverflow(CI))
1952 /// Check if the candidates could be combined with a shift instruction, which
1954 /// 1. Truncate instruction
1955 /// 2. And instruction and the imm is a mask of the low bits:
1956 /// imm & (imm+1) == 0
1957 static bool isExtractBitsCandidateUse(Instruction *User) {
1958 if (!isa<TruncInst>(User)) {
1959 if (User->getOpcode() != Instruction::And ||
1960 !isa<ConstantInt>(User->getOperand(1)))
1963 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1965 if ((Cimm & (Cimm + 1)).getBoolValue())
1971 /// Sink both shift and truncate instruction to the use of truncate's BB.
1973 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1974 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1975 const TargetLowering &TLI, const DataLayout &DL) {
1976 BasicBlock *UserBB = User->getParent();
1977 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1978 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1979 bool MadeChange = false;
1981 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1982 TruncE = TruncI->user_end();
1983 TruncUI != TruncE;) {
1985 Use &TruncTheUse = TruncUI.getUse();
1986 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1987 // Preincrement use iterator so we don't invalidate it.
1991 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1995 // If the use is actually a legal node, there will not be an
1996 // implicit truncate.
1997 // FIXME: always querying the result type is just an
1998 // approximation; some nodes' legality is determined by the
1999 // operand or other means. There's no good way to find out though.
2000 if (TLI.isOperationLegalOrCustom(
2001 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2004 // Don't bother for PHI nodes.
2005 if (isa<PHINode>(TruncUser))
2008 BasicBlock *TruncUserBB = TruncUser->getParent();
2010 if (UserBB == TruncUserBB)
2013 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2014 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2016 if (!InsertedShift && !InsertedTrunc) {
2017 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2018 assert(InsertPt != TruncUserBB->end());
2020 if (ShiftI->getOpcode() == Instruction::AShr)
2021 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2024 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2028 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2030 assert(TruncInsertPt != TruncUserBB->end());
2032 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2033 TruncI->getType(), "", &*TruncInsertPt);
2037 TruncTheUse = InsertedTrunc;
2043 /// Sink the shift *right* instruction into user blocks if the uses could
2044 /// potentially be combined with this shift instruction and generate BitExtract
2045 /// instruction. It will only be applied if the architecture supports BitExtract
2046 /// instruction. Here is an example:
2048 /// %x.extract.shift = lshr i64 %arg1, 32
2050 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2054 /// %x.extract.shift.1 = lshr i64 %arg1, 32
2055 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2057 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
2059 /// Return true if any changes are made.
2060 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2061 const TargetLowering &TLI,
2062 const DataLayout &DL) {
2063 BasicBlock *DefBB = ShiftI->getParent();
2065 /// Only insert instructions in each block once.
2066 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2068 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2070 bool MadeChange = false;
2071 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2073 Use &TheUse = UI.getUse();
2074 Instruction *User = cast<Instruction>(*UI);
2075 // Preincrement use iterator so we don't invalidate it.
2078 // Don't bother for PHI nodes.
2079 if (isa<PHINode>(User))
2082 if (!isExtractBitsCandidateUse(User))
2085 BasicBlock *UserBB = User->getParent();
2087 if (UserBB == DefBB) {
2088 // If the shift and truncate instruction are in the same BB. The use of
2089 // the truncate(TruncUse) may still introduce another truncate if not
2090 // legal. In this case, we would like to sink both shift and truncate
2091 // instruction to the BB of TruncUse.
2094 // i64 shift.result = lshr i64 opnd, imm
2095 // trunc.result = trunc shift.result to i16
2098 // ----> We will have an implicit truncate here if the architecture does
2099 // not have i16 compare.
2100 // cmp i16 trunc.result, opnd2
2102 if (isa<TruncInst>(User) && shiftIsLegal
2103 // If the type of the truncate is legal, no trucate will be
2104 // introduced in other basic blocks.
2106 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2108 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2112 // If we have already inserted a shift into this block, use it.
2113 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2115 if (!InsertedShift) {
2116 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2117 assert(InsertPt != UserBB->end());
2119 if (ShiftI->getOpcode() == Instruction::AShr)
2120 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2123 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2129 // Replace a use of the shift with a use of the new shift.
2130 TheUse = InsertedShift;
2133 // If we removed all uses, nuke the shift.
2134 if (ShiftI->use_empty())
2135 ShiftI->eraseFromParent();
2140 // Translate a masked load intrinsic like
2141 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
2142 // <16 x i1> %mask, <16 x i32> %passthru)
2143 // to a chain of basic blocks, with loading element one-by-one if
2144 // the appropriate mask bit is set
2146 // %1 = bitcast i8* %addr to i32*
2147 // %2 = extractelement <16 x i1> %mask, i32 0
2148 // %3 = icmp eq i1 %2, true
2149 // br i1 %3, label %cond.load, label %else
2151 //cond.load: ; preds = %0
2152 // %4 = getelementptr i32* %1, i32 0
2153 // %5 = load i32* %4
2154 // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
2157 //else: ; preds = %0, %cond.load
2158 // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
2159 // %7 = extractelement <16 x i1> %mask, i32 1
2160 // %8 = icmp eq i1 %7, true
2161 // br i1 %8, label %cond.load1, label %else2
2163 //cond.load1: ; preds = %else
2164 // %9 = getelementptr i32* %1, i32 1
2165 // %10 = load i32* %9
2166 // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
2169 //else2: ; preds = %else, %cond.load1
2170 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2171 // %12 = extractelement <16 x i1> %mask, i32 2
2172 // %13 = icmp eq i1 %12, true
2173 // br i1 %13, label %cond.load4, label %else5
2175 static void ScalarizeMaskedLoad(CallInst *CI) {
2176 Value *Ptr = CI->getArgOperand(0);
2177 Value *Alignment = CI->getArgOperand(1);
2178 Value *Mask = CI->getArgOperand(2);
2179 Value *Src0 = CI->getArgOperand(3);
2181 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2182 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2183 assert(VecType && "Unexpected return type of masked load intrinsic");
2185 Type *EltTy = CI->getType()->getVectorElementType();
2187 IRBuilder<> Builder(CI->getContext());
2188 Instruction *InsertPt = CI;
2189 BasicBlock *IfBlock = CI->getParent();
2190 BasicBlock *CondBlock = nullptr;
2191 BasicBlock *PrevIfBlock = CI->getParent();
2193 Builder.SetInsertPoint(InsertPt);
2194 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2196 // Short-cut if the mask is all-true.
2197 bool IsAllOnesMask = isa<Constant>(Mask) &&
2198 cast<Constant>(Mask)->isAllOnesValue();
2200 if (IsAllOnesMask) {
2201 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2202 CI->replaceAllUsesWith(NewI);
2203 CI->eraseFromParent();
2207 // Adjust alignment for the scalar instruction.
2208 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2209 // Bitcast %addr fron i8* to EltTy*
2211 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2212 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2213 unsigned VectorWidth = VecType->getNumElements();
2215 Value *UndefVal = UndefValue::get(VecType);
2217 // The result vector
2218 Value *VResult = UndefVal;
2220 if (isa<ConstantVector>(Mask)) {
2221 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2222 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2225 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2226 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2227 VResult = Builder.CreateInsertElement(VResult, Load,
2228 Builder.getInt32(Idx));
2230 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2231 CI->replaceAllUsesWith(NewI);
2232 CI->eraseFromParent();
2236 PHINode *Phi = nullptr;
2237 Value *PrevPhi = UndefVal;
2239 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2241 // Fill the "else" block, created in the previous iteration
2243 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2244 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2245 // %to_load = icmp eq i1 %mask_1, true
2246 // br i1 %to_load, label %cond.load, label %else
2249 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2250 Phi->addIncoming(VResult, CondBlock);
2251 Phi->addIncoming(PrevPhi, PrevIfBlock);
2256 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2257 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2258 ConstantInt::get(Predicate->getType(), 1));
2260 // Create "cond" block
2262 // %EltAddr = getelementptr i32* %1, i32 0
2263 // %Elt = load i32* %EltAddr
2264 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2266 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2267 Builder.SetInsertPoint(InsertPt);
2270 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2271 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2272 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2274 // Create "else" block, fill it in the next iteration
2275 BasicBlock *NewIfBlock =
2276 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2277 Builder.SetInsertPoint(InsertPt);
2278 Instruction *OldBr = IfBlock->getTerminator();
2279 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2280 OldBr->eraseFromParent();
2281 PrevIfBlock = IfBlock;
2282 IfBlock = NewIfBlock;
2285 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2286 Phi->addIncoming(VResult, CondBlock);
2287 Phi->addIncoming(PrevPhi, PrevIfBlock);
2288 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2289 CI->replaceAllUsesWith(NewI);
2290 CI->eraseFromParent();
2293 // Translate a masked store intrinsic, like
2294 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2296 // to a chain of basic blocks, that stores element one-by-one if
2297 // the appropriate mask bit is set
2299 // %1 = bitcast i8* %addr to i32*
2300 // %2 = extractelement <16 x i1> %mask, i32 0
2301 // %3 = icmp eq i1 %2, true
2302 // br i1 %3, label %cond.store, label %else
2304 // cond.store: ; preds = %0
2305 // %4 = extractelement <16 x i32> %val, i32 0
2306 // %5 = getelementptr i32* %1, i32 0
2307 // store i32 %4, i32* %5
2310 // else: ; preds = %0, %cond.store
2311 // %6 = extractelement <16 x i1> %mask, i32 1
2312 // %7 = icmp eq i1 %6, true
2313 // br i1 %7, label %cond.store1, label %else2
2315 // cond.store1: ; preds = %else
2316 // %8 = extractelement <16 x i32> %val, i32 1
2317 // %9 = getelementptr i32* %1, i32 1
2318 // store i32 %8, i32* %9
2321 static void ScalarizeMaskedStore(CallInst *CI) {
2322 Value *Src = CI->getArgOperand(0);
2323 Value *Ptr = CI->getArgOperand(1);
2324 Value *Alignment = CI->getArgOperand(2);
2325 Value *Mask = CI->getArgOperand(3);
2327 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2328 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2329 assert(VecType && "Unexpected data type in masked store intrinsic");
2331 Type *EltTy = VecType->getElementType();
2333 IRBuilder<> Builder(CI->getContext());
2334 Instruction *InsertPt = CI;
2335 BasicBlock *IfBlock = CI->getParent();
2336 Builder.SetInsertPoint(InsertPt);
2337 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2339 // Short-cut if the mask is all-true.
2340 bool IsAllOnesMask = isa<Constant>(Mask) &&
2341 cast<Constant>(Mask)->isAllOnesValue();
2343 if (IsAllOnesMask) {
2344 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2345 CI->eraseFromParent();
2349 // Adjust alignment for the scalar instruction.
2350 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2351 // Bitcast %addr fron i8* to EltTy*
2353 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2354 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2355 unsigned VectorWidth = VecType->getNumElements();
2357 if (isa<ConstantVector>(Mask)) {
2358 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2359 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2361 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2363 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2364 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2366 CI->eraseFromParent();
2370 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2372 // Fill the "else" block, created in the previous iteration
2374 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2375 // %to_store = icmp eq i1 %mask_1, true
2376 // br i1 %to_store, label %cond.store, label %else
2378 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2379 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2380 ConstantInt::get(Predicate->getType(), 1));
2382 // Create "cond" block
2384 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
2385 // %EltAddr = getelementptr i32* %1, i32 0
2386 // %store i32 %OneElt, i32* %EltAddr
2388 BasicBlock *CondBlock =
2389 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2390 Builder.SetInsertPoint(InsertPt);
2392 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2394 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2395 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2397 // Create "else" block, fill it in the next iteration
2398 BasicBlock *NewIfBlock =
2399 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2400 Builder.SetInsertPoint(InsertPt);
2401 Instruction *OldBr = IfBlock->getTerminator();
2402 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2403 OldBr->eraseFromParent();
2404 IfBlock = NewIfBlock;
2406 CI->eraseFromParent();
2409 // Translate a masked gather intrinsic like
2410 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2411 // <16 x i1> %Mask, <16 x i32> %Src)
2412 // to a chain of basic blocks, with loading element one-by-one if
2413 // the appropriate mask bit is set
2415 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2416 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2417 // % ToLoad0 = icmp eq i1 % Mask0, true
2418 // br i1 % ToLoad0, label %cond.load, label %else
2421 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2422 // % Load0 = load i32, i32* % Ptr0, align 4
2423 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2427 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2428 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2429 // % ToLoad1 = icmp eq i1 % Mask1, true
2430 // br i1 % ToLoad1, label %cond.load1, label %else2
2433 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2434 // % Load1 = load i32, i32* % Ptr1, align 4
2435 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2438 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2439 // ret <16 x i32> %Result
2440 static void ScalarizeMaskedGather(CallInst *CI) {
2441 Value *Ptrs = CI->getArgOperand(0);
2442 Value *Alignment = CI->getArgOperand(1);
2443 Value *Mask = CI->getArgOperand(2);
2444 Value *Src0 = CI->getArgOperand(3);
2446 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2448 assert(VecType && "Unexpected return type of masked load intrinsic");
2450 IRBuilder<> Builder(CI->getContext());
2451 Instruction *InsertPt = CI;
2452 BasicBlock *IfBlock = CI->getParent();
2453 BasicBlock *CondBlock = nullptr;
2454 BasicBlock *PrevIfBlock = CI->getParent();
2455 Builder.SetInsertPoint(InsertPt);
2456 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2458 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2460 Value *UndefVal = UndefValue::get(VecType);
2462 // The result vector
2463 Value *VResult = UndefVal;
2464 unsigned VectorWidth = VecType->getNumElements();
2466 // Shorten the way if the mask is a vector of constants.
2467 bool IsConstMask = isa<ConstantVector>(Mask);
2470 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2471 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2473 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2474 "Ptr" + Twine(Idx));
2475 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2476 "Load" + Twine(Idx));
2477 VResult = Builder.CreateInsertElement(VResult, Load,
2478 Builder.getInt32(Idx),
2479 "Res" + Twine(Idx));
2481 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2482 CI->replaceAllUsesWith(NewI);
2483 CI->eraseFromParent();
2487 PHINode *Phi = nullptr;
2488 Value *PrevPhi = UndefVal;
2490 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2492 // Fill the "else" block, created in the previous iteration
2494 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
2495 // %ToLoad1 = icmp eq i1 %Mask1, true
2496 // br i1 %ToLoad1, label %cond.load, label %else
2499 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2500 Phi->addIncoming(VResult, CondBlock);
2501 Phi->addIncoming(PrevPhi, PrevIfBlock);
2506 Value *Predicate = Builder.CreateExtractElement(Mask,
2507 Builder.getInt32(Idx),
2508 "Mask" + Twine(Idx));
2509 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2510 ConstantInt::get(Predicate->getType(), 1),
2511 "ToLoad" + Twine(Idx));
2513 // Create "cond" block
2515 // %EltAddr = getelementptr i32* %1, i32 0
2516 // %Elt = load i32* %EltAddr
2517 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2519 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2520 Builder.SetInsertPoint(InsertPt);
2522 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2523 "Ptr" + Twine(Idx));
2524 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2525 "Load" + Twine(Idx));
2526 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2527 "Res" + Twine(Idx));
2529 // Create "else" block, fill it in the next iteration
2530 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2531 Builder.SetInsertPoint(InsertPt);
2532 Instruction *OldBr = IfBlock->getTerminator();
2533 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2534 OldBr->eraseFromParent();
2535 PrevIfBlock = IfBlock;
2536 IfBlock = NewIfBlock;
2539 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2540 Phi->addIncoming(VResult, CondBlock);
2541 Phi->addIncoming(PrevPhi, PrevIfBlock);
2542 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2543 CI->replaceAllUsesWith(NewI);
2544 CI->eraseFromParent();
2547 // Translate a masked scatter intrinsic, like
2548 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2550 // to a chain of basic blocks, that stores element one-by-one if
2551 // the appropriate mask bit is set.
2553 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2554 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2555 // % ToStore0 = icmp eq i1 % Mask0, true
2556 // br i1 %ToStore0, label %cond.store, label %else
2559 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2560 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2561 // store i32 %Elt0, i32* % Ptr0, align 4
2565 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2566 // % ToStore1 = icmp eq i1 % Mask1, true
2567 // br i1 % ToStore1, label %cond.store1, label %else2
2570 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2571 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2572 // store i32 % Elt1, i32* % Ptr1, align 4
2575 static void ScalarizeMaskedScatter(CallInst *CI) {
2576 Value *Src = CI->getArgOperand(0);
2577 Value *Ptrs = CI->getArgOperand(1);
2578 Value *Alignment = CI->getArgOperand(2);
2579 Value *Mask = CI->getArgOperand(3);
2581 assert(isa<VectorType>(Src->getType()) &&
2582 "Unexpected data type in masked scatter intrinsic");
2583 assert(isa<VectorType>(Ptrs->getType()) &&
2584 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2585 "Vector of pointers is expected in masked scatter intrinsic");
2587 IRBuilder<> Builder(CI->getContext());
2588 Instruction *InsertPt = CI;
2589 BasicBlock *IfBlock = CI->getParent();
2590 Builder.SetInsertPoint(InsertPt);
2591 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2593 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2594 unsigned VectorWidth = Src->getType()->getVectorNumElements();
2596 // Shorten the way if the mask is a vector of constants.
2597 bool IsConstMask = isa<ConstantVector>(Mask);
2600 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2601 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2603 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2604 "Elt" + Twine(Idx));
2605 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2606 "Ptr" + Twine(Idx));
2607 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2609 CI->eraseFromParent();
2612 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2613 // Fill the "else" block, created in the previous iteration
2615 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2616 // % ToStore = icmp eq i1 % Mask1, true
2617 // br i1 % ToStore, label %cond.store, label %else
2619 Value *Predicate = Builder.CreateExtractElement(Mask,
2620 Builder.getInt32(Idx),
2621 "Mask" + Twine(Idx));
2623 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2624 ConstantInt::get(Predicate->getType(), 1),
2625 "ToStore" + Twine(Idx));
2627 // Create "cond" block
2629 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2630 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2631 // %store i32 % Elt1, i32* % Ptr1
2633 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2634 Builder.SetInsertPoint(InsertPt);
2636 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2637 "Elt" + Twine(Idx));
2638 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2639 "Ptr" + Twine(Idx));
2640 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2642 // Create "else" block, fill it in the next iteration
2643 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2644 Builder.SetInsertPoint(InsertPt);
2645 Instruction *OldBr = IfBlock->getTerminator();
2646 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2647 OldBr->eraseFromParent();
2648 IfBlock = NewIfBlock;
2650 CI->eraseFromParent();
2653 /// If counting leading or trailing zeros is an expensive operation and a zero
2654 /// input is defined, add a check for zero to avoid calling the intrinsic.
2656 /// We want to transform:
2657 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2661 /// %cmpz = icmp eq i64 %A, 0
2662 /// br i1 %cmpz, label %cond.end, label %cond.false
2664 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2665 /// br label %cond.end
2667 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2669 /// If the transform is performed, return true and set ModifiedDT to true.
2670 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2671 const TargetLowering *TLI,
2672 const DataLayout *DL,
2677 // If a zero input is undefined, it doesn't make sense to despeculate that.
2678 if (match(CountZeros->getOperand(1), m_One()))
2681 // If it's cheap to speculate, there's nothing to do.
2682 auto IntrinsicID = CountZeros->getIntrinsicID();
2683 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2684 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2687 // Only handle legal scalar cases. Anything else requires too much work.
2688 Type *Ty = CountZeros->getType();
2689 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2690 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2693 // The intrinsic will be sunk behind a compare against zero and branch.
2694 BasicBlock *StartBlock = CountZeros->getParent();
2695 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2697 // Create another block after the count zero intrinsic. A PHI will be added
2698 // in this block to select the result of the intrinsic or the bit-width
2699 // constant if the input to the intrinsic is zero.
2700 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2701 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2703 // Set up a builder to create a compare, conditional branch, and PHI.
2704 IRBuilder<> Builder(CountZeros->getContext());
2705 Builder.SetInsertPoint(StartBlock->getTerminator());
2706 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2708 // Replace the unconditional branch that was created by the first split with
2709 // a compare against zero and a conditional branch.
2710 Value *Zero = Constant::getNullValue(Ty);
2711 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2712 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2713 StartBlock->getTerminator()->eraseFromParent();
2715 // Create a PHI in the end block to select either the output of the intrinsic
2716 // or the bit width of the operand.
2717 Builder.SetInsertPoint(&EndBlock->front());
2718 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2719 CountZeros->replaceAllUsesWith(PN);
2720 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2721 PN->addIncoming(BitWidth, StartBlock);
2722 PN->addIncoming(CountZeros, CallBlock);
2724 // We are explicitly handling the zero case, so we can set the intrinsic's
2725 // undefined zero argument to 'true'. This will also prevent reprocessing the
2726 // intrinsic; we only despeculate when a zero input is defined.
2727 CountZeros->setArgOperand(1, Builder.getTrue());
2732 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2733 BasicBlock *BB = CI->getParent();
2735 // Lower inline assembly if we can.
2736 // If we found an inline asm expession, and if the target knows how to
2737 // lower it to normal LLVM code, do so now.
2738 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2739 if (TLI->ExpandInlineAsm(CI)) {
2740 // Avoid invalidating the iterator.
2741 CurInstIterator = BB->begin();
2742 // Avoid processing instructions out of order, which could cause
2743 // reuse before a value is defined.
2747 // Sink address computing for memory operands into the block.
2748 if (optimizeInlineAsmInst(CI))
2752 // Align the pointer arguments to this call if the target thinks it's a good
2754 unsigned MinSize, PrefAlign;
2755 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2756 for (auto &Arg : CI->arg_operands()) {
2757 // We want to align both objects whose address is used directly and
2758 // objects whose address is used in casts and GEPs, though it only makes
2759 // sense for GEPs if the offset is a multiple of the desired alignment and
2760 // if size - offset meets the size threshold.
2761 if (!Arg->getType()->isPointerTy())
2763 APInt Offset(DL->getPointerSizeInBits(
2764 cast<PointerType>(Arg->getType())->getAddressSpace()),
2766 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2767 uint64_t Offset2 = Offset.getLimitedValue();
2768 if ((Offset2 & (PrefAlign-1)) != 0)
2771 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2772 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2773 AI->setAlignment(PrefAlign);
2774 // Global variables can only be aligned if they are defined in this
2775 // object (i.e. they are uniquely initialized in this object), and
2776 // over-aligning global variables that have an explicit section is
2779 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2780 GV->getAlignment() < PrefAlign &&
2781 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2783 GV->setAlignment(PrefAlign);
2785 // If this is a memcpy (or similar) then we may be able to improve the
2787 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2788 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2789 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2790 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2791 if (Align > MI->getAlignment())
2792 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2796 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2798 switch (II->getIntrinsicID()) {
2800 case Intrinsic::objectsize: {
2801 // Lower all uses of llvm.objectsize.*
2802 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2803 Type *ReturnTy = CI->getType();
2804 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2806 // Substituting this can cause recursive simplifications, which can
2807 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2809 WeakVH IterHandle(&*CurInstIterator);
2811 replaceAndRecursivelySimplify(CI, RetVal,
2814 // If the iterator instruction was recursively deleted, start over at the
2815 // start of the block.
2816 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2817 CurInstIterator = BB->begin();
2822 case Intrinsic::masked_load: {
2823 // Scalarize unsupported vector masked load
2824 if (!TTI->isLegalMaskedLoad(CI->getType())) {
2825 ScalarizeMaskedLoad(CI);
2831 case Intrinsic::masked_store: {
2832 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2833 ScalarizeMaskedStore(CI);
2839 case Intrinsic::masked_gather: {
2840 if (!TTI->isLegalMaskedGather(CI->getType())) {
2841 ScalarizeMaskedGather(CI);
2847 case Intrinsic::masked_scatter: {
2848 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2849 ScalarizeMaskedScatter(CI);
2855 case Intrinsic::aarch64_stlxr:
2856 case Intrinsic::aarch64_stxr: {
2857 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2858 if (!ExtVal || !ExtVal->hasOneUse() ||
2859 ExtVal->getParent() == CI->getParent())
2861 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2862 ExtVal->moveBefore(CI);
2863 // Mark this instruction as "inserted by CGP", so that other
2864 // optimizations don't touch it.
2865 InsertedInsts.insert(ExtVal);
2868 case Intrinsic::invariant_group_barrier:
2869 II->replaceAllUsesWith(II->getArgOperand(0));
2870 II->eraseFromParent();
2873 case Intrinsic::cttz:
2874 case Intrinsic::ctlz:
2875 // If counting zeros is expensive, try to avoid it.
2876 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2880 // Unknown address space.
2881 // TODO: Target hook to pick which address space the intrinsic cares
2883 unsigned AddrSpace = ~0u;
2884 SmallVector<Value*, 2> PtrOps;
2886 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2887 while (!PtrOps.empty())
2888 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2893 // From here on out we're working with named functions.
2894 if (!CI->getCalledFunction()) return false;
2896 // Lower all default uses of _chk calls. This is very similar
2897 // to what InstCombineCalls does, but here we are only lowering calls
2898 // to fortified library functions (e.g. __memcpy_chk) that have the default
2899 // "don't know" as the objectsize. Anything else should be left alone.
2900 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2901 if (Value *V = Simplifier.optimizeCall(CI)) {
2902 CI->replaceAllUsesWith(V);
2903 CI->eraseFromParent();
2909 /// Look for opportunities to duplicate return instructions to the predecessor
2910 /// to enable tail call optimizations. The case it is currently looking for is:
2913 /// %tmp0 = tail call i32 @f0()
2914 /// br label %return
2916 /// %tmp1 = tail call i32 @f1()
2917 /// br label %return
2919 /// %tmp2 = tail call i32 @f2()
2920 /// br label %return
2922 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2930 /// %tmp0 = tail call i32 @f0()
2933 /// %tmp1 = tail call i32 @f1()
2936 /// %tmp2 = tail call i32 @f2()
2939 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2943 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
2947 PHINode *PN = nullptr;
2948 BitCastInst *BCI = nullptr;
2949 Value *V = RI->getReturnValue();
2951 BCI = dyn_cast<BitCastInst>(V);
2953 V = BCI->getOperand(0);
2955 PN = dyn_cast<PHINode>(V);
2960 if (PN && PN->getParent() != BB)
2963 // It's not safe to eliminate the sign / zero extension of the return value.
2964 // See llvm::isInTailCallPosition().
2965 const Function *F = BB->getParent();
2966 AttributeSet CallerAttrs = F->getAttributes();
2967 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
2968 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
2971 // Make sure there are no instructions between the PHI and return, or that the
2972 // return is the first instruction in the block.
2974 BasicBlock::iterator BI = BB->begin();
2975 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2977 // Also skip over the bitcast.
2982 BasicBlock::iterator BI = BB->begin();
2983 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2988 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2990 SmallVector<CallInst*, 4> TailCalls;
2992 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2993 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2994 // Make sure the phi value is indeed produced by the tail call.
2995 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2996 TLI->mayBeEmittedAsTailCall(CI))
2997 TailCalls.push_back(CI);
3000 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3001 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
3002 if (!VisitedBBs.insert(*PI).second)
3005 BasicBlock::InstListType &InstList = (*PI)->getInstList();
3006 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
3007 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
3008 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
3012 CallInst *CI = dyn_cast<CallInst>(&*RI);
3013 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
3014 TailCalls.push_back(CI);
3018 bool Changed = false;
3019 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
3020 CallInst *CI = TailCalls[i];
3023 // Conservatively require the attributes of the call to match those of the
3024 // return. Ignore noalias because it doesn't affect the call sequence.
3025 AttributeSet CalleeAttrs = CS.getAttributes();
3026 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3027 removeAttribute(Attribute::NoAlias) !=
3028 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
3029 removeAttribute(Attribute::NoAlias))
3032 // Make sure the call instruction is followed by an unconditional branch to
3033 // the return block.
3034 BasicBlock *CallBB = CI->getParent();
3035 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
3036 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
3039 // Duplicate the return into CallBB.
3040 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
3041 ModifiedDT = Changed = true;
3045 // If we eliminated all predecessors of the block, delete the block now.
3046 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
3047 BB->eraseFromParent();
3052 //===----------------------------------------------------------------------===//
3053 // Memory Optimization
3054 //===----------------------------------------------------------------------===//
3058 /// This is an extended version of TargetLowering::AddrMode
3059 /// which holds actual Value*'s for register values.
3060 struct ExtAddrMode : public TargetLowering::AddrMode {
3063 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
3064 void print(raw_ostream &OS) const;
3067 bool operator==(const ExtAddrMode& O) const {
3068 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
3069 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
3070 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
3075 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3081 void ExtAddrMode::print(raw_ostream &OS) const {
3082 bool NeedPlus = false;
3085 OS << (NeedPlus ? " + " : "")
3087 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3092 OS << (NeedPlus ? " + " : "")
3098 OS << (NeedPlus ? " + " : "")
3100 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3104 OS << (NeedPlus ? " + " : "")
3106 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3112 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3113 void ExtAddrMode::dump() const {
3119 /// \brief This class provides transaction based operation on the IR.
3120 /// Every change made through this class is recorded in the internal state and
3121 /// can be undone (rollback) until commit is called.
3122 class TypePromotionTransaction {
3124 /// \brief This represents the common interface of the individual transaction.
3125 /// Each class implements the logic for doing one specific modification on
3126 /// the IR via the TypePromotionTransaction.
3127 class TypePromotionAction {
3129 /// The Instruction modified.
3133 /// \brief Constructor of the action.
3134 /// The constructor performs the related action on the IR.
3135 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3137 virtual ~TypePromotionAction() {}
3139 /// \brief Undo the modification done by this action.
3140 /// When this method is called, the IR must be in the same state as it was
3141 /// before this action was applied.
3142 /// \pre Undoing the action works if and only if the IR is in the exact same
3143 /// state as it was directly after this action was applied.
3144 virtual void undo() = 0;
3146 /// \brief Advocate every change made by this action.
3147 /// When the results on the IR of the action are to be kept, it is important
3148 /// to call this function, otherwise hidden information may be kept forever.
3149 virtual void commit() {
3150 // Nothing to be done, this action is not doing anything.
3154 /// \brief Utility to remember the position of an instruction.
3155 class InsertionHandler {
3156 /// Position of an instruction.
3157 /// Either an instruction:
3158 /// - Is the first in a basic block: BB is used.
3159 /// - Has a previous instructon: PrevInst is used.
3161 Instruction *PrevInst;
3164 /// Remember whether or not the instruction had a previous instruction.
3165 bool HasPrevInstruction;
3168 /// \brief Record the position of \p Inst.
3169 InsertionHandler(Instruction *Inst) {
3170 BasicBlock::iterator It = Inst->getIterator();
3171 HasPrevInstruction = (It != (Inst->getParent()->begin()));
3172 if (HasPrevInstruction)
3173 Point.PrevInst = &*--It;
3175 Point.BB = Inst->getParent();
3178 /// \brief Insert \p Inst at the recorded position.
3179 void insert(Instruction *Inst) {
3180 if (HasPrevInstruction) {
3181 if (Inst->getParent())
3182 Inst->removeFromParent();
3183 Inst->insertAfter(Point.PrevInst);
3185 Instruction *Position = &*Point.BB->getFirstInsertionPt();
3186 if (Inst->getParent())
3187 Inst->moveBefore(Position);
3189 Inst->insertBefore(Position);
3194 /// \brief Move an instruction before another.
3195 class InstructionMoveBefore : public TypePromotionAction {
3196 /// Original position of the instruction.
3197 InsertionHandler Position;
3200 /// \brief Move \p Inst before \p Before.
3201 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3202 : TypePromotionAction(Inst), Position(Inst) {
3203 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3204 Inst->moveBefore(Before);
3207 /// \brief Move the instruction back to its original position.
3208 void undo() override {
3209 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3210 Position.insert(Inst);
3214 /// \brief Set the operand of an instruction with a new value.
3215 class OperandSetter : public TypePromotionAction {
3216 /// Original operand of the instruction.
3218 /// Index of the modified instruction.
3222 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3223 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3224 : TypePromotionAction(Inst), Idx(Idx) {
3225 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3226 << "for:" << *Inst << "\n"
3227 << "with:" << *NewVal << "\n");
3228 Origin = Inst->getOperand(Idx);
3229 Inst->setOperand(Idx, NewVal);
3232 /// \brief Restore the original value of the instruction.
3233 void undo() override {
3234 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3235 << "for: " << *Inst << "\n"
3236 << "with: " << *Origin << "\n");
3237 Inst->setOperand(Idx, Origin);
3241 /// \brief Hide the operands of an instruction.
3242 /// Do as if this instruction was not using any of its operands.
3243 class OperandsHider : public TypePromotionAction {
3244 /// The list of original operands.
3245 SmallVector<Value *, 4> OriginalValues;
3248 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3249 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3250 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3251 unsigned NumOpnds = Inst->getNumOperands();
3252 OriginalValues.reserve(NumOpnds);
3253 for (unsigned It = 0; It < NumOpnds; ++It) {
3254 // Save the current operand.
3255 Value *Val = Inst->getOperand(It);
3256 OriginalValues.push_back(Val);
3258 // We could use OperandSetter here, but that would imply an overhead
3259 // that we are not willing to pay.
3260 Inst->setOperand(It, UndefValue::get(Val->getType()));
3264 /// \brief Restore the original list of uses.
3265 void undo() override {
3266 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3267 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3268 Inst->setOperand(It, OriginalValues[It]);
3272 /// \brief Build a truncate instruction.
3273 class TruncBuilder : public TypePromotionAction {
3276 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3278 /// trunc Opnd to Ty.
3279 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3280 IRBuilder<> Builder(Opnd);
3281 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3282 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3285 /// \brief Get the built value.
3286 Value *getBuiltValue() { return Val; }
3288 /// \brief Remove the built instruction.
3289 void undo() override {
3290 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3291 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3292 IVal->eraseFromParent();
3296 /// \brief Build a sign extension instruction.
3297 class SExtBuilder : public TypePromotionAction {
3300 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3302 /// sext Opnd to Ty.
3303 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3304 : TypePromotionAction(InsertPt) {
3305 IRBuilder<> Builder(InsertPt);
3306 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3307 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3310 /// \brief Get the built value.
3311 Value *getBuiltValue() { return Val; }
3313 /// \brief Remove the built instruction.
3314 void undo() override {
3315 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3316 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3317 IVal->eraseFromParent();
3321 /// \brief Build a zero extension instruction.
3322 class ZExtBuilder : public TypePromotionAction {
3325 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3327 /// zext Opnd to Ty.
3328 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3329 : TypePromotionAction(InsertPt) {
3330 IRBuilder<> Builder(InsertPt);
3331 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3332 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3335 /// \brief Get the built value.
3336 Value *getBuiltValue() { return Val; }
3338 /// \brief Remove the built instruction.
3339 void undo() override {
3340 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3341 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3342 IVal->eraseFromParent();
3346 /// \brief Mutate an instruction to another type.
3347 class TypeMutator : public TypePromotionAction {
3348 /// Record the original type.
3352 /// \brief Mutate the type of \p Inst into \p NewTy.
3353 TypeMutator(Instruction *Inst, Type *NewTy)
3354 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3355 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3357 Inst->mutateType(NewTy);
3360 /// \brief Mutate the instruction back to its original type.
3361 void undo() override {
3362 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3364 Inst->mutateType(OrigTy);
3368 /// \brief Replace the uses of an instruction by another instruction.
3369 class UsesReplacer : public TypePromotionAction {
3370 /// Helper structure to keep track of the replaced uses.
3371 struct InstructionAndIdx {
3372 /// The instruction using the instruction.
3374 /// The index where this instruction is used for Inst.
3376 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3377 : Inst(Inst), Idx(Idx) {}
3380 /// Keep track of the original uses (pair Instruction, Index).
3381 SmallVector<InstructionAndIdx, 4> OriginalUses;
3382 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3385 /// \brief Replace all the use of \p Inst by \p New.
3386 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3387 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3389 // Record the original uses.
3390 for (Use &U : Inst->uses()) {
3391 Instruction *UserI = cast<Instruction>(U.getUser());
3392 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3394 // Now, we can replace the uses.
3395 Inst->replaceAllUsesWith(New);
3398 /// \brief Reassign the original uses of Inst to Inst.
3399 void undo() override {
3400 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3401 for (use_iterator UseIt = OriginalUses.begin(),
3402 EndIt = OriginalUses.end();
3403 UseIt != EndIt; ++UseIt) {
3404 UseIt->Inst->setOperand(UseIt->Idx, Inst);
3409 /// \brief Remove an instruction from the IR.
3410 class InstructionRemover : public TypePromotionAction {
3411 /// Original position of the instruction.
3412 InsertionHandler Inserter;
3413 /// Helper structure to hide all the link to the instruction. In other
3414 /// words, this helps to do as if the instruction was removed.
3415 OperandsHider Hider;
3416 /// Keep track of the uses replaced, if any.
3417 UsesReplacer *Replacer;
3420 /// \brief Remove all reference of \p Inst and optinally replace all its
3422 /// \pre If !Inst->use_empty(), then New != nullptr
3423 InstructionRemover(Instruction *Inst, Value *New = nullptr)
3424 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3427 Replacer = new UsesReplacer(Inst, New);
3428 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3429 Inst->removeFromParent();
3432 ~InstructionRemover() override { delete Replacer; }
3434 /// \brief Really remove the instruction.
3435 void commit() override { delete Inst; }
3437 /// \brief Resurrect the instruction and reassign it to the proper uses if
3438 /// new value was provided when build this action.
3439 void undo() override {
3440 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3441 Inserter.insert(Inst);
3449 /// Restoration point.
3450 /// The restoration point is a pointer to an action instead of an iterator
3451 /// because the iterator may be invalidated but not the pointer.
3452 typedef const TypePromotionAction *ConstRestorationPt;
3453 /// Advocate every changes made in that transaction.
3455 /// Undo all the changes made after the given point.
3456 void rollback(ConstRestorationPt Point);
3457 /// Get the current restoration point.
3458 ConstRestorationPt getRestorationPoint() const;
3460 /// \name API for IR modification with state keeping to support rollback.
3462 /// Same as Instruction::setOperand.
3463 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3464 /// Same as Instruction::eraseFromParent.
3465 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3466 /// Same as Value::replaceAllUsesWith.
3467 void replaceAllUsesWith(Instruction *Inst, Value *New);
3468 /// Same as Value::mutateType.
3469 void mutateType(Instruction *Inst, Type *NewTy);
3470 /// Same as IRBuilder::createTrunc.
3471 Value *createTrunc(Instruction *Opnd, Type *Ty);
3472 /// Same as IRBuilder::createSExt.
3473 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3474 /// Same as IRBuilder::createZExt.
3475 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3476 /// Same as Instruction::moveBefore.
3477 void moveBefore(Instruction *Inst, Instruction *Before);
3481 /// The ordered list of actions made so far.
3482 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3483 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3486 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3489 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3492 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3495 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3498 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3500 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3503 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3504 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3507 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3509 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3510 Value *Val = Ptr->getBuiltValue();
3511 Actions.push_back(std::move(Ptr));
3515 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3516 Value *Opnd, Type *Ty) {
3517 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3518 Value *Val = Ptr->getBuiltValue();
3519 Actions.push_back(std::move(Ptr));
3523 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3524 Value *Opnd, Type *Ty) {
3525 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3526 Value *Val = Ptr->getBuiltValue();
3527 Actions.push_back(std::move(Ptr));
3531 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3532 Instruction *Before) {
3534 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3537 TypePromotionTransaction::ConstRestorationPt
3538 TypePromotionTransaction::getRestorationPoint() const {
3539 return !Actions.empty() ? Actions.back().get() : nullptr;
3542 void TypePromotionTransaction::commit() {
3543 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3549 void TypePromotionTransaction::rollback(
3550 TypePromotionTransaction::ConstRestorationPt Point) {
3551 while (!Actions.empty() && Point != Actions.back().get()) {
3552 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3557 /// \brief A helper class for matching addressing modes.
3559 /// This encapsulates the logic for matching the target-legal addressing modes.
3560 class AddressingModeMatcher {
3561 SmallVectorImpl<Instruction*> &AddrModeInsts;
3562 const TargetMachine &TM;
3563 const TargetLowering &TLI;
3564 const DataLayout &DL;
3566 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3567 /// the memory instruction that we're computing this address for.
3570 Instruction *MemoryInst;
3572 /// This is the addressing mode that we're building up. This is
3573 /// part of the return value of this addressing mode matching stuff.
3574 ExtAddrMode &AddrMode;
3576 /// The instructions inserted by other CodeGenPrepare optimizations.
3577 const SetOfInstrs &InsertedInsts;
3578 /// A map from the instructions to their type before promotion.
3579 InstrToOrigTy &PromotedInsts;
3580 /// The ongoing transaction where every action should be registered.
3581 TypePromotionTransaction &TPT;
3583 /// This is set to true when we should not do profitability checks.
3584 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3585 bool IgnoreProfitability;
3587 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3588 const TargetMachine &TM, Type *AT, unsigned AS,
3589 Instruction *MI, ExtAddrMode &AM,
3590 const SetOfInstrs &InsertedInsts,
3591 InstrToOrigTy &PromotedInsts,
3592 TypePromotionTransaction &TPT)
3593 : AddrModeInsts(AMI), TM(TM),
3594 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3595 ->getTargetLowering()),
3596 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3597 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3598 PromotedInsts(PromotedInsts), TPT(TPT) {
3599 IgnoreProfitability = false;
3603 /// Find the maximal addressing mode that a load/store of V can fold,
3604 /// give an access type of AccessTy. This returns a list of involved
3605 /// instructions in AddrModeInsts.
3606 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3608 /// \p PromotedInsts maps the instructions to their type before promotion.
3609 /// \p The ongoing transaction where every action should be registered.
3610 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3611 Instruction *MemoryInst,
3612 SmallVectorImpl<Instruction*> &AddrModeInsts,
3613 const TargetMachine &TM,
3614 const SetOfInstrs &InsertedInsts,
3615 InstrToOrigTy &PromotedInsts,
3616 TypePromotionTransaction &TPT) {
3619 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3620 MemoryInst, Result, InsertedInsts,
3621 PromotedInsts, TPT).matchAddr(V, 0);
3622 (void)Success; assert(Success && "Couldn't select *anything*?");
3626 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3627 bool matchAddr(Value *V, unsigned Depth);
3628 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3629 bool *MovedAway = nullptr);
3630 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3631 ExtAddrMode &AMBefore,
3632 ExtAddrMode &AMAfter);
3633 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3634 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3635 Value *PromotedOperand) const;
3638 /// Try adding ScaleReg*Scale to the current addressing mode.
3639 /// Return true and update AddrMode if this addr mode is legal for the target,
3641 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3643 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3644 // mode. Just process that directly.
3646 return matchAddr(ScaleReg, Depth);
3648 // If the scale is 0, it takes nothing to add this.
3652 // If we already have a scale of this value, we can add to it, otherwise, we
3653 // need an available scale field.
3654 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3657 ExtAddrMode TestAddrMode = AddrMode;
3659 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3660 // [A+B + A*7] -> [B+A*8].
3661 TestAddrMode.Scale += Scale;
3662 TestAddrMode.ScaledReg = ScaleReg;
3664 // If the new address isn't legal, bail out.
3665 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3668 // It was legal, so commit it.
3669 AddrMode = TestAddrMode;
3671 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3672 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3673 // X*Scale + C*Scale to addr mode.
3674 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3675 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3676 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3677 TestAddrMode.ScaledReg = AddLHS;
3678 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3680 // If this addressing mode is legal, commit it and remember that we folded
3681 // this instruction.
3682 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3683 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3684 AddrMode = TestAddrMode;
3689 // Otherwise, not (x+c)*scale, just return what we have.
3693 /// This is a little filter, which returns true if an addressing computation
3694 /// involving I might be folded into a load/store accessing it.
3695 /// This doesn't need to be perfect, but needs to accept at least
3696 /// the set of instructions that MatchOperationAddr can.
3697 static bool MightBeFoldableInst(Instruction *I) {
3698 switch (I->getOpcode()) {
3699 case Instruction::BitCast:
3700 case Instruction::AddrSpaceCast:
3701 // Don't touch identity bitcasts.
3702 if (I->getType() == I->getOperand(0)->getType())
3704 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3705 case Instruction::PtrToInt:
3706 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3708 case Instruction::IntToPtr:
3709 // We know the input is intptr_t, so this is foldable.
3711 case Instruction::Add:
3713 case Instruction::Mul:
3714 case Instruction::Shl:
3715 // Can only handle X*C and X << C.
3716 return isa<ConstantInt>(I->getOperand(1));
3717 case Instruction::GetElementPtr:
3724 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3725 /// \note \p Val is assumed to be the product of some type promotion.
3726 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3727 /// to be legal, as the non-promoted value would have had the same state.
3728 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3729 const DataLayout &DL, Value *Val) {
3730 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3733 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3734 // If the ISDOpcode is undefined, it was undefined before the promotion.
3737 // Otherwise, check if the promoted instruction is legal or not.
3738 return TLI.isOperationLegalOrCustom(
3739 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3742 /// \brief Hepler class to perform type promotion.
3743 class TypePromotionHelper {
3744 /// \brief Utility function to check whether or not a sign or zero extension
3745 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3746 /// either using the operands of \p Inst or promoting \p Inst.
3747 /// The type of the extension is defined by \p IsSExt.
3748 /// In other words, check if:
3749 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3750 /// #1 Promotion applies:
3751 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3752 /// #2 Operand reuses:
3753 /// ext opnd1 to ConsideredExtType.
3754 /// \p PromotedInsts maps the instructions to their type before promotion.
3755 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3756 const InstrToOrigTy &PromotedInsts, bool IsSExt);
3758 /// \brief Utility function to determine if \p OpIdx should be promoted when
3759 /// promoting \p Inst.
3760 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3761 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3764 /// \brief Utility function to promote the operand of \p Ext when this
3765 /// operand is a promotable trunc or sext or zext.
3766 /// \p PromotedInsts maps the instructions to their type before promotion.
3767 /// \p CreatedInstsCost[out] contains the cost of all instructions
3768 /// created to promote the operand of Ext.
3769 /// Newly added extensions are inserted in \p Exts.
3770 /// Newly added truncates are inserted in \p Truncs.
3771 /// Should never be called directly.
3772 /// \return The promoted value which is used instead of Ext.
3773 static Value *promoteOperandForTruncAndAnyExt(
3774 Instruction *Ext, TypePromotionTransaction &TPT,
3775 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3776 SmallVectorImpl<Instruction *> *Exts,
3777 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3779 /// \brief Utility function to promote the operand of \p Ext when this
3780 /// operand is promotable and is not a supported trunc or sext.
3781 /// \p PromotedInsts maps the instructions to their type before promotion.
3782 /// \p CreatedInstsCost[out] contains the cost of all the instructions
3783 /// created to promote the operand of Ext.
3784 /// Newly added extensions are inserted in \p Exts.
3785 /// Newly added truncates are inserted in \p Truncs.
3786 /// Should never be called directly.
3787 /// \return The promoted value which is used instead of Ext.
3788 static Value *promoteOperandForOther(Instruction *Ext,
3789 TypePromotionTransaction &TPT,
3790 InstrToOrigTy &PromotedInsts,
3791 unsigned &CreatedInstsCost,
3792 SmallVectorImpl<Instruction *> *Exts,
3793 SmallVectorImpl<Instruction *> *Truncs,
3794 const TargetLowering &TLI, bool IsSExt);
3796 /// \see promoteOperandForOther.
3797 static Value *signExtendOperandForOther(
3798 Instruction *Ext, TypePromotionTransaction &TPT,
3799 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3800 SmallVectorImpl<Instruction *> *Exts,
3801 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3802 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3803 Exts, Truncs, TLI, true);
3806 /// \see promoteOperandForOther.
3807 static Value *zeroExtendOperandForOther(
3808 Instruction *Ext, TypePromotionTransaction &TPT,
3809 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3810 SmallVectorImpl<Instruction *> *Exts,
3811 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3812 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3813 Exts, Truncs, TLI, false);
3817 /// Type for the utility function that promotes the operand of Ext.
3818 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3819 InstrToOrigTy &PromotedInsts,
3820 unsigned &CreatedInstsCost,
3821 SmallVectorImpl<Instruction *> *Exts,
3822 SmallVectorImpl<Instruction *> *Truncs,
3823 const TargetLowering &TLI);
3824 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3825 /// action to promote the operand of \p Ext instead of using Ext.
3826 /// \return NULL if no promotable action is possible with the current
3828 /// \p InsertedInsts keeps track of all the instructions inserted by the
3829 /// other CodeGenPrepare optimizations. This information is important
3830 /// because we do not want to promote these instructions as CodeGenPrepare
3831 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3832 /// \p PromotedInsts maps the instructions to their type before promotion.
3833 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3834 const TargetLowering &TLI,
3835 const InstrToOrigTy &PromotedInsts);
3838 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3839 Type *ConsideredExtType,
3840 const InstrToOrigTy &PromotedInsts,
3842 // The promotion helper does not know how to deal with vector types yet.
3843 // To be able to fix that, we would need to fix the places where we
3844 // statically extend, e.g., constants and such.
3845 if (Inst->getType()->isVectorTy())
3848 // We can always get through zext.
3849 if (isa<ZExtInst>(Inst))
3852 // sext(sext) is ok too.
3853 if (IsSExt && isa<SExtInst>(Inst))
3856 // We can get through binary operator, if it is legal. In other words, the
3857 // binary operator must have a nuw or nsw flag.
3858 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3859 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3860 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3861 (IsSExt && BinOp->hasNoSignedWrap())))
3864 // Check if we can do the following simplification.
3865 // ext(trunc(opnd)) --> ext(opnd)
3866 if (!isa<TruncInst>(Inst))
3869 Value *OpndVal = Inst->getOperand(0);
3870 // Check if we can use this operand in the extension.
3871 // If the type is larger than the result type of the extension, we cannot.
3872 if (!OpndVal->getType()->isIntegerTy() ||
3873 OpndVal->getType()->getIntegerBitWidth() >
3874 ConsideredExtType->getIntegerBitWidth())
3877 // If the operand of the truncate is not an instruction, we will not have
3878 // any information on the dropped bits.
3879 // (Actually we could for constant but it is not worth the extra logic).
3880 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3884 // Check if the source of the type is narrow enough.
3885 // I.e., check that trunc just drops extended bits of the same kind of
3887 // #1 get the type of the operand and check the kind of the extended bits.
3888 const Type *OpndType;
3889 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3890 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3891 OpndType = It->second.getPointer();
3892 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3893 OpndType = Opnd->getOperand(0)->getType();
3897 // #2 check that the truncate just drops extended bits.
3898 return Inst->getType()->getIntegerBitWidth() >=
3899 OpndType->getIntegerBitWidth();
3902 TypePromotionHelper::Action TypePromotionHelper::getAction(
3903 Instruction *Ext, const SetOfInstrs &InsertedInsts,
3904 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3905 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3906 "Unexpected instruction type");
3907 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3908 Type *ExtTy = Ext->getType();
3909 bool IsSExt = isa<SExtInst>(Ext);
3910 // If the operand of the extension is not an instruction, we cannot
3912 // If it, check we can get through.
3913 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3916 // Do not promote if the operand has been added by codegenprepare.
3917 // Otherwise, it means we are undoing an optimization that is likely to be
3918 // redone, thus causing potential infinite loop.
3919 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3922 // SExt or Trunc instructions.
3923 // Return the related handler.
3924 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3925 isa<ZExtInst>(ExtOpnd))
3926 return promoteOperandForTruncAndAnyExt;
3928 // Regular instruction.
3929 // Abort early if we will have to insert non-free instructions.
3930 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3932 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3935 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3936 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3937 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3938 SmallVectorImpl<Instruction *> *Exts,
3939 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3940 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3941 // get through it and this method should not be called.
3942 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3943 Value *ExtVal = SExt;
3944 bool HasMergedNonFreeExt = false;
3945 if (isa<ZExtInst>(SExtOpnd)) {
3946 // Replace s|zext(zext(opnd))
3948 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3950 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3951 TPT.replaceAllUsesWith(SExt, ZExt);
3952 TPT.eraseInstruction(SExt);
3955 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3957 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3959 CreatedInstsCost = 0;
3961 // Remove dead code.
3962 if (SExtOpnd->use_empty())
3963 TPT.eraseInstruction(SExtOpnd);
3965 // Check if the extension is still needed.
3966 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3967 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3970 Exts->push_back(ExtInst);
3971 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3976 // At this point we have: ext ty opnd to ty.
3977 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3978 Value *NextVal = ExtInst->getOperand(0);
3979 TPT.eraseInstruction(ExtInst, NextVal);
3983 Value *TypePromotionHelper::promoteOperandForOther(
3984 Instruction *Ext, TypePromotionTransaction &TPT,
3985 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3986 SmallVectorImpl<Instruction *> *Exts,
3987 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3989 // By construction, the operand of Ext is an instruction. Otherwise we cannot
3990 // get through it and this method should not be called.
3991 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3992 CreatedInstsCost = 0;
3993 if (!ExtOpnd->hasOneUse()) {
3994 // ExtOpnd will be promoted.
3995 // All its uses, but Ext, will need to use a truncated value of the
3996 // promoted version.
3997 // Create the truncate now.
3998 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3999 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4000 ITrunc->removeFromParent();
4001 // Insert it just after the definition.
4002 ITrunc->insertAfter(ExtOpnd);
4004 Truncs->push_back(ITrunc);
4007 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4008 // Restore the operand of Ext (which has been replaced by the previous call
4009 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4010 TPT.setOperand(Ext, 0, ExtOpnd);
4013 // Get through the Instruction:
4014 // 1. Update its type.
4015 // 2. Replace the uses of Ext by Inst.
4016 // 3. Extend each operand that needs to be extended.
4018 // Remember the original type of the instruction before promotion.
4019 // This is useful to know that the high bits are sign extended bits.
4020 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
4021 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
4023 TPT.mutateType(ExtOpnd, Ext->getType());
4025 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4027 Instruction *ExtForOpnd = Ext;
4029 DEBUG(dbgs() << "Propagate Ext to operands\n");
4030 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4032 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4033 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4034 !shouldExtOperand(ExtOpnd, OpIdx)) {
4035 DEBUG(dbgs() << "No need to propagate\n");
4038 // Check if we can statically extend the operand.
4039 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4040 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4041 DEBUG(dbgs() << "Statically extend\n");
4042 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4043 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4044 : Cst->getValue().zext(BitWidth);
4045 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4048 // UndefValue are typed, so we have to statically sign extend them.
4049 if (isa<UndefValue>(Opnd)) {
4050 DEBUG(dbgs() << "Statically extend\n");
4051 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4055 // Otherwise we have to explicity sign extend the operand.
4056 // Check if Ext was reused to extend an operand.
4058 // If yes, create a new one.
4059 DEBUG(dbgs() << "More operands to ext\n");
4060 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4061 : TPT.createZExt(Ext, Opnd, Ext->getType());
4062 if (!isa<Instruction>(ValForExtOpnd)) {
4063 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4066 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4069 Exts->push_back(ExtForOpnd);
4070 TPT.setOperand(ExtForOpnd, 0, Opnd);
4072 // Move the sign extension before the insertion point.
4073 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4074 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4075 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4076 // If more sext are required, new instructions will have to be created.
4077 ExtForOpnd = nullptr;
4079 if (ExtForOpnd == Ext) {
4080 DEBUG(dbgs() << "Extension is useless now\n");
4081 TPT.eraseInstruction(Ext);
4086 /// Check whether or not promoting an instruction to a wider type is profitable.
4087 /// \p NewCost gives the cost of extension instructions created by the
4089 /// \p OldCost gives the cost of extension instructions before the promotion
4090 /// plus the number of instructions that have been
4091 /// matched in the addressing mode the promotion.
4092 /// \p PromotedOperand is the value that has been promoted.
4093 /// \return True if the promotion is profitable, false otherwise.
4094 bool AddressingModeMatcher::isPromotionProfitable(
4095 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4096 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
4097 // The cost of the new extensions is greater than the cost of the
4098 // old extension plus what we folded.
4099 // This is not profitable.
4100 if (NewCost > OldCost)
4102 if (NewCost < OldCost)
4104 // The promotion is neutral but it may help folding the sign extension in
4105 // loads for instance.
4106 // Check that we did not create an illegal instruction.
4107 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4110 /// Given an instruction or constant expr, see if we can fold the operation
4111 /// into the addressing mode. If so, update the addressing mode and return
4112 /// true, otherwise return false without modifying AddrMode.
4113 /// If \p MovedAway is not NULL, it contains the information of whether or
4114 /// not AddrInst has to be folded into the addressing mode on success.
4115 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4116 /// because it has been moved away.
4117 /// Thus AddrInst must not be added in the matched instructions.
4118 /// This state can happen when AddrInst is a sext, since it may be moved away.
4119 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
4120 /// not be referenced anymore.
4121 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4124 // Avoid exponential behavior on extremely deep expression trees.
4125 if (Depth >= 5) return false;
4127 // By default, all matched instructions stay in place.
4132 case Instruction::PtrToInt:
4133 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4134 return matchAddr(AddrInst->getOperand(0), Depth);
4135 case Instruction::IntToPtr: {
4136 auto AS = AddrInst->getType()->getPointerAddressSpace();
4137 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4138 // This inttoptr is a no-op if the integer type is pointer sized.
4139 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4140 return matchAddr(AddrInst->getOperand(0), Depth);
4143 case Instruction::BitCast:
4144 // BitCast is always a noop, and we can handle it as long as it is
4145 // int->int or pointer->pointer (we don't want int<->fp or something).
4146 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
4147 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
4148 // Don't touch identity bitcasts. These were probably put here by LSR,
4149 // and we don't want to mess around with them. Assume it knows what it
4151 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4152 return matchAddr(AddrInst->getOperand(0), Depth);
4154 case Instruction::AddrSpaceCast: {
4156 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4157 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4158 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
4159 return matchAddr(AddrInst->getOperand(0), Depth);
4162 case Instruction::Add: {
4163 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4164 ExtAddrMode BackupAddrMode = AddrMode;
4165 unsigned OldSize = AddrModeInsts.size();
4166 // Start a transaction at this point.
4167 // The LHS may match but not the RHS.
4168 // Therefore, we need a higher level restoration point to undo partially
4169 // matched operation.
4170 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4171 TPT.getRestorationPoint();
4173 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4174 matchAddr(AddrInst->getOperand(0), Depth+1))
4177 // Restore the old addr mode info.
4178 AddrMode = BackupAddrMode;
4179 AddrModeInsts.resize(OldSize);
4180 TPT.rollback(LastKnownGood);
4182 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4183 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4184 matchAddr(AddrInst->getOperand(1), Depth+1))
4187 // Otherwise we definitely can't merge the ADD in.
4188 AddrMode = BackupAddrMode;
4189 AddrModeInsts.resize(OldSize);
4190 TPT.rollback(LastKnownGood);
4193 //case Instruction::Or:
4194 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4196 case Instruction::Mul:
4197 case Instruction::Shl: {
4198 // Can only handle X*C and X << C.
4199 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4202 int64_t Scale = RHS->getSExtValue();
4203 if (Opcode == Instruction::Shl)
4204 Scale = 1LL << Scale;
4206 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4208 case Instruction::GetElementPtr: {
4209 // Scan the GEP. We check it if it contains constant offsets and at most
4210 // one variable offset.
4211 int VariableOperand = -1;
4212 unsigned VariableScale = 0;
4214 int64_t ConstantOffset = 0;
4215 gep_type_iterator GTI = gep_type_begin(AddrInst);
4216 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4217 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
4218 const StructLayout *SL = DL.getStructLayout(STy);
4220 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4221 ConstantOffset += SL->getElementOffset(Idx);
4223 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
4224 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4225 ConstantOffset += CI->getSExtValue()*TypeSize;
4226 } else if (TypeSize) { // Scales of zero don't do anything.
4227 // We only allow one variable index at the moment.
4228 if (VariableOperand != -1)
4231 // Remember the variable index.
4232 VariableOperand = i;
4233 VariableScale = TypeSize;
4238 // A common case is for the GEP to only do a constant offset. In this case,
4239 // just add it to the disp field and check validity.
4240 if (VariableOperand == -1) {
4241 AddrMode.BaseOffs += ConstantOffset;
4242 if (ConstantOffset == 0 ||
4243 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4244 // Check to see if we can fold the base pointer in too.
4245 if (matchAddr(AddrInst->getOperand(0), Depth+1))
4248 AddrMode.BaseOffs -= ConstantOffset;
4252 // Save the valid addressing mode in case we can't match.
4253 ExtAddrMode BackupAddrMode = AddrMode;
4254 unsigned OldSize = AddrModeInsts.size();
4256 // See if the scale and offset amount is valid for this target.
4257 AddrMode.BaseOffs += ConstantOffset;
4259 // Match the base operand of the GEP.
4260 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4261 // If it couldn't be matched, just stuff the value in a register.
4262 if (AddrMode.HasBaseReg) {
4263 AddrMode = BackupAddrMode;
4264 AddrModeInsts.resize(OldSize);
4267 AddrMode.HasBaseReg = true;
4268 AddrMode.BaseReg = AddrInst->getOperand(0);
4271 // Match the remaining variable portion of the GEP.
4272 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4274 // If it couldn't be matched, try stuffing the base into a register
4275 // instead of matching it, and retrying the match of the scale.
4276 AddrMode = BackupAddrMode;
4277 AddrModeInsts.resize(OldSize);
4278 if (AddrMode.HasBaseReg)
4280 AddrMode.HasBaseReg = true;
4281 AddrMode.BaseReg = AddrInst->getOperand(0);
4282 AddrMode.BaseOffs += ConstantOffset;
4283 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4284 VariableScale, Depth)) {
4285 // If even that didn't work, bail.
4286 AddrMode = BackupAddrMode;
4287 AddrModeInsts.resize(OldSize);
4294 case Instruction::SExt:
4295 case Instruction::ZExt: {
4296 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4300 // Try to move this ext out of the way of the addressing mode.
4301 // Ask for a method for doing so.
4302 TypePromotionHelper::Action TPH =
4303 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4307 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4308 TPT.getRestorationPoint();
4309 unsigned CreatedInstsCost = 0;
4310 unsigned ExtCost = !TLI.isExtFree(Ext);
4311 Value *PromotedOperand =
4312 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4313 // SExt has been moved away.
4314 // Thus either it will be rematched later in the recursive calls or it is
4315 // gone. Anyway, we must not fold it into the addressing mode at this point.
4319 // addr = gep base, idx
4321 // promotedOpnd = ext opnd <- no match here
4322 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4323 // addr = gep base, op <- match
4327 assert(PromotedOperand &&
4328 "TypePromotionHelper should have filtered out those cases");
4330 ExtAddrMode BackupAddrMode = AddrMode;
4331 unsigned OldSize = AddrModeInsts.size();
4333 if (!matchAddr(PromotedOperand, Depth) ||
4334 // The total of the new cost is equal to the cost of the created
4336 // The total of the old cost is equal to the cost of the extension plus
4337 // what we have saved in the addressing mode.
4338 !isPromotionProfitable(CreatedInstsCost,
4339 ExtCost + (AddrModeInsts.size() - OldSize),
4341 AddrMode = BackupAddrMode;
4342 AddrModeInsts.resize(OldSize);
4343 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4344 TPT.rollback(LastKnownGood);
4353 /// If we can, try to add the value of 'Addr' into the current addressing mode.
4354 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4355 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
4358 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4359 // Start a transaction at this point that we will rollback if the matching
4361 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4362 TPT.getRestorationPoint();
4363 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4364 // Fold in immediates if legal for the target.
4365 AddrMode.BaseOffs += CI->getSExtValue();
4366 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4368 AddrMode.BaseOffs -= CI->getSExtValue();
4369 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4370 // If this is a global variable, try to fold it into the addressing mode.
4371 if (!AddrMode.BaseGV) {
4372 AddrMode.BaseGV = GV;
4373 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4375 AddrMode.BaseGV = nullptr;
4377 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4378 ExtAddrMode BackupAddrMode = AddrMode;
4379 unsigned OldSize = AddrModeInsts.size();
4381 // Check to see if it is possible to fold this operation.
4382 bool MovedAway = false;
4383 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4384 // This instruction may have been moved away. If so, there is nothing
4388 // Okay, it's possible to fold this. Check to see if it is actually
4389 // *profitable* to do so. We use a simple cost model to avoid increasing
4390 // register pressure too much.
4391 if (I->hasOneUse() ||
4392 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4393 AddrModeInsts.push_back(I);
4397 // It isn't profitable to do this, roll back.
4398 //cerr << "NOT FOLDING: " << *I;
4399 AddrMode = BackupAddrMode;
4400 AddrModeInsts.resize(OldSize);
4401 TPT.rollback(LastKnownGood);
4403 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4404 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4406 TPT.rollback(LastKnownGood);
4407 } else if (isa<ConstantPointerNull>(Addr)) {
4408 // Null pointer gets folded without affecting the addressing mode.
4412 // Worse case, the target should support [reg] addressing modes. :)
4413 if (!AddrMode.HasBaseReg) {
4414 AddrMode.HasBaseReg = true;
4415 AddrMode.BaseReg = Addr;
4416 // Still check for legality in case the target supports [imm] but not [i+r].
4417 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4419 AddrMode.HasBaseReg = false;
4420 AddrMode.BaseReg = nullptr;
4423 // If the base register is already taken, see if we can do [r+r].
4424 if (AddrMode.Scale == 0) {
4426 AddrMode.ScaledReg = Addr;
4427 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4430 AddrMode.ScaledReg = nullptr;
4433 TPT.rollback(LastKnownGood);
4437 /// Check to see if all uses of OpVal by the specified inline asm call are due
4438 /// to memory operands. If so, return true, otherwise return false.
4439 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4440 const TargetMachine &TM) {
4441 const Function *F = CI->getParent()->getParent();
4442 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
4443 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
4444 TargetLowering::AsmOperandInfoVector TargetConstraints =
4445 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
4446 ImmutableCallSite(CI));
4447 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4448 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4450 // Compute the constraint code and ConstraintType to use.
4451 TLI->ComputeConstraintToUse(OpInfo, SDValue());
4453 // If this asm operand is our Value*, and if it isn't an indirect memory
4454 // operand, we can't fold it!
4455 if (OpInfo.CallOperandVal == OpVal &&
4456 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4457 !OpInfo.isIndirect))
4464 /// Recursively walk all the uses of I until we find a memory use.
4465 /// If we find an obviously non-foldable instruction, return true.
4466 /// Add the ultimately found memory instructions to MemoryUses.
4467 static bool FindAllMemoryUses(
4469 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4470 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
4471 // If we already considered this instruction, we're done.
4472 if (!ConsideredInsts.insert(I).second)
4475 // If this is an obviously unfoldable instruction, bail out.
4476 if (!MightBeFoldableInst(I))
4479 // Loop over all the uses, recursively processing them.
4480 for (Use &U : I->uses()) {
4481 Instruction *UserI = cast<Instruction>(U.getUser());
4483 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4484 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4488 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4489 unsigned opNo = U.getOperandNo();
4490 if (opNo == 0) return true; // Storing addr, not into addr.
4491 MemoryUses.push_back(std::make_pair(SI, opNo));
4495 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4496 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4497 if (!IA) return true;
4499 // If this is a memory operand, we're cool, otherwise bail out.
4500 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
4505 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
4512 /// Return true if Val is already known to be live at the use site that we're
4513 /// folding it into. If so, there is no cost to include it in the addressing
4514 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4515 /// instruction already.
4516 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4517 Value *KnownLive2) {
4518 // If Val is either of the known-live values, we know it is live!
4519 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4522 // All values other than instructions and arguments (e.g. constants) are live.
4523 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4525 // If Val is a constant sized alloca in the entry block, it is live, this is
4526 // true because it is just a reference to the stack/frame pointer, which is
4527 // live for the whole function.
4528 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4529 if (AI->isStaticAlloca())
4532 // Check to see if this value is already used in the memory instruction's
4533 // block. If so, it's already live into the block at the very least, so we
4534 // can reasonably fold it.
4535 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4538 /// It is possible for the addressing mode of the machine to fold the specified
4539 /// instruction into a load or store that ultimately uses it.
4540 /// However, the specified instruction has multiple uses.
4541 /// Given this, it may actually increase register pressure to fold it
4542 /// into the load. For example, consider this code:
4546 /// use(Y) -> nonload/store
4550 /// In this case, Y has multiple uses, and can be folded into the load of Z
4551 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4552 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4553 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4554 /// number of computations either.
4556 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4557 /// X was live across 'load Z' for other reasons, we actually *would* want to
4558 /// fold the addressing mode in the Z case. This would make Y die earlier.
4559 bool AddressingModeMatcher::
4560 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4561 ExtAddrMode &AMAfter) {
4562 if (IgnoreProfitability) return true;
4564 // AMBefore is the addressing mode before this instruction was folded into it,
4565 // and AMAfter is the addressing mode after the instruction was folded. Get
4566 // the set of registers referenced by AMAfter and subtract out those
4567 // referenced by AMBefore: this is the set of values which folding in this
4568 // address extends the lifetime of.
4570 // Note that there are only two potential values being referenced here,
4571 // BaseReg and ScaleReg (global addresses are always available, as are any
4572 // folded immediates).
4573 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4575 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4576 // lifetime wasn't extended by adding this instruction.
4577 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4579 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4580 ScaledReg = nullptr;
4582 // If folding this instruction (and it's subexprs) didn't extend any live
4583 // ranges, we're ok with it.
4584 if (!BaseReg && !ScaledReg)
4587 // If all uses of this instruction are ultimately load/store/inlineasm's,
4588 // check to see if their addressing modes will include this instruction. If
4589 // so, we can fold it into all uses, so it doesn't matter if it has multiple
4591 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4592 SmallPtrSet<Instruction*, 16> ConsideredInsts;
4593 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
4594 return false; // Has a non-memory, non-foldable use!
4596 // Now that we know that all uses of this instruction are part of a chain of
4597 // computation involving only operations that could theoretically be folded
4598 // into a memory use, loop over each of these uses and see if they could
4599 // *actually* fold the instruction.
4600 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4601 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4602 Instruction *User = MemoryUses[i].first;
4603 unsigned OpNo = MemoryUses[i].second;
4605 // Get the access type of this use. If the use isn't a pointer, we don't
4606 // know what it accesses.
4607 Value *Address = User->getOperand(OpNo);
4608 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4611 Type *AddressAccessTy = AddrTy->getElementType();
4612 unsigned AS = AddrTy->getAddressSpace();
4614 // Do a match against the root of this address, ignoring profitability. This
4615 // will tell us if the addressing mode for the memory operation will
4616 // *actually* cover the shared instruction.
4618 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4619 TPT.getRestorationPoint();
4620 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
4621 MemoryInst, Result, InsertedInsts,
4622 PromotedInsts, TPT);
4623 Matcher.IgnoreProfitability = true;
4624 bool Success = Matcher.matchAddr(Address, 0);
4625 (void)Success; assert(Success && "Couldn't select *anything*?");
4627 // The match was to check the profitability, the changes made are not
4628 // part of the original matcher. Therefore, they should be dropped
4629 // otherwise the original matcher will not present the right state.
4630 TPT.rollback(LastKnownGood);
4632 // If the match didn't cover I, then it won't be shared by it.
4633 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
4634 I) == MatchedAddrModeInsts.end())
4637 MatchedAddrModeInsts.clear();
4643 } // end anonymous namespace
4645 /// Return true if the specified values are defined in a
4646 /// different basic block than BB.
4647 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4648 if (Instruction *I = dyn_cast<Instruction>(V))
4649 return I->getParent() != BB;
4653 /// Load and Store Instructions often have addressing modes that can do
4654 /// significant amounts of computation. As such, instruction selection will try
4655 /// to get the load or store to do as much computation as possible for the
4656 /// program. The problem is that isel can only see within a single block. As
4657 /// such, we sink as much legal addressing mode work into the block as possible.
4659 /// This method is used to optimize both load/store and inline asms with memory
4661 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4662 Type *AccessTy, unsigned AddrSpace) {
4665 // Try to collapse single-value PHI nodes. This is necessary to undo
4666 // unprofitable PRE transformations.
4667 SmallVector<Value*, 8> worklist;
4668 SmallPtrSet<Value*, 16> Visited;
4669 worklist.push_back(Addr);
4671 // Use a worklist to iteratively look through PHI nodes, and ensure that
4672 // the addressing mode obtained from the non-PHI roots of the graph
4674 Value *Consensus = nullptr;
4675 unsigned NumUsesConsensus = 0;
4676 bool IsNumUsesConsensusValid = false;
4677 SmallVector<Instruction*, 16> AddrModeInsts;
4678 ExtAddrMode AddrMode;
4679 TypePromotionTransaction TPT;
4680 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4681 TPT.getRestorationPoint();
4682 while (!worklist.empty()) {
4683 Value *V = worklist.back();
4684 worklist.pop_back();
4686 // Break use-def graph loops.
4687 if (!Visited.insert(V).second) {
4688 Consensus = nullptr;
4692 // For a PHI node, push all of its incoming values.
4693 if (PHINode *P = dyn_cast<PHINode>(V)) {
4694 for (Value *IncValue : P->incoming_values())
4695 worklist.push_back(IncValue);
4699 // For non-PHIs, determine the addressing mode being computed.
4700 SmallVector<Instruction*, 16> NewAddrModeInsts;
4701 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4702 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
4703 InsertedInsts, PromotedInsts, TPT);
4705 // This check is broken into two cases with very similar code to avoid using
4706 // getNumUses() as much as possible. Some values have a lot of uses, so
4707 // calling getNumUses() unconditionally caused a significant compile-time
4711 AddrMode = NewAddrMode;
4712 AddrModeInsts = NewAddrModeInsts;
4714 } else if (NewAddrMode == AddrMode) {
4715 if (!IsNumUsesConsensusValid) {
4716 NumUsesConsensus = Consensus->getNumUses();
4717 IsNumUsesConsensusValid = true;
4720 // Ensure that the obtained addressing mode is equivalent to that obtained
4721 // for all other roots of the PHI traversal. Also, when choosing one
4722 // such root as representative, select the one with the most uses in order
4723 // to keep the cost modeling heuristics in AddressingModeMatcher
4725 unsigned NumUses = V->getNumUses();
4726 if (NumUses > NumUsesConsensus) {
4728 NumUsesConsensus = NumUses;
4729 AddrModeInsts = NewAddrModeInsts;
4734 Consensus = nullptr;
4738 // If the addressing mode couldn't be determined, or if multiple different
4739 // ones were determined, bail out now.
4741 TPT.rollback(LastKnownGood);
4746 // Check to see if any of the instructions supersumed by this addr mode are
4747 // non-local to I's BB.
4748 bool AnyNonLocal = false;
4749 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
4750 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
4756 // If all the instructions matched are already in this BB, don't do anything.
4758 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
4762 // Insert this computation right after this user. Since our caller is
4763 // scanning from the top of the BB to the bottom, reuse of the expr are
4764 // guaranteed to happen later.
4765 IRBuilder<> Builder(MemoryInst);
4767 // Now that we determined the addressing expression we want to use and know
4768 // that we have to sink it into this block. Check to see if we have already
4769 // done this for some other load/store instr in this block. If so, reuse the
4771 Value *&SunkAddr = SunkAddrs[Addr];
4773 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4774 << *MemoryInst << "\n");
4775 if (SunkAddr->getType() != Addr->getType())
4776 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4777 } else if (AddrSinkUsingGEPs ||
4778 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4779 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
4781 // By default, we use the GEP-based method when AA is used later. This
4782 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4783 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4784 << *MemoryInst << "\n");
4785 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4786 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4788 // First, find the pointer.
4789 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4790 ResultPtr = AddrMode.BaseReg;
4791 AddrMode.BaseReg = nullptr;
4794 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4795 // We can't add more than one pointer together, nor can we scale a
4796 // pointer (both of which seem meaningless).
4797 if (ResultPtr || AddrMode.Scale != 1)
4800 ResultPtr = AddrMode.ScaledReg;
4804 if (AddrMode.BaseGV) {
4808 ResultPtr = AddrMode.BaseGV;
4811 // If the real base value actually came from an inttoptr, then the matcher
4812 // will look through it and provide only the integer value. In that case,
4814 if (!ResultPtr && AddrMode.BaseReg) {
4816 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
4817 AddrMode.BaseReg = nullptr;
4818 } else if (!ResultPtr && AddrMode.Scale == 1) {
4820 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4825 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4826 SunkAddr = Constant::getNullValue(Addr->getType());
4827 } else if (!ResultPtr) {
4831 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4832 Type *I8Ty = Builder.getInt8Ty();
4834 // Start with the base register. Do this first so that subsequent address
4835 // matching finds it last, which will prevent it from trying to match it
4836 // as the scaled value in case it happens to be a mul. That would be
4837 // problematic if we've sunk a different mul for the scale, because then
4838 // we'd end up sinking both muls.
4839 if (AddrMode.BaseReg) {
4840 Value *V = AddrMode.BaseReg;
4841 if (V->getType() != IntPtrTy)
4842 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4847 // Add the scale value.
4848 if (AddrMode.Scale) {
4849 Value *V = AddrMode.ScaledReg;
4850 if (V->getType() == IntPtrTy) {
4852 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4853 cast<IntegerType>(V->getType())->getBitWidth()) {
4854 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4856 // It is only safe to sign extend the BaseReg if we know that the math
4857 // required to create it did not overflow before we extend it. Since
4858 // the original IR value was tossed in favor of a constant back when
4859 // the AddrMode was created we need to bail out gracefully if widths
4860 // do not match instead of extending it.
4861 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4862 if (I && (ResultIndex != AddrMode.BaseReg))
4863 I->eraseFromParent();
4867 if (AddrMode.Scale != 1)
4868 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4871 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4876 // Add in the Base Offset if present.
4877 if (AddrMode.BaseOffs) {
4878 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4880 // We need to add this separately from the scale above to help with
4881 // SDAG consecutive load/store merging.
4882 if (ResultPtr->getType() != I8PtrTy)
4883 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4884 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4891 SunkAddr = ResultPtr;
4893 if (ResultPtr->getType() != I8PtrTy)
4894 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4895 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4898 if (SunkAddr->getType() != Addr->getType())
4899 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4902 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4903 << *MemoryInst << "\n");
4904 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4905 Value *Result = nullptr;
4907 // Start with the base register. Do this first so that subsequent address
4908 // matching finds it last, which will prevent it from trying to match it
4909 // as the scaled value in case it happens to be a mul. That would be
4910 // problematic if we've sunk a different mul for the scale, because then
4911 // we'd end up sinking both muls.
4912 if (AddrMode.BaseReg) {
4913 Value *V = AddrMode.BaseReg;
4914 if (V->getType()->isPointerTy())
4915 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4916 if (V->getType() != IntPtrTy)
4917 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4921 // Add the scale value.
4922 if (AddrMode.Scale) {
4923 Value *V = AddrMode.ScaledReg;
4924 if (V->getType() == IntPtrTy) {
4926 } else if (V->getType()->isPointerTy()) {
4927 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4928 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4929 cast<IntegerType>(V->getType())->getBitWidth()) {
4930 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4932 // It is only safe to sign extend the BaseReg if we know that the math
4933 // required to create it did not overflow before we extend it. Since
4934 // the original IR value was tossed in favor of a constant back when
4935 // the AddrMode was created we need to bail out gracefully if widths
4936 // do not match instead of extending it.
4937 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4938 if (I && (Result != AddrMode.BaseReg))
4939 I->eraseFromParent();
4942 if (AddrMode.Scale != 1)
4943 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4946 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4951 // Add in the BaseGV if present.
4952 if (AddrMode.BaseGV) {
4953 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4955 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4960 // Add in the Base Offset if present.
4961 if (AddrMode.BaseOffs) {
4962 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4964 Result = Builder.CreateAdd(Result, V, "sunkaddr");
4970 SunkAddr = Constant::getNullValue(Addr->getType());
4972 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4975 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4977 // If we have no uses, recursively delete the value and all dead instructions
4979 if (Repl->use_empty()) {
4980 // This can cause recursive deletion, which can invalidate our iterator.
4981 // Use a WeakVH to hold onto it in case this happens.
4982 WeakVH IterHandle(&*CurInstIterator);
4983 BasicBlock *BB = CurInstIterator->getParent();
4985 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4987 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
4988 // If the iterator instruction was recursively deleted, start over at the
4989 // start of the block.
4990 CurInstIterator = BB->begin();
4998 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4999 /// address computing into the block when possible / profitable.
5000 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
5001 bool MadeChange = false;
5003 const TargetRegisterInfo *TRI =
5004 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
5005 TargetLowering::AsmOperandInfoVector TargetConstraints =
5006 TLI->ParseConstraints(*DL, TRI, CS);
5008 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5009 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
5011 // Compute the constraint code and ConstraintType to use.
5012 TLI->ComputeConstraintToUse(OpInfo, SDValue());
5014 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5015 OpInfo.isIndirect) {
5016 Value *OpVal = CS->getArgOperand(ArgNo++);
5017 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
5018 } else if (OpInfo.Type == InlineAsm::isInput)
5025 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
5026 /// sign extensions.
5027 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
5028 assert(!Inst->use_empty() && "Input must have at least one use");
5029 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
5030 bool IsSExt = isa<SExtInst>(FirstUser);
5031 Type *ExtTy = FirstUser->getType();
5032 for (const User *U : Inst->users()) {
5033 const Instruction *UI = cast<Instruction>(U);
5034 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5036 Type *CurTy = UI->getType();
5037 // Same input and output types: Same instruction after CSE.
5041 // If IsSExt is true, we are in this situation:
5043 // b = sext ty1 a to ty2
5044 // c = sext ty1 a to ty3
5045 // Assuming ty2 is shorter than ty3, this could be turned into:
5047 // b = sext ty1 a to ty2
5048 // c = sext ty2 b to ty3
5049 // However, the last sext is not free.
5053 // This is a ZExt, maybe this is free to extend from one type to another.
5054 // In that case, we would not account for a different use.
5057 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5058 CurTy->getScalarType()->getIntegerBitWidth()) {
5066 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5069 // All uses are the same or can be derived from one another for free.
5073 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
5074 /// load instruction.
5075 /// If an ext(load) can be formed, it is returned via \p LI for the load
5076 /// and \p Inst for the extension.
5077 /// Otherwise LI == nullptr and Inst == nullptr.
5078 /// When some promotion happened, \p TPT contains the proper state to
5081 /// \return true when promoting was necessary to expose the ext(load)
5082 /// opportunity, false otherwise.
5086 /// %ld = load i32* %addr
5087 /// %add = add nuw i32 %ld, 4
5088 /// %zext = zext i32 %add to i64
5092 /// %ld = load i32* %addr
5093 /// %zext = zext i32 %ld to i64
5094 /// %add = add nuw i64 %zext, 4
5096 /// Thanks to the promotion, we can match zext(load i32*) to i64.
5097 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
5098 LoadInst *&LI, Instruction *&Inst,
5099 const SmallVectorImpl<Instruction *> &Exts,
5100 unsigned CreatedInstsCost = 0) {
5101 // Iterate over all the extensions to see if one form an ext(load).
5102 for (auto I : Exts) {
5103 // Check if we directly have ext(load).
5104 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
5106 // No promotion happened here.
5109 // Check whether or not we want to do any promotion.
5110 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
5112 // Get the action to perform the promotion.
5113 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
5114 I, InsertedInsts, *TLI, PromotedInsts);
5115 // Check if we can promote.
5118 // Save the current state.
5119 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5120 TPT.getRestorationPoint();
5121 SmallVector<Instruction *, 4> NewExts;
5122 unsigned NewCreatedInstsCost = 0;
5123 unsigned ExtCost = !TLI->isExtFree(I);
5125 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5126 &NewExts, nullptr, *TLI);
5127 assert(PromotedVal &&
5128 "TypePromotionHelper should have filtered out those cases");
5130 // We would be able to merge only one extension in a load.
5131 // Therefore, if we have more than 1 new extension we heuristically
5132 // cut this search path, because it means we degrade the code quality.
5133 // With exactly 2, the transformation is neutral, because we will merge
5134 // one extension but leave one. However, we optimistically keep going,
5135 // because the new extension may be removed too.
5136 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5137 TotalCreatedInstsCost -= ExtCost;
5138 if (!StressExtLdPromotion &&
5139 (TotalCreatedInstsCost > 1 ||
5140 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5141 // The promotion is not profitable, rollback to the previous state.
5142 TPT.rollback(LastKnownGood);
5145 // The promotion is profitable.
5146 // Check if it exposes an ext(load).
5147 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
5148 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5149 // If we have created a new extension, i.e., now we have two
5150 // extensions. We must make sure one of them is merged with
5151 // the load, otherwise we may degrade the code quality.
5152 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
5153 // Promotion happened.
5155 // If this does not help to expose an ext(load) then, rollback.
5156 TPT.rollback(LastKnownGood);
5158 // None of the extension can form an ext(load).
5164 /// Move a zext or sext fed by a load into the same basic block as the load,
5165 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
5166 /// extend into the load.
5167 /// \p I[in/out] the extension may be modified during the process if some
5168 /// promotions apply.
5170 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
5171 // Try to promote a chain of computation if it allows to form
5172 // an extended load.
5173 TypePromotionTransaction TPT;
5174 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5175 TPT.getRestorationPoint();
5176 SmallVector<Instruction *, 1> Exts;
5178 // Look for a load being extended.
5179 LoadInst *LI = nullptr;
5180 Instruction *OldExt = I;
5181 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
5183 assert(!HasPromoted && !LI && "If we did not match any load instruction "
5184 "the code must remain the same");
5189 // If they're already in the same block, there's nothing to do.
5190 // Make the cheap checks first if we did not promote.
5191 // If we promoted, we need to check if it is indeed profitable.
5192 if (!HasPromoted && LI->getParent() == I->getParent())
5195 EVT VT = TLI->getValueType(*DL, I->getType());
5196 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
5198 // If the load has other users and the truncate is not free, this probably
5199 // isn't worthwhile.
5200 if (!LI->hasOneUse() && TLI &&
5201 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
5202 !TLI->isTruncateFree(I->getType(), LI->getType())) {
5204 TPT.rollback(LastKnownGood);
5208 // Check whether the target supports casts folded into loads.
5210 if (isa<ZExtInst>(I))
5211 LType = ISD::ZEXTLOAD;
5213 assert(isa<SExtInst>(I) && "Unexpected ext type!");
5214 LType = ISD::SEXTLOAD;
5216 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
5218 TPT.rollback(LastKnownGood);
5222 // Move the extend into the same block as the load, so that SelectionDAG
5225 I->removeFromParent();
5231 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5232 BasicBlock *DefBB = I->getParent();
5234 // If the result of a {s|z}ext and its source are both live out, rewrite all
5235 // other uses of the source with result of extension.
5236 Value *Src = I->getOperand(0);
5237 if (Src->hasOneUse())
5240 // Only do this xform if truncating is free.
5241 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5244 // Only safe to perform the optimization if the source is also defined in
5246 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5249 bool DefIsLiveOut = false;
5250 for (User *U : I->users()) {
5251 Instruction *UI = cast<Instruction>(U);
5253 // Figure out which BB this ext is used in.
5254 BasicBlock *UserBB = UI->getParent();
5255 if (UserBB == DefBB) continue;
5256 DefIsLiveOut = true;
5262 // Make sure none of the uses are PHI nodes.
5263 for (User *U : Src->users()) {
5264 Instruction *UI = cast<Instruction>(U);
5265 BasicBlock *UserBB = UI->getParent();
5266 if (UserBB == DefBB) continue;
5267 // Be conservative. We don't want this xform to end up introducing
5268 // reloads just before load / store instructions.
5269 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5273 // InsertedTruncs - Only insert one trunc in each block once.
5274 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5276 bool MadeChange = false;
5277 for (Use &U : Src->uses()) {
5278 Instruction *User = cast<Instruction>(U.getUser());
5280 // Figure out which BB this ext is used in.
5281 BasicBlock *UserBB = User->getParent();
5282 if (UserBB == DefBB) continue;
5284 // Both src and def are live in this block. Rewrite the use.
5285 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5287 if (!InsertedTrunc) {
5288 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5289 assert(InsertPt != UserBB->end());
5290 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5291 InsertedInsts.insert(InsertedTrunc);
5294 // Replace a use of the {s|z}ext source with a use of the result.
5303 // Find loads whose uses only use some of the loaded value's bits. Add an "and"
5304 // just after the load if the target can fold this into one extload instruction,
5305 // with the hope of eliminating some of the other later "and" instructions using
5306 // the loaded value. "and"s that are made trivially redundant by the insertion
5307 // of the new "and" are removed by this function, while others (e.g. those whose
5308 // path from the load goes through a phi) are left for isel to potentially
5341 // becomes (after a call to optimizeLoadExt for each load):
5345 // x1' = and x1, 0xff
5349 // x2' = and x2, 0xff
5356 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5358 if (!Load->isSimple() ||
5359 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5362 // Skip loads we've already transformed or have no reason to transform.
5363 if (Load->hasOneUse()) {
5364 User *LoadUser = *Load->user_begin();
5365 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
5366 !dyn_cast<PHINode>(LoadUser))
5370 // Look at all uses of Load, looking through phis, to determine how many bits
5371 // of the loaded value are needed.
5372 SmallVector<Instruction *, 8> WorkList;
5373 SmallPtrSet<Instruction *, 16> Visited;
5374 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5375 for (auto *U : Load->users())
5376 WorkList.push_back(cast<Instruction>(U));
5378 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5379 unsigned BitWidth = LoadResultVT.getSizeInBits();
5380 APInt DemandBits(BitWidth, 0);
5381 APInt WidestAndBits(BitWidth, 0);
5383 while (!WorkList.empty()) {
5384 Instruction *I = WorkList.back();
5385 WorkList.pop_back();
5387 // Break use-def graph loops.
5388 if (!Visited.insert(I).second)
5391 // For a PHI node, push all of its users.
5392 if (auto *Phi = dyn_cast<PHINode>(I)) {
5393 for (auto *U : Phi->users())
5394 WorkList.push_back(cast<Instruction>(U));
5398 switch (I->getOpcode()) {
5399 case llvm::Instruction::And: {
5400 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5403 APInt AndBits = AndC->getValue();
5404 DemandBits |= AndBits;
5405 // Keep track of the widest and mask we see.
5406 if (AndBits.ugt(WidestAndBits))
5407 WidestAndBits = AndBits;
5408 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5409 AndsToMaybeRemove.push_back(I);
5413 case llvm::Instruction::Shl: {
5414 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5417 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5418 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5419 DemandBits |= ShlDemandBits;
5423 case llvm::Instruction::Trunc: {
5424 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5425 unsigned TruncBitWidth = TruncVT.getSizeInBits();
5426 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5427 DemandBits |= TruncBits;
5436 uint32_t ActiveBits = DemandBits.getActiveBits();
5437 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5438 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5439 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5440 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5441 // followed by an AND.
5442 // TODO: Look into removing this restriction by fixing backends to either
5443 // return false for isLoadExtLegal for i1 or have them select this pattern to
5444 // a single instruction.
5446 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5447 // mask, since these are the only ands that will be removed by isel.
5448 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
5449 WidestAndBits != DemandBits)
5452 LLVMContext &Ctx = Load->getType()->getContext();
5453 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5454 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5456 // Reject cases that won't be matched as extloads.
5457 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5458 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5461 IRBuilder<> Builder(Load->getNextNode());
5462 auto *NewAnd = dyn_cast<Instruction>(
5463 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5465 // Replace all uses of load with new and (except for the use of load in the
5467 Load->replaceAllUsesWith(NewAnd);
5468 NewAnd->setOperand(0, Load);
5470 // Remove any and instructions that are now redundant.
5471 for (auto *And : AndsToMaybeRemove)
5472 // Check that the and mask is the same as the one we decided to put on the
5474 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5475 And->replaceAllUsesWith(NewAnd);
5476 if (&*CurInstIterator == And)
5477 CurInstIterator = std::next(And->getIterator());
5478 And->eraseFromParent();
5486 /// Check if V (an operand of a select instruction) is an expensive instruction
5487 /// that is only used once.
5488 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5489 auto *I = dyn_cast<Instruction>(V);
5490 // If it's safe to speculatively execute, then it should not have side
5491 // effects; therefore, it's safe to sink and possibly *not* execute.
5492 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5493 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5496 /// Returns true if a SelectInst should be turned into an explicit branch.
5497 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5499 // FIXME: This should use the same heuristics as IfConversion to determine
5500 // whether a select is better represented as a branch. This requires that
5501 // branch probability metadata is preserved for the select, which is not the
5504 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5506 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5507 // comparison condition. If the compare has more than one use, there's
5508 // probably another cmov or setcc around, so it's not worth emitting a branch.
5509 if (!Cmp || !Cmp->hasOneUse())
5512 Value *CmpOp0 = Cmp->getOperand(0);
5513 Value *CmpOp1 = Cmp->getOperand(1);
5515 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
5516 // on a load from memory. But if the load is used more than once, do not
5517 // change the select to a branch because the load is probably needed
5518 // regardless of whether the branch is taken or not.
5519 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
5520 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
5523 // If either operand of the select is expensive and only needed on one side
5524 // of the select, we should form a branch.
5525 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5526 sinkSelectOperand(TTI, SI->getFalseValue()))
5533 /// If we have a SelectInst that will likely profit from branch prediction,
5534 /// turn it into a branch.
5535 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5536 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5538 // Can we convert the 'select' to CF ?
5539 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
5542 TargetLowering::SelectSupportKind SelectKind;
5544 SelectKind = TargetLowering::VectorMaskSelect;
5545 else if (SI->getType()->isVectorTy())
5546 SelectKind = TargetLowering::ScalarCondVectorVal;
5548 SelectKind = TargetLowering::ScalarValSelect;
5550 // Do we have efficient codegen support for this kind of 'selects' ?
5551 if (TLI->isSelectSupported(SelectKind)) {
5552 // We have efficient codegen support for the select instruction.
5553 // Check if it is profitable to keep this 'select'.
5554 if (!TLI->isPredictableSelectExpensive() ||
5555 !isFormingBranchFromSelectProfitable(TTI, SI))
5561 // Transform a sequence like this:
5563 // %cmp = cmp uge i32 %a, %b
5564 // %sel = select i1 %cmp, i32 %c, i32 %d
5568 // %cmp = cmp uge i32 %a, %b
5569 // br i1 %cmp, label %select.true, label %select.false
5571 // br label %select.end
5573 // br label %select.end
5575 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5577 // In addition, we may sink instructions that produce %c or %d from
5578 // the entry block into the destination(s) of the new branch.
5579 // If the true or false blocks do not contain a sunken instruction, that
5580 // block and its branch may be optimized away. In that case, one side of the
5581 // first branch will point directly to select.end, and the corresponding PHI
5582 // predecessor block will be the start block.
5584 // First, we split the block containing the select into 2 blocks.
5585 BasicBlock *StartBlock = SI->getParent();
5586 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
5587 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5589 // Delete the unconditional branch that was just created by the split.
5590 StartBlock->getTerminator()->eraseFromParent();
5592 // These are the new basic blocks for the conditional branch.
5593 // At least one will become an actual new basic block.
5594 BasicBlock *TrueBlock = nullptr;
5595 BasicBlock *FalseBlock = nullptr;
5597 // Sink expensive instructions into the conditional blocks to avoid executing
5598 // them speculatively.
5599 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5600 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5601 EndBlock->getParent(), EndBlock);
5602 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5603 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5604 TrueInst->moveBefore(TrueBranch);
5606 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5607 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5608 EndBlock->getParent(), EndBlock);
5609 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5610 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5611 FalseInst->moveBefore(FalseBranch);
5614 // If there was nothing to sink, then arbitrarily choose the 'false' side
5615 // for a new input value to the PHI.
5616 if (TrueBlock == FalseBlock) {
5617 assert(TrueBlock == nullptr &&
5618 "Unexpected basic block transform while optimizing select");
5620 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5621 EndBlock->getParent(), EndBlock);
5622 BranchInst::Create(EndBlock, FalseBlock);
5625 // Insert the real conditional branch based on the original condition.
5626 // If we did not create a new block for one of the 'true' or 'false' paths
5627 // of the condition, it means that side of the branch goes to the end block
5628 // directly and the path originates from the start block from the point of
5629 // view of the new PHI.
5630 if (TrueBlock == nullptr) {
5631 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
5632 TrueBlock = StartBlock;
5633 } else if (FalseBlock == nullptr) {
5634 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
5635 FalseBlock = StartBlock;
5637 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
5640 // The select itself is replaced with a PHI Node.
5641 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5643 PN->addIncoming(SI->getTrueValue(), TrueBlock);
5644 PN->addIncoming(SI->getFalseValue(), FalseBlock);
5646 SI->replaceAllUsesWith(PN);
5647 SI->eraseFromParent();
5649 // Instruct OptimizeBlock to skip to the next block.
5650 CurInstIterator = StartBlock->end();
5651 ++NumSelectsExpanded;
5655 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5656 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5658 for (unsigned i = 0; i < Mask.size(); ++i) {
5659 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5661 SplatElem = Mask[i];
5667 /// Some targets have expensive vector shifts if the lanes aren't all the same
5668 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5669 /// it's often worth sinking a shufflevector splat down to its use so that
5670 /// codegen can spot all lanes are identical.
5671 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5672 BasicBlock *DefBB = SVI->getParent();
5674 // Only do this xform if variable vector shifts are particularly expensive.
5675 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5678 // We only expect better codegen by sinking a shuffle if we can recognise a
5680 if (!isBroadcastShuffle(SVI))
5683 // InsertedShuffles - Only insert a shuffle in each block once.
5684 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5686 bool MadeChange = false;
5687 for (User *U : SVI->users()) {
5688 Instruction *UI = cast<Instruction>(U);
5690 // Figure out which BB this ext is used in.
5691 BasicBlock *UserBB = UI->getParent();
5692 if (UserBB == DefBB) continue;
5694 // For now only apply this when the splat is used by a shift instruction.
5695 if (!UI->isShift()) continue;
5697 // Everything checks out, sink the shuffle if the user's block doesn't
5698 // already have a copy.
5699 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5701 if (!InsertedShuffle) {
5702 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5703 assert(InsertPt != UserBB->end());
5705 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5706 SVI->getOperand(2), "", &*InsertPt);
5709 UI->replaceUsesOfWith(SVI, InsertedShuffle);
5713 // If we removed all uses, nuke the shuffle.
5714 if (SVI->use_empty()) {
5715 SVI->eraseFromParent();
5722 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5726 Value *Cond = SI->getCondition();
5727 Type *OldType = Cond->getType();
5728 LLVMContext &Context = Cond->getContext();
5729 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5730 unsigned RegWidth = RegType.getSizeInBits();
5732 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5735 // If the register width is greater than the type width, expand the condition
5736 // of the switch instruction and each case constant to the width of the
5737 // register. By widening the type of the switch condition, subsequent
5738 // comparisons (for case comparisons) will not need to be extended to the
5739 // preferred register width, so we will potentially eliminate N-1 extends,
5740 // where N is the number of cases in the switch.
5741 auto *NewType = Type::getIntNTy(Context, RegWidth);
5743 // Zero-extend the switch condition and case constants unless the switch
5744 // condition is a function argument that is already being sign-extended.
5745 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5746 // everything instead.
5747 Instruction::CastOps ExtType = Instruction::ZExt;
5748 if (auto *Arg = dyn_cast<Argument>(Cond))
5749 if (Arg->hasSExtAttr())
5750 ExtType = Instruction::SExt;
5752 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5753 ExtInst->insertBefore(SI);
5754 SI->setCondition(ExtInst);
5755 for (SwitchInst::CaseIt Case : SI->cases()) {
5756 APInt NarrowConst = Case.getCaseValue()->getValue();
5757 APInt WideConst = (ExtType == Instruction::ZExt) ?
5758 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5759 Case.setValue(ConstantInt::get(Context, WideConst));
5766 /// \brief Helper class to promote a scalar operation to a vector one.
5767 /// This class is used to move downward extractelement transition.
5769 /// a = vector_op <2 x i32>
5770 /// b = extractelement <2 x i32> a, i32 0
5775 /// a = vector_op <2 x i32>
5776 /// c = vector_op a (equivalent to scalar_op on the related lane)
5777 /// * d = extractelement <2 x i32> c, i32 0
5779 /// Assuming both extractelement and store can be combine, we get rid of the
5781 class VectorPromoteHelper {
5782 /// DataLayout associated with the current module.
5783 const DataLayout &DL;
5785 /// Used to perform some checks on the legality of vector operations.
5786 const TargetLowering &TLI;
5788 /// Used to estimated the cost of the promoted chain.
5789 const TargetTransformInfo &TTI;
5791 /// The transition being moved downwards.
5792 Instruction *Transition;
5793 /// The sequence of instructions to be promoted.
5794 SmallVector<Instruction *, 4> InstsToBePromoted;
5795 /// Cost of combining a store and an extract.
5796 unsigned StoreExtractCombineCost;
5797 /// Instruction that will be combined with the transition.
5798 Instruction *CombineInst;
5800 /// \brief The instruction that represents the current end of the transition.
5801 /// Since we are faking the promotion until we reach the end of the chain
5802 /// of computation, we need a way to get the current end of the transition.
5803 Instruction *getEndOfTransition() const {
5804 if (InstsToBePromoted.empty())
5806 return InstsToBePromoted.back();
5809 /// \brief Return the index of the original value in the transition.
5810 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5811 /// c, is at index 0.
5812 unsigned getTransitionOriginalValueIdx() const {
5813 assert(isa<ExtractElementInst>(Transition) &&
5814 "Other kind of transitions are not supported yet");
5818 /// \brief Return the index of the index in the transition.
5819 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5821 unsigned getTransitionIdx() const {
5822 assert(isa<ExtractElementInst>(Transition) &&
5823 "Other kind of transitions are not supported yet");
5827 /// \brief Get the type of the transition.
5828 /// This is the type of the original value.
5829 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5830 /// transition is <2 x i32>.
5831 Type *getTransitionType() const {
5832 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5835 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5836 /// I.e., we have the following sequence:
5837 /// Def = Transition <ty1> a to <ty2>
5838 /// b = ToBePromoted <ty2> Def, ...
5840 /// b = ToBePromoted <ty1> a, ...
5841 /// Def = Transition <ty1> ToBePromoted to <ty2>
5842 void promoteImpl(Instruction *ToBePromoted);
5844 /// \brief Check whether or not it is profitable to promote all the
5845 /// instructions enqueued to be promoted.
5846 bool isProfitableToPromote() {
5847 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5848 unsigned Index = isa<ConstantInt>(ValIdx)
5849 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5851 Type *PromotedType = getTransitionType();
5853 StoreInst *ST = cast<StoreInst>(CombineInst);
5854 unsigned AS = ST->getPointerAddressSpace();
5855 unsigned Align = ST->getAlignment();
5856 // Check if this store is supported.
5857 if (!TLI.allowsMisalignedMemoryAccesses(
5858 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5860 // If this is not supported, there is no way we can combine
5861 // the extract with the store.
5865 // The scalar chain of computation has to pay for the transition
5866 // scalar to vector.
5867 // The vector chain has to account for the combining cost.
5868 uint64_t ScalarCost =
5869 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5870 uint64_t VectorCost = StoreExtractCombineCost;
5871 for (const auto &Inst : InstsToBePromoted) {
5872 // Compute the cost.
5873 // By construction, all instructions being promoted are arithmetic ones.
5874 // Moreover, one argument is a constant that can be viewed as a splat
5876 Value *Arg0 = Inst->getOperand(0);
5877 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5878 isa<ConstantFP>(Arg0);
5879 TargetTransformInfo::OperandValueKind Arg0OVK =
5880 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5881 : TargetTransformInfo::OK_AnyValue;
5882 TargetTransformInfo::OperandValueKind Arg1OVK =
5883 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5884 : TargetTransformInfo::OK_AnyValue;
5885 ScalarCost += TTI.getArithmeticInstrCost(
5886 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5887 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5890 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5891 << ScalarCost << "\nVector: " << VectorCost << '\n');
5892 return ScalarCost > VectorCost;
5895 /// \brief Generate a constant vector with \p Val with the same
5896 /// number of elements as the transition.
5897 /// \p UseSplat defines whether or not \p Val should be replicated
5898 /// across the whole vector.
5899 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5900 /// otherwise we generate a vector with as many undef as possible:
5901 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5902 /// used at the index of the extract.
5903 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5904 unsigned ExtractIdx = UINT_MAX;
5906 // If we cannot determine where the constant must be, we have to
5907 // use a splat constant.
5908 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5909 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5910 ExtractIdx = CstVal->getSExtValue();
5915 unsigned End = getTransitionType()->getVectorNumElements();
5917 return ConstantVector::getSplat(End, Val);
5919 SmallVector<Constant *, 4> ConstVec;
5920 UndefValue *UndefVal = UndefValue::get(Val->getType());
5921 for (unsigned Idx = 0; Idx != End; ++Idx) {
5922 if (Idx == ExtractIdx)
5923 ConstVec.push_back(Val);
5925 ConstVec.push_back(UndefVal);
5927 return ConstantVector::get(ConstVec);
5930 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5931 /// in \p Use can trigger undefined behavior.
5932 static bool canCauseUndefinedBehavior(const Instruction *Use,
5933 unsigned OperandIdx) {
5934 // This is not safe to introduce undef when the operand is on
5935 // the right hand side of a division-like instruction.
5936 if (OperandIdx != 1)
5938 switch (Use->getOpcode()) {
5941 case Instruction::SDiv:
5942 case Instruction::UDiv:
5943 case Instruction::SRem:
5944 case Instruction::URem:
5946 case Instruction::FDiv:
5947 case Instruction::FRem:
5948 return !Use->hasNoNaNs();
5950 llvm_unreachable(nullptr);
5954 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5955 const TargetTransformInfo &TTI, Instruction *Transition,
5956 unsigned CombineCost)
5957 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5958 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5959 assert(Transition && "Do not know how to promote null");
5962 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5963 bool canPromote(const Instruction *ToBePromoted) const {
5964 // We could support CastInst too.
5965 return isa<BinaryOperator>(ToBePromoted);
5968 /// \brief Check if it is profitable to promote \p ToBePromoted
5969 /// by moving downward the transition through.
5970 bool shouldPromote(const Instruction *ToBePromoted) const {
5971 // Promote only if all the operands can be statically expanded.
5972 // Indeed, we do not want to introduce any new kind of transitions.
5973 for (const Use &U : ToBePromoted->operands()) {
5974 const Value *Val = U.get();
5975 if (Val == getEndOfTransition()) {
5976 // If the use is a division and the transition is on the rhs,
5977 // we cannot promote the operation, otherwise we may create a
5978 // division by zero.
5979 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5983 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5984 !isa<ConstantFP>(Val))
5987 // Check that the resulting operation is legal.
5988 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5991 return StressStoreExtract ||
5992 TLI.isOperationLegalOrCustom(
5993 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5996 /// \brief Check whether or not \p Use can be combined
5997 /// with the transition.
5998 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5999 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6001 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
6002 void enqueueForPromotion(Instruction *ToBePromoted) {
6003 InstsToBePromoted.push_back(ToBePromoted);
6006 /// \brief Set the instruction that will be combined with the transition.
6007 void recordCombineInstruction(Instruction *ToBeCombined) {
6008 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6009 CombineInst = ToBeCombined;
6012 /// \brief Promote all the instructions enqueued for promotion if it is
6014 /// \return True if the promotion happened, false otherwise.
6016 // Check if there is something to promote.
6017 // Right now, if we do not have anything to combine with,
6018 // we assume the promotion is not profitable.
6019 if (InstsToBePromoted.empty() || !CombineInst)
6023 if (!StressStoreExtract && !isProfitableToPromote())
6027 for (auto &ToBePromoted : InstsToBePromoted)
6028 promoteImpl(ToBePromoted);
6029 InstsToBePromoted.clear();
6033 } // End of anonymous namespace.
6035 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6036 // At this point, we know that all the operands of ToBePromoted but Def
6037 // can be statically promoted.
6038 // For Def, we need to use its parameter in ToBePromoted:
6039 // b = ToBePromoted ty1 a
6040 // Def = Transition ty1 b to ty2
6041 // Move the transition down.
6042 // 1. Replace all uses of the promoted operation by the transition.
6043 // = ... b => = ... Def.
6044 assert(ToBePromoted->getType() == Transition->getType() &&
6045 "The type of the result of the transition does not match "
6047 ToBePromoted->replaceAllUsesWith(Transition);
6048 // 2. Update the type of the uses.
6049 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6050 Type *TransitionTy = getTransitionType();
6051 ToBePromoted->mutateType(TransitionTy);
6052 // 3. Update all the operands of the promoted operation with promoted
6054 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6055 for (Use &U : ToBePromoted->operands()) {
6056 Value *Val = U.get();
6057 Value *NewVal = nullptr;
6058 if (Val == Transition)
6059 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6060 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6061 isa<ConstantFP>(Val)) {
6062 // Use a splat constant if it is not safe to use undef.
6063 NewVal = getConstantVector(
6064 cast<Constant>(Val),
6065 isa<UndefValue>(Val) ||
6066 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6068 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6070 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6072 Transition->removeFromParent();
6073 Transition->insertAfter(ToBePromoted);
6074 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6077 /// Some targets can do store(extractelement) with one instruction.
6078 /// Try to push the extractelement towards the stores when the target
6079 /// has this feature and this is profitable.
6080 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
6081 unsigned CombineCost = UINT_MAX;
6082 if (DisableStoreExtract || !TLI ||
6083 (!StressStoreExtract &&
6084 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6085 Inst->getOperand(1), CombineCost)))
6088 // At this point we know that Inst is a vector to scalar transition.
6089 // Try to move it down the def-use chain, until:
6090 // - We can combine the transition with its single use
6091 // => we got rid of the transition.
6092 // - We escape the current basic block
6093 // => we would need to check that we are moving it at a cheaper place and
6094 // we do not do that for now.
6095 BasicBlock *Parent = Inst->getParent();
6096 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
6097 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6098 // If the transition has more than one use, assume this is not going to be
6100 while (Inst->hasOneUse()) {
6101 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6102 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6104 if (ToBePromoted->getParent() != Parent) {
6105 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6106 << ToBePromoted->getParent()->getName()
6107 << ") than the transition (" << Parent->getName() << ").\n");
6111 if (VPH.canCombine(ToBePromoted)) {
6112 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6113 << "will be combined with: " << *ToBePromoted << '\n');
6114 VPH.recordCombineInstruction(ToBePromoted);
6115 bool Changed = VPH.promote();
6116 NumStoreExtractExposed += Changed;
6120 DEBUG(dbgs() << "Try promoting.\n");
6121 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6124 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6126 VPH.enqueueForPromotion(ToBePromoted);
6127 Inst = ToBePromoted;
6132 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
6133 // Bail out if we inserted the instruction to prevent optimizations from
6134 // stepping on each other's toes.
6135 if (InsertedInsts.count(I))
6138 if (PHINode *P = dyn_cast<PHINode>(I)) {
6139 // It is possible for very late stage optimizations (such as SimplifyCFG)
6140 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6141 // trivial PHI, go ahead and zap it here.
6142 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
6143 P->replaceAllUsesWith(V);
6144 P->eraseFromParent();
6151 if (CastInst *CI = dyn_cast<CastInst>(I)) {
6152 // If the source of the cast is a constant, then this should have
6153 // already been constant folded. The only reason NOT to constant fold
6154 // it is if something (e.g. LSR) was careful to place the constant
6155 // evaluation in a block other than then one that uses it (e.g. to hoist
6156 // the address of globals out of a loop). If this is the case, we don't
6157 // want to forward-subst the cast.
6158 if (isa<Constant>(CI->getOperand(0)))
6161 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
6164 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6165 /// Sink a zext or sext into its user blocks if the target type doesn't
6166 /// fit in one register
6168 TLI->getTypeAction(CI->getContext(),
6169 TLI->getValueType(*DL, CI->getType())) ==
6170 TargetLowering::TypeExpandInteger) {
6171 return SinkCast(CI);
6173 bool MadeChange = moveExtToFormExtLoad(I);
6174 return MadeChange | optimizeExtUses(I);
6180 if (CmpInst *CI = dyn_cast<CmpInst>(I))
6181 if (!TLI || !TLI->hasMultipleConditionRegisters())
6182 return OptimizeCmpExpression(CI);
6184 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6185 stripInvariantGroupMetadata(*LI);
6187 bool Modified = optimizeLoadExt(LI);
6188 unsigned AS = LI->getPointerAddressSpace();
6189 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6195 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6196 stripInvariantGroupMetadata(*SI);
6198 unsigned AS = SI->getPointerAddressSpace();
6199 return optimizeMemoryInst(I, SI->getOperand(1),
6200 SI->getOperand(0)->getType(), AS);
6205 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6207 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6208 BinOp->getOpcode() == Instruction::LShr)) {
6209 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6210 if (TLI && CI && TLI->hasExtractBitsInsn())
6211 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6216 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6217 if (GEPI->hasAllZeroIndices()) {
6218 /// The GEP operand must be a pointer, so must its result -> BitCast
6219 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6220 GEPI->getName(), GEPI);
6221 GEPI->replaceAllUsesWith(NC);
6222 GEPI->eraseFromParent();
6224 optimizeInst(NC, ModifiedDT);
6230 if (CallInst *CI = dyn_cast<CallInst>(I))
6231 return optimizeCallInst(CI, ModifiedDT);
6233 if (SelectInst *SI = dyn_cast<SelectInst>(I))
6234 return optimizeSelectInst(SI);
6236 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6237 return optimizeShuffleVectorInst(SVI);
6239 if (auto *Switch = dyn_cast<SwitchInst>(I))
6240 return optimizeSwitchInst(Switch);
6242 if (isa<ExtractElementInst>(I))
6243 return optimizeExtractElementInst(I);
6248 /// Given an OR instruction, check to see if this is a bitreverse
6249 /// idiom. If so, insert the new intrinsic and return true.
6250 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6251 const TargetLowering &TLI) {
6252 if (!I.getType()->isIntegerTy() ||
6253 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6254 TLI.getValueType(DL, I.getType(), true)))
6257 SmallVector<Instruction*, 4> Insts;
6258 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
6260 Instruction *LastInst = Insts.back();
6261 I.replaceAllUsesWith(LastInst);
6262 RecursivelyDeleteTriviallyDeadInstructions(&I);
6266 // In this pass we look for GEP and cast instructions that are used
6267 // across basic blocks and rewrite them to improve basic-block-at-a-time
6269 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
6271 bool MadeChange = false;
6273 CurInstIterator = BB.begin();
6274 while (CurInstIterator != BB.end()) {
6275 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6280 bool MadeBitReverse = true;
6281 while (TLI && MadeBitReverse) {
6282 MadeBitReverse = false;
6283 for (auto &I : reverse(BB)) {
6284 if (makeBitReverse(I, *DL, *TLI)) {
6285 MadeBitReverse = MadeChange = true;
6290 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6295 // llvm.dbg.value is far away from the value then iSel may not be able
6296 // handle it properly. iSel will drop llvm.dbg.value if it can not
6297 // find a node corresponding to the value.
6298 bool CodeGenPrepare::placeDbgValues(Function &F) {
6299 bool MadeChange = false;
6300 for (BasicBlock &BB : F) {
6301 Instruction *PrevNonDbgInst = nullptr;
6302 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6303 Instruction *Insn = &*BI++;
6304 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6305 // Leave dbg.values that refer to an alloca alone. These
6306 // instrinsics describe the address of a variable (= the alloca)
6307 // being taken. They should not be moved next to the alloca
6308 // (and to the beginning of the scope), but rather stay close to
6309 // where said address is used.
6310 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6311 PrevNonDbgInst = Insn;
6315 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6316 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6317 // If VI is a phi in a block with an EHPad terminator, we can't insert
6319 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6321 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6322 DVI->removeFromParent();
6323 if (isa<PHINode>(VI))
6324 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6326 DVI->insertAfter(VI);
6335 // If there is a sequence that branches based on comparing a single bit
6336 // against zero that can be combined into a single instruction, and the
6337 // target supports folding these into a single instruction, sink the
6338 // mask and compare into the branch uses. Do this before OptimizeBlock ->
6339 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
6341 bool CodeGenPrepare::sinkAndCmp(Function &F) {
6342 if (!EnableAndCmpSinking)
6344 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
6346 bool MadeChange = false;
6347 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
6348 BasicBlock *BB = &*I++;
6350 // Does this BB end with the following?
6351 // %andVal = and %val, #single-bit-set
6352 // %icmpVal = icmp %andResult, 0
6353 // br i1 %cmpVal label %dest1, label %dest2"
6354 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
6355 if (!Brcc || !Brcc->isConditional())
6357 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
6358 if (!Cmp || Cmp->getParent() != BB)
6360 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
6361 if (!Zero || !Zero->isZero())
6363 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
6364 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
6366 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
6367 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
6369 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
6371 // Push the "and; icmp" for any users that are conditional branches.
6372 // Since there can only be one branch use per BB, we don't need to keep
6373 // track of which BBs we insert into.
6374 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
6378 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
6380 if (!BrccUser || !BrccUser->isConditional())
6382 BasicBlock *UserBB = BrccUser->getParent();
6383 if (UserBB == BB) continue;
6384 DEBUG(dbgs() << "found Brcc use\n");
6386 // Sink the "and; icmp" to use.
6388 BinaryOperator *NewAnd =
6389 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
6392 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
6396 DEBUG(BrccUser->getParent()->dump());
6402 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
6403 /// success, or returns false if no or invalid metadata was found.
6404 static bool extractBranchMetadata(BranchInst *BI,
6405 uint64_t &ProbTrue, uint64_t &ProbFalse) {
6406 assert(BI->isConditional() &&
6407 "Looking for probabilities on unconditional branch?");
6408 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
6409 if (!ProfileData || ProfileData->getNumOperands() != 3)
6412 const auto *CITrue =
6413 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
6414 const auto *CIFalse =
6415 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
6416 if (!CITrue || !CIFalse)
6419 ProbTrue = CITrue->getValue().getZExtValue();
6420 ProbFalse = CIFalse->getValue().getZExtValue();
6425 /// \brief Scale down both weights to fit into uint32_t.
6426 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6427 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6428 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6429 NewTrue = NewTrue / Scale;
6430 NewFalse = NewFalse / Scale;
6433 /// \brief Some targets prefer to split a conditional branch like:
6435 /// %0 = icmp ne i32 %a, 0
6436 /// %1 = icmp ne i32 %b, 0
6437 /// %or.cond = or i1 %0, %1
6438 /// br i1 %or.cond, label %TrueBB, label %FalseBB
6440 /// into multiple branch instructions like:
6443 /// %0 = icmp ne i32 %a, 0
6444 /// br i1 %0, label %TrueBB, label %bb2
6446 /// %1 = icmp ne i32 %b, 0
6447 /// br i1 %1, label %TrueBB, label %FalseBB
6449 /// This usually allows instruction selection to do even further optimizations
6450 /// and combine the compare with the branch instruction. Currently this is
6451 /// applied for targets which have "cheap" jump instructions.
6453 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6455 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6456 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6459 bool MadeChange = false;
6460 for (auto &BB : F) {
6461 // Does this BB end with the following?
6462 // %cond1 = icmp|fcmp|binary instruction ...
6463 // %cond2 = icmp|fcmp|binary instruction ...
6464 // %cond.or = or|and i1 %cond1, cond2
6465 // br i1 %cond.or label %dest1, label %dest2"
6466 BinaryOperator *LogicOp;
6467 BasicBlock *TBB, *FBB;
6468 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6471 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6472 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6476 Value *Cond1, *Cond2;
6477 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6478 m_OneUse(m_Value(Cond2)))))
6479 Opc = Instruction::And;
6480 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6481 m_OneUse(m_Value(Cond2)))))
6482 Opc = Instruction::Or;
6486 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6487 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6490 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6493 auto *InsertBefore = std::next(Function::iterator(BB))
6494 .getNodePtrUnchecked();
6495 auto TmpBB = BasicBlock::Create(BB.getContext(),
6496 BB.getName() + ".cond.split",
6497 BB.getParent(), InsertBefore);
6499 // Update original basic block by using the first condition directly by the
6500 // branch instruction and removing the no longer needed and/or instruction.
6501 Br1->setCondition(Cond1);
6502 LogicOp->eraseFromParent();
6504 // Depending on the conditon we have to either replace the true or the false
6505 // successor of the original branch instruction.
6506 if (Opc == Instruction::And)
6507 Br1->setSuccessor(0, TmpBB);
6509 Br1->setSuccessor(1, TmpBB);
6511 // Fill in the new basic block.
6512 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6513 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6514 I->removeFromParent();
6515 I->insertBefore(Br2);
6518 // Update PHI nodes in both successors. The original BB needs to be
6519 // replaced in one succesor's PHI nodes, because the branch comes now from
6520 // the newly generated BB (NewBB). In the other successor we need to add one
6521 // incoming edge to the PHI nodes, because both branch instructions target
6522 // now the same successor. Depending on the original branch condition
6523 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6524 // we perfrom the correct update for the PHI nodes.
6525 // This doesn't change the successor order of the just created branch
6526 // instruction (or any other instruction).
6527 if (Opc == Instruction::Or)
6528 std::swap(TBB, FBB);
6530 // Replace the old BB with the new BB.
6531 for (auto &I : *TBB) {
6532 PHINode *PN = dyn_cast<PHINode>(&I);
6536 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6537 PN->setIncomingBlock(i, TmpBB);
6540 // Add another incoming edge form the new BB.
6541 for (auto &I : *FBB) {
6542 PHINode *PN = dyn_cast<PHINode>(&I);
6545 auto *Val = PN->getIncomingValueForBlock(&BB);
6546 PN->addIncoming(Val, TmpBB);
6549 // Update the branch weights (from SelectionDAGBuilder::
6550 // FindMergedConditions).
6551 if (Opc == Instruction::Or) {
6552 // Codegen X | Y as:
6561 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6562 // The requirement is that
6563 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6564 // = TrueProb for orignal BB.
6565 // Assuming the orignal weights are A and B, one choice is to set BB1's
6566 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6568 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6569 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6570 // TmpBB, but the math is more complicated.
6571 uint64_t TrueWeight, FalseWeight;
6572 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6573 uint64_t NewTrueWeight = TrueWeight;
6574 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6575 scaleWeights(NewTrueWeight, NewFalseWeight);
6576 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6577 .createBranchWeights(TrueWeight, FalseWeight));
6579 NewTrueWeight = TrueWeight;
6580 NewFalseWeight = 2 * FalseWeight;
6581 scaleWeights(NewTrueWeight, NewFalseWeight);
6582 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6583 .createBranchWeights(TrueWeight, FalseWeight));
6586 // Codegen X & Y as:
6594 // This requires creation of TmpBB after CurBB.
6596 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6597 // The requirement is that
6598 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6599 // = FalseProb for orignal BB.
6600 // Assuming the orignal weights are A and B, one choice is to set BB1's
6601 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6603 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6604 uint64_t TrueWeight, FalseWeight;
6605 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6606 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6607 uint64_t NewFalseWeight = FalseWeight;
6608 scaleWeights(NewTrueWeight, NewFalseWeight);
6609 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6610 .createBranchWeights(TrueWeight, FalseWeight));
6612 NewTrueWeight = 2 * TrueWeight;
6613 NewFalseWeight = FalseWeight;
6614 scaleWeights(NewTrueWeight, NewFalseWeight);
6615 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6616 .createBranchWeights(TrueWeight, FalseWeight));
6620 // Note: No point in getting fancy here, since the DT info is never
6621 // available to CodeGenPrepare.
6626 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6632 void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
6633 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
6634 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());