1a07bfc0c3577f71585153b63635d87173c47479
[oota-llvm.git] / lib / CodeGen / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
58 using namespace llvm;
59 using namespace llvm::PatternMatch;
60
61 #define DEBUG_TYPE "codegenprepare"
62
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 "
67                       "sunken Cmps");
68 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
69                        "of sunken Casts");
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");
82
83 static cl::opt<bool> DisableBranchOpts(
84   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
85   cl::desc("Disable branch optimizations in CodeGenPrepare"));
86
87 static cl::opt<bool>
88     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
89                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
90
91 static cl::opt<bool> DisableSelectToBranch(
92   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
93   cl::desc("Disable select to branch conversion."));
94
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."));
98
99 static cl::opt<bool> EnableAndCmpSinking(
100    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
101    cl::desc("Enable sinkinig and/cmp into branches."));
102
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"));
106
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"));
110
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 "
114              "CodeGenPrepare"));
115
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"));
120
121 namespace {
122 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
123 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
124 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
125 class TypePromotionTransaction;
126
127   class CodeGenPrepare : public FunctionPass {
128     const TargetMachine *TM;
129     const TargetLowering *TLI;
130     const TargetTransformInfo *TTI;
131     const TargetLibraryInfo *TLInfo;
132
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;
136
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;
141
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;
147
148     /// True if CFG is modified in any way.
149     bool ModifiedDT;
150
151     /// True if optimizing for size.
152     bool OptSize;
153
154     /// DataLayout for the Function being processed.
155     const DataLayout *DL;
156
157   public:
158     static char ID; // Pass identification, replacement for typeid
159     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
160         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
161         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
162       }
163     bool runOnFunction(Function &F) override;
164
165     const char *getPassName() const override { return "CodeGen Prepare"; }
166
167     void getAnalysisUsage(AnalysisUsage &AU) const override {
168       AU.addPreserved<DominatorTreeWrapperPass>();
169       AU.addRequired<TargetLibraryInfoWrapperPass>();
170       AU.addRequired<TargetTransformInfoWrapperPass>();
171     }
172
173   private:
174     bool eliminateFallThrough(Function &F);
175     bool eliminateMostlyEmptyBlocks(Function &F);
176     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
177     void eliminateMostlyEmptyBlock(BasicBlock *BB);
178     bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
179     bool optimizeInst(Instruction *I, bool& ModifiedDT);
180     bool optimizeMemoryInst(Instruction *I, Value *Addr,
181                             Type *AccessTy, unsigned AS);
182     bool optimizeInlineAsmInst(CallInst *CS);
183     bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
184     bool moveExtToFormExtLoad(Instruction *&I);
185     bool optimizeExtUses(Instruction *I);
186     bool optimizeLoadExt(LoadInst *I);
187     bool optimizeSelectInst(SelectInst *SI);
188     bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
189     bool optimizeSwitchInst(SwitchInst *CI);
190     bool optimizeExtractElementInst(Instruction *Inst);
191     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
192     bool placeDbgValues(Function &F);
193     bool sinkAndCmp(Function &F);
194     bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
195                         Instruction *&Inst,
196                         const SmallVectorImpl<Instruction *> &Exts,
197                         unsigned CreatedInstCost);
198     bool splitBranchCondition(Function &F);
199     bool simplifyOffsetableRelocate(Instruction &I);
200     void stripInvariantGroupMetadata(Instruction &I);
201   };
202 }
203
204 char CodeGenPrepare::ID = 0;
205 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
206                    "Optimize for code generation", false, false)
207
208 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
209   return new CodeGenPrepare(TM);
210 }
211
212 namespace {
213
214 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
215 Value* GetUntaintedAddress(Value* CurrentAddress);
216
217 // The depth we trace down a variable to look for its dependence set.
218 const unsigned kDependenceDepth = 4;
219
220 // Recursively looks for variables that 'Val' depends on at the given depth
221 // 'Depth', and adds them in 'DepSet'. If 'InsertOnlyLeafNodes' is true, only
222 // inserts the leaf node values; otherwise, all visited nodes are included in
223 // 'DepSet'. Note that constants will be ignored.
224 template <typename SetType>
225 void recursivelyFindDependence(SetType* DepSet, Value* Val,
226                                bool InsertOnlyLeafNodes = false,
227                                unsigned Depth = kDependenceDepth) {
228   if (Val == nullptr) {
229     return;
230   }
231   if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
232     DepSet->insert(Val);
233   }
234   if (Depth == 0) {
235     // Cannot go deeper. Insert the leaf nodes.
236     if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
237       DepSet->insert(Val);
238     }
239     return;
240   }
241
242   // Go one step further to explore the dependence of the operands.
243   Instruction* I = nullptr;
244   if ((I = dyn_cast<Instruction>(Val))) {
245     if (isa<LoadInst>(I)) {
246       // A load is considerd the leaf load of the dependence tree. Done.
247       DepSet->insert(Val);
248       return;
249     } else if (I->isBinaryOp()) {
250       BinaryOperator* I = dyn_cast<BinaryOperator>(Val);
251       Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
252       recursivelyFindDependence(DepSet, Op0, Depth - 1);
253       recursivelyFindDependence(DepSet, Op1, Depth - 1);
254     } else if (I->isCast()) {
255       Value* Op0 = I->getOperand(0);
256       recursivelyFindDependence(DepSet, Op0, Depth - 1);
257     } else if (I->getOpcode() == Instruction::Select) {
258       Value* Op0 = I->getOperand(0);
259       Value* Op1 = I->getOperand(1);
260       Value* Op2 = I->getOperand(2);
261       recursivelyFindDependence(DepSet, Op0, Depth - 1);
262       recursivelyFindDependence(DepSet, Op1, Depth - 1);
263       recursivelyFindDependence(DepSet, Op2, Depth - 1);
264     } else if (I->getOpcode() == Instruction::GetElementPtr) {
265       for (unsigned i = 0; i < I->getNumOperands(); i++) {
266         recursivelyFindDependence(DepSet, I->getOperand(i), Depth - 1);
267       }
268     } else if (I->getOpcode() == Instruction::Store) {
269       auto* SI = dyn_cast<StoreInst>(Val);
270       recursivelyFindDependence(DepSet, SI->getPointerOperand(), Depth - 1);
271       recursivelyFindDependence(DepSet, SI->getValueOperand(), Depth - 1);
272     } else {
273       Value* Op0 = nullptr;
274       Value* Op1 = nullptr;
275       switch (I->getOpcode()) {
276         case Instruction::ICmp:
277         case Instruction::FCmp: {
278           Op0 = I->getOperand(0);
279           Op1 = I->getOperand(1);
280           recursivelyFindDependence(DepSet, Op0, Depth - 1);
281           recursivelyFindDependence(DepSet, Op1, Depth - 1);
282           break;
283         }
284         default: {
285           // Be conservative. Add it and be done with it.
286           DepSet->insert(Val);
287           return;
288         }
289       }
290     }
291   } else if (isa<Constant>(Val)) {
292     // Not interested in constant values. Done.
293     return;
294   } else {
295     // Be conservative. Add it and be done with it.
296     DepSet->insert(Val);
297     return;
298   }
299 }
300
301 // Helper function to create a Cast instruction.
302 Value* createCast(IRBuilder<true, NoFolder>& Builder, Value* DepVal,
303                   Type* TargetIntegerType) {
304   Instruction::CastOps CastOp = Instruction::BitCast;
305   switch (DepVal->getType()->getTypeID()) {
306     case Type::IntegerTyID: {
307       CastOp = Instruction::SExt;
308       break;
309     }
310     case Type::FloatTyID:
311     case Type::DoubleTyID: {
312       CastOp = Instruction::FPToSI;
313       break;
314     }
315     case Type::PointerTyID: {
316       CastOp = Instruction::PtrToInt;
317       break;
318     }
319     default: { break; }
320   }
321
322   return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
323 }
324
325 // Given a value, if it's a tainted address, this function returns the
326 // instruction that ORs the "dependence value" with the "original address".
327 // Otherwise, returns nullptr.  This instruction is the first OR instruction
328 // where one of its operand is an AND instruction with an operand being 0.
329 //
330 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
331 // %0 = load i32, i32* @y, align 4, !tbaa !1
332 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
333 // %1 = sext i1 %cmp to i32
334 // %2 = ptrtoint i32* @x to i32
335 // %3 = and i32 %1, 0
336 // %4 = or i32 %3, %2
337 // %5 = inttoptr i32 %4 to i32*
338 // store i32 1, i32* %5, align 4
339 Instruction* getOrAddress(Value* CurrentAddress) {
340   // Is it a cast from integer to pointer type.
341   Instruction* OrAddress = nullptr;
342   Instruction* AndDep = nullptr;
343   Instruction* CastToInt = nullptr;
344   Value* ActualAddress = nullptr;
345   Constant* ZeroConst = nullptr;
346
347   const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
348   if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
349     // Is it an OR instruction: %1 = or %and, %actualAddress.
350     if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
351         OrAddress->getOpcode() == Instruction::Or) {
352       // The first operand should be and AND instruction.
353       AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
354       if (AndDep && AndDep->getOpcode() == Instruction::And) {
355         // Also make sure its first operand of the "AND" is 0, or the "AND" is
356         // marked explicitly by "NoInstCombine".
357         if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
358             ZeroConst->isNullValue()) {
359           return OrAddress;
360         }
361       }
362     }
363   }
364   // Looks like it's not been tainted.
365   return nullptr;
366 }
367
368 // Given a value, if it's a tainted address, this function returns the
369 // instruction that taints the "dependence value". Otherwise, returns nullptr.
370 // This instruction is the last AND instruction where one of its operand is 0.
371 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
372 // %0 = load i32, i32* @y, align 4, !tbaa !1
373 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
374 // %1 = sext i1 %cmp to i32
375 // %2 = ptrtoint i32* @x to i32
376 // %3 = and i32 %1, 0
377 // %4 = or i32 %3, %2
378 // %5 = inttoptr i32 %4 to i32*
379 // store i32 1, i32* %5, align 4
380 Instruction* getAndDependence(Value* CurrentAddress) {
381   // If 'CurrentAddress' is tainted, get the OR instruction.
382   auto* OrAddress = getOrAddress(CurrentAddress);
383   if (OrAddress == nullptr) {
384     return nullptr;
385   }
386
387   // No need to check the operands.
388   auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
389   assert(AndDepInst);
390   return AndDepInst;
391 }
392
393 // Given a value, if it's a tainted address, this function returns
394 // the "dependence value", which is the first operand in the AND instruction.
395 // E.g., it returns '%1' 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 Value* getDependence(Value* CurrentAddress) {
405   auto* AndInst = getAndDependence(CurrentAddress);
406   if (AndInst == nullptr) {
407     return nullptr;
408   }
409   return AndInst->getOperand(0);
410 }
411
412 // Given an address that has been tainted, returns the only condition it depends
413 // on, if any; otherwise, returns nullptr.
414 Value* getConditionDependence(Value* Address) {
415   auto* Dep = getDependence(Address);
416   if (Dep == nullptr) {
417     // 'Address' has not been dependence-tainted.
418     return nullptr;
419   }
420
421   Value* Operand = Dep;
422   while (true) {
423     auto* Inst = dyn_cast<Instruction>(Operand);
424     if (Inst == nullptr) {
425       // Non-instruction type does not have condition dependence.
426       return nullptr;
427     }
428     if (Inst->getOpcode() == Instruction::ICmp) {
429       return Inst;
430     } else {
431       if (Inst->getNumOperands() != 1) {
432         return nullptr;
433       } else {
434         Operand = Inst->getOperand(0);
435       }
436     }
437   }
438 }
439
440 // Conservatively decides whether the dependence set of 'Val1' includes the
441 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
442 // 'Val2' and use that single value as its dependence set.
443 // If it returns true, it means the dependence set of 'Val1' includes that of
444 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
445 bool dependenceSetInclusion(Value* Val1, Value* Val2,
446                             int Val1ExpandLevel = 2 * kDependenceDepth,
447                             int Val2ExpandLevel = kDependenceDepth) {
448   typedef SmallSet<Value*, 8> IncludingSet;
449   typedef SmallSet<Value*, 4> IncludedSet;
450
451   IncludingSet DepSet1;
452   IncludedSet DepSet2;
453   // Look for more depths for the including set.
454   recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
455                             Val1ExpandLevel);
456   recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
457                             Val2ExpandLevel);
458
459   auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
460     for (auto* Dep : Subset) {
461       if (0 == FullSet.count(Dep)) {
462         return false;
463       }
464     }
465     return true;
466   };
467   bool inclusion = set_inclusion(DepSet1, DepSet2);
468   DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
469   DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
470   DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
471   DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
472   DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
473
474   return inclusion;
475 }
476
477 // Recursively iterates through the operands spawned from 'DepVal'. If there
478 // exists a single value that 'DepVal' only depends on, we call that value the
479 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
480 Value* getRootDependence(Value* DepVal) {
481   SmallSet<Value*, 8> DepSet;
482   for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
483     recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
484                               depth);
485     if (DepSet.size() == 1) {
486       return *DepSet.begin();
487     }
488     DepSet.clear();
489   }
490   return DepVal;
491 }
492
493 // This function actually taints 'DepVal' to the address to 'SI'. If the
494 // address
495 // of 'SI' already depends on whatever 'DepVal' depends on, this function
496 // doesn't do anything and returns false. Otherwise, returns true.
497 //
498 // This effect forces the store and any stores that comes later to depend on
499 // 'DepVal'. For example, we have a condition "cond", and a store instruction
500 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
501 // "cond", we do the following:
502 // %conv = sext i1 %cond to i32
503 // %addrVal = ptrtoint i32* %addr to i32
504 // %andCond = and i32 conv, 0;
505 // %orAddr = or i32 %andCond, %addrVal;
506 // %NewAddr = inttoptr i32 %orAddr to i32*;
507 //
508 // This is a more concrete example:
509 // ------
510 // %0 = load i32, i32* @y, align 4, !tbaa !1
511 // %cmp = icmp ne i32 %0, 42  // <== this is like the condition
512 // %1 = sext i1 %cmp to i32
513 // %2 = ptrtoint i32* @x to i32
514 // %3 = and i32 %1, 0
515 // %4 = or i32 %3, %2
516 // %5 = inttoptr i32 %4 to i32*
517 // store i32 1, i32* %5, align 4
518 bool taintStoreAddress(StoreInst* SI, Value* DepVal,
519                        const char* calling_func = __builtin_FUNCTION()) {
520   DEBUG(dbgs() << "Called from " << calling_func << '\n');
521   IRBuilder<true, NoFolder> Builder(SI);
522   BasicBlock* BB = SI->getParent();
523   Value* Address = SI->getPointerOperand();
524   Type* TargetIntegerType =
525       IntegerType::get(Address->getContext(),
526                        BB->getModule()->getDataLayout().getPointerSizeInBits());
527
528   // Does SI's address already depends on whatever 'DepVal' depends on?
529   if (StoreAddressDependOnValue(SI, DepVal)) {
530     return false;
531   }
532
533   // Figure out if there's a root variable 'DepVal' depends on. For example, we
534   // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
535   // to be "%struct* %0" since all other operands are constant.
536   DepVal = getRootDependence(DepVal);
537
538   // Is this already a dependence-tainted store?
539   Value* OldDep = getDependence(Address);
540   if (OldDep) {
541     // The address of 'SI' has already been tainted.  Just need to absorb the
542     // DepVal to the existing dependence in the address of SI.
543     Instruction* AndDep = getAndDependence(Address);
544     IRBuilder<true, NoFolder> Builder(AndDep);
545     Value* NewDep = nullptr;
546     if (DepVal->getType() == AndDep->getType()) {
547       NewDep = Builder.CreateAnd(OldDep, DepVal);
548     } else {
549       NewDep = Builder.CreateAnd(
550           OldDep, createCast(Builder, DepVal, TargetIntegerType));
551     }
552
553     auto* NewDepInst = dyn_cast<Instruction>(NewDep);
554
555     // Use the new AND instruction as the dependence
556     AndDep->setOperand(0, NewDep);
557     return true;
558   }
559
560   // SI's address has not been tainted. Now taint it with 'DepVal'.
561   Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
562   Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
563   Value* AndDepVal =
564       Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
565   auto AndInst = dyn_cast<Instruction>(AndDepVal);
566   // XXX-comment: The original IR InstCombiner would change our and instruction
567   // to a select and then the back end optimize the condition out.  We attach a
568   // flag to instructions and set it here to inform the InstCombiner to not to
569   // touch this and instruction at all.
570   Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
571   Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
572
573   DEBUG(dbgs() << "[taintStoreAddress]\n"
574                << "Original store: " << *SI << '\n');
575   SI->setOperand(1, NewAddr);
576
577   // Debug output.
578   DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
579                << "\tCast dependence value to integer: " << *CastDepToInt
580                << '\n'
581                << "\tCast address to integer: " << *PtrToIntCast << '\n'
582                << "\tAnd dependence value: " << *AndDepVal << '\n'
583                << "\tOr address: " << *OrAddr << '\n'
584                << "\tCast or instruction to address: " << *NewAddr << "\n\n");
585
586   return true;
587 }
588
589 // Looks for the previous store in the if block --- 'BrBB', which makes the
590 // speculative store 'StoreToHoist' safe.
591 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
592   assert(StoreToHoist && "StoreToHoist must be a real store");
593
594   Value* StorePtr = StoreToHoist->getPointerOperand();
595
596   // Look for a store to the same pointer in BrBB.
597   for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
598        RI != RE; ++RI) {
599     Instruction* CurI = &*RI;
600
601     StoreInst* SI = dyn_cast<StoreInst>(CurI);
602     // Found the previous store make sure it stores to the same location.
603     // XXX-update: If the previous store's original untainted address are the
604     // same as 'StorePtr', we are also good to hoist the store.
605     if (SI && (SI->getPointerOperand() == StorePtr ||
606                GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
607       // Found the previous store, return its value operand.
608       return SI;
609     }
610   }
611
612   assert(false &&
613          "We should not reach here since this store is safe to speculate");
614 }
615
616 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
617 // condition already depends on 'DepVal'.
618 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
619   assert(BI->isConditional());
620   auto* Cond = BI->getOperand(0);
621   if (dependenceSetInclusion(Cond, DepVal)) {
622     // The dependence/ordering is self-evident.
623     return false;
624   }
625
626   IRBuilder<true, NoFolder> Builder(BI);
627   auto* AndDep =
628       Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
629   auto* TruncAndDep =
630       Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
631   auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
632   BI->setOperand(0, OrCond);
633
634   // Debug output.
635   DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
636
637   return true;
638 }
639
640 bool ConditionalBranchDependsOnValue(BranchInst* BI, Value* DepVal) {
641   assert(BI->isConditional());
642   auto* Cond = BI->getOperand(0);
643   return dependenceSetInclusion(Cond, DepVal);
644 }
645
646 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
647 // the first conditional branch. Returns nullptr if there's no such immediately
648 // following store/branch instructions, which we can only enforce the load with
649 // 'acquire'.
650 Instruction* findFirstStoreCondBranchInst(LoadInst* LI) {
651   // In some situations, relaxed loads can be left as is:
652   // 1. The relaxed load is used to calculate the address of the immediate
653   // following store;
654   // 2. The relaxed load is used as a condition in the immediate following
655   // condition, and there are no stores in between. This is actually quite
656   // common. E.g.,
657   // int r1 = x.load(relaxed);
658   // if (r1 != 0) {
659   //   y.store(1, relaxed);
660   // }
661   // However, in this function, we don't deal with them directly. Instead, we
662   // just find the immediate following store/condition branch and return it.
663
664   auto* BB = LI->getParent();
665   auto BE = BB->end();
666   auto BBI = BasicBlock::iterator(LI);
667   BBI++;
668   while (true) {
669     for (; BBI != BE; BBI++) {
670       auto* Inst = dyn_cast<Instruction>(&*BBI);
671       if (Inst == nullptr) {
672         continue;
673       }
674       if (Inst->getOpcode() == Instruction::Store) {
675         return Inst;
676       } else if (Inst->getOpcode() == Instruction::Br) {
677         auto* BrInst = dyn_cast<BranchInst>(Inst);
678         if (BrInst->isConditional()) {
679           return Inst;
680         } else {
681           // Reinitialize iterators with the destination of the unconditional
682           // branch.
683           BB = BrInst->getSuccessor(0);
684           BBI = BB->begin();
685           BE = BB->end();
686           break;
687         }
688       }
689     }
690     if (BBI == BE) {
691       return nullptr;
692     }
693   }
694 }
695
696 // XXX-comment: Returns whether the code has been changed.
697 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
698   bool Changed = false;
699   for (auto* LI : MonotonicLoadInsts) {
700     auto* FirstInst = findFirstStoreCondBranchInst(LI);
701     if (FirstInst == nullptr) {
702       // We don't seem to be able to taint a following store/conditional branch
703       // instruction. Simply make it acquire.
704       DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
705                    << *LI << "\n");
706       LI->setOrdering(Acquire);
707       Changed = true;
708       continue;
709     }
710     // Taint 'FirstInst', which could be a store or a condition branch
711     // instruction.
712     if (FirstInst->getOpcode() == Instruction::Store) {
713       Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
714     } else if (FirstInst->getOpcode() == Instruction::Br) {
715       Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
716     } else {
717       assert(false && "findFirstStoreCondBranchInst() should return a "
718                     "store/condition branch instruction");
719     }
720   }
721   return Changed;
722 }
723
724 // Inserts a fake conditional branch right after the instruction 'SplitInst',
725 // and the branch condition is 'Condition'. 'SplitInst' will be placed in the
726 // newly created block.
727 void AddFakeConditionalBranch(Instruction* SplitInst, Value* Condition) {
728   auto* BB = SplitInst->getParent();
729   TerminatorInst* ThenTerm = nullptr;
730   TerminatorInst* ElseTerm = nullptr;
731   SplitBlockAndInsertIfThenElse(Condition, SplitInst, &ThenTerm, &ElseTerm);
732   assert(ThenTerm && ElseTerm &&
733          "Then/Else terminators cannot be empty after basic block spliting");
734   auto* ThenBB = ThenTerm->getParent();
735   auto* ElseBB = ElseTerm->getParent();
736   auto* TailBB = ThenBB->getSingleSuccessor();
737   assert(TailBB && "Tail block cannot be empty after basic block spliting");
738
739   ThenBB->disableCanEliminateBlock();
740   ThenBB->disableCanEliminateBlock();
741   TailBB->disableCanEliminateBlock();
742   ThenBB->setName(BB->getName() + "Then.Fake");
743   ElseBB->setName(BB->getName() + "Else.Fake");
744   DEBUG(dbgs() << "Add fake conditional branch:\n"
745                << "Then Block:\n"
746                << *ThenBB << "Else Block:\n"
747                << *ElseBB << "\n");
748 }
749
750 // Returns true if the code is changed, and false otherwise.
751 void TaintRelaxedLoads(LoadInst* LI) {
752   IRBuilder<true, NoFolder> Builder(LI->getNextNode());
753   auto* FakeCondition = dyn_cast<Instruction>(Builder.CreateICmp(
754       CmpInst::ICMP_EQ, LI, Constant::getNullValue(LI->getType())));
755   AddFakeConditionalBranch(FakeCondition->getNextNode(), FakeCondition);
756 }
757
758 // XXX-comment: Returns whether the code has been changed.
759 bool AddFakeConditionalBranchAfterMonotonicLoads(
760     const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
761   bool Changed = false;
762   for (auto* LI : MonotonicLoadInsts) {
763     auto* FirstInst = findFirstStoreCondBranchInst(LI);
764     if (FirstInst != nullptr) {
765       if (FirstInst->getOpcode() == Instruction::Store) {
766         if (StoreAddressDependOnValue(dyn_cast<StoreInst>(FirstInst), LI)) {
767           continue;
768         }
769       } else if (FirstInst->getOpcode() == Instruction::Br) {
770         if (ConditionalBranchDependsOnValue(dyn_cast<BranchInst>(FirstInst),
771                                             LI)) {
772           continue;
773         }
774       } else {
775         dbgs() << "FirstInst=" << *FirstInst << "\n";
776         assert(false && "findFirstStoreCondBranchInst() should return a "
777                         "store/condition branch instruction");
778       }
779     }
780
781     // We really need to process the relaxed load now.
782     TaintRelaxedLoads(LI);
783     Changed = true;
784   }
785   return Changed;
786 }
787
788 /**** Implementations of public methods for dependence tainting ****/
789 Value* GetUntaintedAddress(Value* CurrentAddress) {
790   auto* OrAddress = getOrAddress(CurrentAddress);
791   if (OrAddress == nullptr) {
792     // Is it tainted by a select instruction?
793     auto* Inst = dyn_cast<Instruction>(CurrentAddress);
794     if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
795       // A selection instruction.
796       if (Inst->getOperand(1) == Inst->getOperand(2)) {
797         return Inst->getOperand(1);
798       }
799     }
800
801     return CurrentAddress;
802   }
803   Value* ActualAddress = nullptr;
804
805   auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
806   if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
807     return CastToInt->getOperand(0);
808   } else {
809     // This should be a IntToPtr constant expression.
810     ConstantExpr* PtrToIntExpr =
811         dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
812     if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
813       return PtrToIntExpr->getOperand(0);
814     }
815   }
816
817   // Looks like it's not been dependence-tainted. Returns itself.
818   return CurrentAddress;
819 }
820
821 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
822   AAMDNodes AATags;
823   SI->getAAMetadata(AATags);
824   const auto& DL = SI->getModule()->getDataLayout();
825   const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
826   DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
827     dbgs() << "[GetUntaintedMemoryLocation]\n"
828            << "Storing address: " << *SI->getPointerOperand()
829            << "\nUntainted address: " << *OriginalAddr << "\n";
830   });
831   return MemoryLocation(OriginalAddr,
832                         DL.getTypeStoreSize(SI->getValueOperand()->getType()),
833                         AATags);
834 }
835
836 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
837   if (dependenceSetInclusion(SI, DepVal)) {
838     return false;
839   }
840
841   bool tainted = taintStoreAddress(SI, DepVal);
842   assert(tainted);
843   return tainted;
844 }
845
846 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
847   if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
848     return false;
849   }
850
851   bool tainted = taintStoreAddress(SI, DepVal);
852   assert(tainted);
853   return tainted;
854 }
855
856 bool CompressTaintedStore(BasicBlock* BB) {
857   // This function looks for windows of adajcent stores in 'BB' that satisfy the
858   // following condition (and then do optimization):
859   // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
860   //                 address depends on && Dep(v1) includes Dep(d1);
861   // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
862   //                 address depends on && Dep(v2) includes Dep(d2) &&
863   //                 Dep(d2) includes Dep(d1);
864   // ...
865   // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
866   //                 address depends on && Dep(dN) includes Dep(d"N-1").
867   //
868   // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
869   // safely transform the above to the following. In between these stores, we
870   // can omit untainted stores to the same address 'Addr' since they internally
871   // have dependence on the previous stores on the same address.
872   // =>
873   // *Addr = v1
874   // *Addr = v2
875   // *Addr(d3) = v3
876   for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
877     // Look for the first store in such a window of adajacent stores.
878     auto* FirstSI = dyn_cast<StoreInst>(&*BI);
879     if (!FirstSI) {
880       continue;
881     }
882
883     // The first store in the window must be tainted.
884     auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
885     if (UntaintedAddress == FirstSI->getPointerOperand()) {
886       continue;
887     }
888
889     // The first store's address must directly depend on and only depend on a
890     // condition.
891     auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
892     if (nullptr == FirstSIDepCond) {
893       continue;
894     }
895
896     // Dep(first store's storing value) includes Dep(tainted dependence).
897     if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
898       continue;
899     }
900
901     // Look for subsequent stores to the same address that satisfy the condition
902     // of "compressing the dependence".
903     SmallVector<StoreInst*, 8> AdajacentStores;
904     AdajacentStores.push_back(FirstSI);
905     auto BII = BasicBlock::iterator(FirstSI);
906     for (BII++; BII != BE; BII++) {
907       auto* CurrSI = dyn_cast<StoreInst>(&*BII);
908       if (!CurrSI) {
909         if (BII->mayHaveSideEffects()) {
910           // Be conservative. Instructions with side effects are similar to
911           // stores.
912           break;
913         }
914         continue;
915       }
916
917       auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
918       auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
919       // All other stores must satisfy either:
920       // A. 'CurrSI' is an untainted store to the same address, or
921       // B. the combination of the following 5 subconditions:
922       // 1. Tainted;
923       // 2. Untainted address is the same as the group's address;
924       // 3. The address is tainted with a sole value which is a condition;
925       // 4. The storing value depends on the condition in 3.
926       // 5. The condition in 3 depends on the previous stores dependence
927       // condition.
928
929       // Condition A. Should ignore this store directly.
930       if (OrigAddress == CurrSI->getPointerOperand() &&
931           OrigAddress == UntaintedAddress) {
932         continue;
933       }
934       // Check condition B.
935       Value* Cond = nullptr;
936       if (OrigAddress == CurrSI->getPointerOperand() ||
937           OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
938           !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
939         // Check condition 1, 2, 3 & 4.
940         break;
941       }
942
943       // Check condition 5.
944       StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
945       auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
946       assert(PrevSIDepCond &&
947              "Store in the group must already depend on a condtion");
948       if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
949         break;
950       }
951
952       AdajacentStores.push_back(CurrSI);
953     }
954
955     if (AdajacentStores.size() == 1) {
956       // The outer loop should keep looking from the next store.
957       continue;
958     }
959
960     // Now we have such a group of tainted stores to the same address.
961     DEBUG(dbgs() << "[CompressTaintedStore]\n");
962     DEBUG(dbgs() << "Original BB\n");
963     DEBUG(dbgs() << *BB << '\n');
964     auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
965     for (unsigned i = 0; i < AdajacentStores.size() - 1; ++i) {
966       auto* SI = AdajacentStores[i];
967
968       // Use the original address for stores before the last one.
969       SI->setOperand(1, UntaintedAddress);
970
971       DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
972     }
973     // XXX-comment: Try to make the last store use fewer registers.
974     // If LastSI's storing value is a select based on the condition with which
975     // its address is tainted, transform the tainted address to a select
976     // instruction, as follows:
977     // r1 = Select Cond ? A : B
978     // r2 = Cond & 0
979     // r3 = Addr | r2
980     // *r3 = r1
981     // ==>
982     // r1 = Select Cond ? A : B
983     // r2 = Select Cond ? Addr : Addr
984     // *r2 = r1
985     // The idea is that both Select instructions depend on the same condition,
986     // so hopefully the backend can generate two cmov instructions for them (and
987     // this saves the number of registers needed).
988     auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
989     auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
990     if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
991         LastSIValue->getOperand(0) == LastSIDep) {
992       // XXX-comment: Maybe it's better for us to just leave it as an and/or
993       // dependence pattern.
994       //      /*
995       IRBuilder<true, NoFolder> Builder(LastSI);
996       auto* Address =
997           Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
998       LastSI->setOperand(1, Address);
999       DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
1000       //      */
1001     }
1002   }
1003
1004   return true;
1005 }
1006
1007 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
1008   Value* OldDep = getDependence(OldAddress);
1009   // Return false when there's no dependence to pass from the OldAddress.
1010   if (!OldDep) {
1011     return false;
1012   }
1013
1014   // No need to pass the dependence to NewStore's address if it already depends
1015   // on whatever 'OldAddress' depends on.
1016   if (StoreAddressDependOnValue(NewStore, OldDep)) {
1017     return false;
1018   }
1019   return taintStoreAddress(NewStore, OldAddress);
1020 }
1021
1022 SmallSet<Value*, 8> FindDependence(Value* Val) {
1023   SmallSet<Value*, 8> DepSet;
1024   recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
1025   return DepSet;
1026 }
1027
1028 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
1029   return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
1030 }
1031
1032 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
1033   return dependenceSetInclusion(SI, Dep);
1034 }
1035
1036 } // namespace
1037
1038
1039
1040 bool CodeGenPrepare::runOnFunction(Function &F) {
1041   bool EverMadeChange = false;
1042
1043   if (skipOptnoneFunction(F))
1044     return false;
1045
1046   DL = &F.getParent()->getDataLayout();
1047
1048   // Clear per function information.
1049   InsertedInsts.clear();
1050   PromotedInsts.clear();
1051
1052   ModifiedDT = false;
1053   if (TM)
1054     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
1055   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1056   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1057   OptSize = F.optForSize();
1058
1059   /// This optimization identifies DIV instructions that can be
1060   /// profitably bypassed and carried out with a shorter, faster divide.
1061   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
1062     const DenseMap<unsigned int, unsigned int> &BypassWidths =
1063        TLI->getBypassSlowDivWidths();
1064     BasicBlock* BB = &*F.begin();
1065     while (BB != nullptr) {
1066       // bypassSlowDivision may create new BBs, but we don't want to reapply the
1067       // optimization to those blocks.
1068       BasicBlock* Next = BB->getNextNode();
1069       EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
1070       BB = Next;
1071     }
1072   }
1073
1074   // Eliminate blocks that contain only PHI nodes and an
1075   // unconditional branch.
1076   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
1077
1078   // llvm.dbg.value is far away from the value then iSel may not be able
1079   // handle it properly. iSel will drop llvm.dbg.value if it can not
1080   // find a node corresponding to the value.
1081   EverMadeChange |= placeDbgValues(F);
1082
1083   // If there is a mask, compare against zero, and branch that can be combined
1084   // into a single target instruction, push the mask and compare into branch
1085   // users. Do this before OptimizeBlock -> OptimizeInst ->
1086   // OptimizeCmpExpression, which perturbs the pattern being searched for.
1087   if (!DisableBranchOpts) {
1088     EverMadeChange |= sinkAndCmp(F);
1089     EverMadeChange |= splitBranchCondition(F);
1090   }
1091
1092   bool MadeChange = true;
1093   while (MadeChange) {
1094     MadeChange = false;
1095     for (Function::iterator I = F.begin(); I != F.end(); ) {
1096       BasicBlock *BB = &*I++;
1097       bool ModifiedDTOnIteration = false;
1098       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
1099
1100       // Restart BB iteration if the dominator tree of the Function was changed
1101       if (ModifiedDTOnIteration)
1102         break;
1103     }
1104     EverMadeChange |= MadeChange;
1105   }
1106
1107   SunkAddrs.clear();
1108
1109   if (!DisableBranchOpts) {
1110     MadeChange = false;
1111     SmallPtrSet<BasicBlock*, 8> WorkList;
1112     for (BasicBlock &BB : F) {
1113       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
1114       MadeChange |= ConstantFoldTerminator(&BB, true);
1115       if (!MadeChange) continue;
1116
1117       for (SmallVectorImpl<BasicBlock*>::iterator
1118              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1119         if (pred_begin(*II) == pred_end(*II))
1120           WorkList.insert(*II);
1121     }
1122
1123     // Delete the dead blocks and any of their dead successors.
1124     MadeChange |= !WorkList.empty();
1125     while (!WorkList.empty()) {
1126       BasicBlock *BB = *WorkList.begin();
1127       WorkList.erase(BB);
1128       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
1129
1130       DeleteDeadBlock(BB);
1131
1132       for (SmallVectorImpl<BasicBlock*>::iterator
1133              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
1134         if (pred_begin(*II) == pred_end(*II))
1135           WorkList.insert(*II);
1136     }
1137
1138     // Merge pairs of basic blocks with unconditional branches, connected by
1139     // a single edge.
1140     if (EverMadeChange || MadeChange)
1141       MadeChange |= eliminateFallThrough(F);
1142
1143     EverMadeChange |= MadeChange;
1144   }
1145
1146   if (!DisableGCOpts) {
1147     SmallVector<Instruction *, 2> Statepoints;
1148     for (BasicBlock &BB : F)
1149       for (Instruction &I : BB)
1150         if (isStatepoint(I))
1151           Statepoints.push_back(&I);
1152     for (auto &I : Statepoints)
1153       EverMadeChange |= simplifyOffsetableRelocate(*I);
1154   }
1155
1156   // XXX-comment: Delay dealing with relaxed loads in this function to avoid
1157   // further changes done by other passes (e.g., SimplifyCFG).
1158   // Collect all the relaxed loads.
1159   SmallVector<LoadInst*, 1> MonotonicLoadInsts;
1160   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
1161     if (I->isAtomic()) {
1162       switch (I->getOpcode()) {
1163         case Instruction::Load: {
1164           auto* LI = dyn_cast<LoadInst>(&*I);
1165           if (LI->getOrdering() == Monotonic) {
1166             MonotonicLoadInsts.push_back(LI);
1167           }
1168           break;
1169         }
1170         default: {
1171           break;
1172         }
1173       }
1174     }
1175   }
1176   EverMadeChange |=
1177       AddFakeConditionalBranchAfterMonotonicLoads(MonotonicLoadInsts);
1178
1179   return EverMadeChange;
1180 }
1181
1182 /// Merge basic blocks which are connected by a single edge, where one of the
1183 /// basic blocks has a single successor pointing to the other basic block,
1184 /// which has a single predecessor.
1185 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
1186   bool Changed = false;
1187   // Scan all of the blocks in the function, except for the entry block.
1188   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1189     BasicBlock *BB = &*I++;
1190     // If the destination block has a single pred, then this is a trivial
1191     // edge, just collapse it.
1192     BasicBlock *SinglePred = BB->getSinglePredecessor();
1193
1194     // Don't merge if BB's address is taken.
1195     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
1196
1197     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
1198     if (Term && !Term->isConditional()) {
1199       Changed = true;
1200       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
1201       // Remember if SinglePred was the entry block of the function.
1202       // If so, we will need to move BB back to the entry position.
1203       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1204       MergeBasicBlockIntoOnlyPred(BB, nullptr);
1205
1206       if (isEntry && BB != &BB->getParent()->getEntryBlock())
1207         BB->moveBefore(&BB->getParent()->getEntryBlock());
1208
1209       // We have erased a block. Update the iterator.
1210       I = BB->getIterator();
1211     }
1212   }
1213   return Changed;
1214 }
1215
1216 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
1217 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
1218 /// edges in ways that are non-optimal for isel. Start by eliminating these
1219 /// blocks so we can split them the way we want them.
1220 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
1221   bool MadeChange = false;
1222   // Note that this intentionally skips the entry block.
1223   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
1224     BasicBlock *BB = &*I++;
1225     // If this block doesn't end with an uncond branch, ignore it.
1226     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
1227     if (!BI || !BI->isUnconditional())
1228       continue;
1229
1230     // If the instruction before the branch (skipping debug info) isn't a phi
1231     // node, then other stuff is happening here.
1232     BasicBlock::iterator BBI = BI->getIterator();
1233     if (BBI != BB->begin()) {
1234       --BBI;
1235       while (isa<DbgInfoIntrinsic>(BBI)) {
1236         if (BBI == BB->begin())
1237           break;
1238         --BBI;
1239       }
1240       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
1241         continue;
1242     }
1243
1244     // Do not break infinite loops.
1245     BasicBlock *DestBB = BI->getSuccessor(0);
1246     if (DestBB == BB)
1247       continue;
1248
1249     if (!canMergeBlocks(BB, DestBB))
1250       continue;
1251
1252     eliminateMostlyEmptyBlock(BB);
1253     MadeChange = true;
1254   }
1255   return MadeChange;
1256 }
1257
1258 /// Return true if we can merge BB into DestBB if there is a single
1259 /// unconditional branch between them, and BB contains no other non-phi
1260 /// instructions.
1261 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1262                                     const BasicBlock *DestBB) const {
1263   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1264   // the successor.  If there are more complex condition (e.g. preheaders),
1265   // don't mess around with them.
1266   BasicBlock::const_iterator BBI = BB->begin();
1267   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1268     for (const User *U : PN->users()) {
1269       const Instruction *UI = cast<Instruction>(U);
1270       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1271         return false;
1272       // If User is inside DestBB block and it is a PHINode then check
1273       // incoming value. If incoming value is not from BB then this is
1274       // a complex condition (e.g. preheaders) we want to avoid here.
1275       if (UI->getParent() == DestBB) {
1276         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1277           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1278             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1279             if (Insn && Insn->getParent() == BB &&
1280                 Insn->getParent() != UPN->getIncomingBlock(I))
1281               return false;
1282           }
1283       }
1284     }
1285   }
1286
1287   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1288   // and DestBB may have conflicting incoming values for the block.  If so, we
1289   // can't merge the block.
1290   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1291   if (!DestBBPN) return true;  // no conflict.
1292
1293   // Collect the preds of BB.
1294   SmallPtrSet<const BasicBlock*, 16> BBPreds;
1295   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1296     // It is faster to get preds from a PHI than with pred_iterator.
1297     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1298       BBPreds.insert(BBPN->getIncomingBlock(i));
1299   } else {
1300     BBPreds.insert(pred_begin(BB), pred_end(BB));
1301   }
1302
1303   // Walk the preds of DestBB.
1304   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1305     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1306     if (BBPreds.count(Pred)) {   // Common predecessor?
1307       BBI = DestBB->begin();
1308       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
1309         const Value *V1 = PN->getIncomingValueForBlock(Pred);
1310         const Value *V2 = PN->getIncomingValueForBlock(BB);
1311
1312         // If V2 is a phi node in BB, look up what the mapped value will be.
1313         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1314           if (V2PN->getParent() == BB)
1315             V2 = V2PN->getIncomingValueForBlock(Pred);
1316
1317         // If there is a conflict, bail out.
1318         if (V1 != V2) return false;
1319       }
1320     }
1321   }
1322
1323   return true;
1324 }
1325
1326
1327 /// Eliminate a basic block that has only phi's and an unconditional branch in
1328 /// it.
1329 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1330   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1331   BasicBlock *DestBB = BI->getSuccessor(0);
1332
1333   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
1334
1335   // If the destination block has a single pred, then this is a trivial edge,
1336   // just collapse it.
1337   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1338     if (SinglePred != DestBB) {
1339       // Remember if SinglePred was the entry block of the function.  If so, we
1340       // will need to move BB back to the entry position.
1341       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
1342       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
1343
1344       if (isEntry && BB != &BB->getParent()->getEntryBlock())
1345         BB->moveBefore(&BB->getParent()->getEntryBlock());
1346
1347       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1348       return;
1349     }
1350   }
1351
1352   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
1353   // to handle the new incoming edges it is about to have.
1354   PHINode *PN;
1355   for (BasicBlock::iterator BBI = DestBB->begin();
1356        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1357     // Remove the incoming value for BB, and remember it.
1358     Value *InVal = PN->removeIncomingValue(BB, false);
1359
1360     // Two options: either the InVal is a phi node defined in BB or it is some
1361     // value that dominates BB.
1362     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1363     if (InValPhi && InValPhi->getParent() == BB) {
1364       // Add all of the input values of the input PHI as inputs of this phi.
1365       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1366         PN->addIncoming(InValPhi->getIncomingValue(i),
1367                         InValPhi->getIncomingBlock(i));
1368     } else {
1369       // Otherwise, add one instance of the dominating value for each edge that
1370       // we will be adding.
1371       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1372         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1373           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
1374       } else {
1375         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1376           PN->addIncoming(InVal, *PI);
1377       }
1378     }
1379   }
1380
1381   // The PHIs are now updated, change everything that refers to BB to use
1382   // DestBB and remove BB.
1383   BB->replaceAllUsesWith(DestBB);
1384   BB->eraseFromParent();
1385   ++NumBlocksElim;
1386
1387   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1388 }
1389
1390 // Computes a map of base pointer relocation instructions to corresponding
1391 // derived pointer relocation instructions given a vector of all relocate calls
1392 static void computeBaseDerivedRelocateMap(
1393     const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1394     DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1395         &RelocateInstMap) {
1396   // Collect information in two maps: one primarily for locating the base object
1397   // while filling the second map; the second map is the final structure holding
1398   // a mapping between Base and corresponding Derived relocate calls
1399   DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1400   for (auto *ThisRelocate : AllRelocateCalls) {
1401     auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1402                             ThisRelocate->getDerivedPtrIndex());
1403     RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1404   }
1405   for (auto &Item : RelocateIdxMap) {
1406     std::pair<unsigned, unsigned> Key = Item.first;
1407     if (Key.first == Key.second)
1408       // Base relocation: nothing to insert
1409       continue;
1410
1411     GCRelocateInst *I = Item.second;
1412     auto BaseKey = std::make_pair(Key.first, Key.first);
1413
1414     // We're iterating over RelocateIdxMap so we cannot modify it.
1415     auto MaybeBase = RelocateIdxMap.find(BaseKey);
1416     if (MaybeBase == RelocateIdxMap.end())
1417       // TODO: We might want to insert a new base object relocate and gep off
1418       // that, if there are enough derived object relocates.
1419       continue;
1420
1421     RelocateInstMap[MaybeBase->second].push_back(I);
1422   }
1423 }
1424
1425 // Accepts a GEP and extracts the operands into a vector provided they're all
1426 // small integer constants
1427 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1428                                           SmallVectorImpl<Value *> &OffsetV) {
1429   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1430     // Only accept small constant integer operands
1431     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1432     if (!Op || Op->getZExtValue() > 20)
1433       return false;
1434   }
1435
1436   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1437     OffsetV.push_back(GEP->getOperand(i));
1438   return true;
1439 }
1440
1441 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1442 // replace, computes a replacement, and affects it.
1443 static bool
1444 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1445                           const SmallVectorImpl<GCRelocateInst *> &Targets) {
1446   bool MadeChange = false;
1447   for (GCRelocateInst *ToReplace : Targets) {
1448     assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1449            "Not relocating a derived object of the original base object");
1450     if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1451       // A duplicate relocate call. TODO: coalesce duplicates.
1452       continue;
1453     }
1454
1455     if (RelocatedBase->getParent() != ToReplace->getParent()) {
1456       // Base and derived relocates are in different basic blocks.
1457       // In this case transform is only valid when base dominates derived
1458       // relocate. However it would be too expensive to check dominance
1459       // for each such relocate, so we skip the whole transformation.
1460       continue;
1461     }
1462
1463     Value *Base = ToReplace->getBasePtr();
1464     auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1465     if (!Derived || Derived->getPointerOperand() != Base)
1466       continue;
1467
1468     SmallVector<Value *, 2> OffsetV;
1469     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1470       continue;
1471
1472     // Create a Builder and replace the target callsite with a gep
1473     assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
1474
1475     // Insert after RelocatedBase
1476     IRBuilder<> Builder(RelocatedBase->getNextNode());
1477     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1478
1479     // If gc_relocate does not match the actual type, cast it to the right type.
1480     // In theory, there must be a bitcast after gc_relocate if the type does not
1481     // match, and we should reuse it to get the derived pointer. But it could be
1482     // cases like this:
1483     // bb1:
1484     //  ...
1485     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1486     //  br label %merge
1487     //
1488     // bb2:
1489     //  ...
1490     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1491     //  br label %merge
1492     //
1493     // merge:
1494     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1495     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1496     //
1497     // In this case, we can not find the bitcast any more. So we insert a new bitcast
1498     // no matter there is already one or not. In this way, we can handle all cases, and
1499     // the extra bitcast should be optimized away in later passes.
1500     Value *ActualRelocatedBase = RelocatedBase;
1501     if (RelocatedBase->getType() != Base->getType()) {
1502       ActualRelocatedBase =
1503           Builder.CreateBitCast(RelocatedBase, Base->getType());
1504     }
1505     Value *Replacement = Builder.CreateGEP(
1506         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1507     Replacement->takeName(ToReplace);
1508     // If the newly generated derived pointer's type does not match the original derived
1509     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1510     Value *ActualReplacement = Replacement;
1511     if (Replacement->getType() != ToReplace->getType()) {
1512       ActualReplacement =
1513           Builder.CreateBitCast(Replacement, ToReplace->getType());
1514     }
1515     ToReplace->replaceAllUsesWith(ActualReplacement);
1516     ToReplace->eraseFromParent();
1517
1518     MadeChange = true;
1519   }
1520   return MadeChange;
1521 }
1522
1523 // Turns this:
1524 //
1525 // %base = ...
1526 // %ptr = gep %base + 15
1527 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1528 // %base' = relocate(%tok, i32 4, i32 4)
1529 // %ptr' = relocate(%tok, i32 4, i32 5)
1530 // %val = load %ptr'
1531 //
1532 // into this:
1533 //
1534 // %base = ...
1535 // %ptr = gep %base + 15
1536 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1537 // %base' = gc.relocate(%tok, i32 4, i32 4)
1538 // %ptr' = gep %base' + 15
1539 // %val = load %ptr'
1540 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1541   bool MadeChange = false;
1542   SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1543
1544   for (auto *U : I.users())
1545     if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1546       // Collect all the relocate calls associated with a statepoint
1547       AllRelocateCalls.push_back(Relocate);
1548
1549   // We need atleast one base pointer relocation + one derived pointer
1550   // relocation to mangle
1551   if (AllRelocateCalls.size() < 2)
1552     return false;
1553
1554   // RelocateInstMap is a mapping from the base relocate instruction to the
1555   // corresponding derived relocate instructions
1556   DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1557   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1558   if (RelocateInstMap.empty())
1559     return false;
1560
1561   for (auto &Item : RelocateInstMap)
1562     // Item.first is the RelocatedBase to offset against
1563     // Item.second is the vector of Targets to replace
1564     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1565   return MadeChange;
1566 }
1567
1568 /// SinkCast - Sink the specified cast instruction into its user blocks
1569 static bool SinkCast(CastInst *CI) {
1570   BasicBlock *DefBB = CI->getParent();
1571
1572   /// InsertedCasts - Only insert a cast in each block once.
1573   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1574
1575   bool MadeChange = false;
1576   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1577        UI != E; ) {
1578     Use &TheUse = UI.getUse();
1579     Instruction *User = cast<Instruction>(*UI);
1580
1581     // Figure out which BB this cast is used in.  For PHI's this is the
1582     // appropriate predecessor block.
1583     BasicBlock *UserBB = User->getParent();
1584     if (PHINode *PN = dyn_cast<PHINode>(User)) {
1585       UserBB = PN->getIncomingBlock(TheUse);
1586     }
1587
1588     // Preincrement use iterator so we don't invalidate it.
1589     ++UI;
1590
1591     // If the block selected to receive the cast is an EH pad that does not
1592     // allow non-PHI instructions before the terminator, we can't sink the
1593     // cast.
1594     if (UserBB->getTerminator()->isEHPad())
1595       continue;
1596
1597     // If this user is in the same block as the cast, don't change the cast.
1598     if (UserBB == DefBB) continue;
1599
1600     // If we have already inserted a cast into this block, use it.
1601     CastInst *&InsertedCast = InsertedCasts[UserBB];
1602
1603     if (!InsertedCast) {
1604       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1605       assert(InsertPt != UserBB->end());
1606       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1607                                       CI->getType(), "", &*InsertPt);
1608     }
1609
1610     // Replace a use of the cast with a use of the new cast.
1611     TheUse = InsertedCast;
1612     MadeChange = true;
1613     ++NumCastUses;
1614   }
1615
1616   // If we removed all uses, nuke the cast.
1617   if (CI->use_empty()) {
1618     CI->eraseFromParent();
1619     MadeChange = true;
1620   }
1621
1622   return MadeChange;
1623 }
1624
1625 /// If the specified cast instruction is a noop copy (e.g. it's casting from
1626 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1627 /// reduce the number of virtual registers that must be created and coalesced.
1628 ///
1629 /// Return true if any changes are made.
1630 ///
1631 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1632                                        const DataLayout &DL) {
1633   // If this is a noop copy,
1634   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1635   EVT DstVT = TLI.getValueType(DL, CI->getType());
1636
1637   // This is an fp<->int conversion?
1638   if (SrcVT.isInteger() != DstVT.isInteger())
1639     return false;
1640
1641   // If this is an extension, it will be a zero or sign extension, which
1642   // isn't a noop.
1643   if (SrcVT.bitsLT(DstVT)) return false;
1644
1645   // If these values will be promoted, find out what they will be promoted
1646   // to.  This helps us consider truncates on PPC as noop copies when they
1647   // are.
1648   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1649       TargetLowering::TypePromoteInteger)
1650     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1651   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1652       TargetLowering::TypePromoteInteger)
1653     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1654
1655   // If, after promotion, these are the same types, this is a noop copy.
1656   if (SrcVT != DstVT)
1657     return false;
1658
1659   return SinkCast(CI);
1660 }
1661
1662 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1663 /// possible.
1664 ///
1665 /// Return true if any changes were made.
1666 static bool CombineUAddWithOverflow(CmpInst *CI) {
1667   Value *A, *B;
1668   Instruction *AddI;
1669   if (!match(CI,
1670              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1671     return false;
1672
1673   Type *Ty = AddI->getType();
1674   if (!isa<IntegerType>(Ty))
1675     return false;
1676
1677   // We don't want to move around uses of condition values this late, so we we
1678   // check if it is legal to create the call to the intrinsic in the basic
1679   // block containing the icmp:
1680
1681   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1682     return false;
1683
1684 #ifndef NDEBUG
1685   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1686   // for now:
1687   if (AddI->hasOneUse())
1688     assert(*AddI->user_begin() == CI && "expected!");
1689 #endif
1690
1691   Module *M = CI->getModule();
1692   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1693
1694   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1695
1696   auto *UAddWithOverflow =
1697       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1698   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1699   auto *Overflow =
1700       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1701
1702   CI->replaceAllUsesWith(Overflow);
1703   AddI->replaceAllUsesWith(UAdd);
1704   CI->eraseFromParent();
1705   AddI->eraseFromParent();
1706   return true;
1707 }
1708
1709 /// Sink the given CmpInst into user blocks to reduce the number of virtual
1710 /// registers that must be created and coalesced. This is a clear win except on
1711 /// targets with multiple condition code registers (PowerPC), where it might
1712 /// lose; some adjustment may be wanted there.
1713 ///
1714 /// Return true if any changes are made.
1715 static bool SinkCmpExpression(CmpInst *CI) {
1716   BasicBlock *DefBB = CI->getParent();
1717
1718   /// Only insert a cmp in each block once.
1719   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1720
1721   bool MadeChange = false;
1722   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1723        UI != E; ) {
1724     Use &TheUse = UI.getUse();
1725     Instruction *User = cast<Instruction>(*UI);
1726
1727     // Preincrement use iterator so we don't invalidate it.
1728     ++UI;
1729
1730     // Don't bother for PHI nodes.
1731     if (isa<PHINode>(User))
1732       continue;
1733
1734     // Figure out which BB this cmp is used in.
1735     BasicBlock *UserBB = User->getParent();
1736
1737     // If this user is in the same block as the cmp, don't change the cmp.
1738     if (UserBB == DefBB) continue;
1739
1740     // If we have already inserted a cmp into this block, use it.
1741     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1742
1743     if (!InsertedCmp) {
1744       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1745       assert(InsertPt != UserBB->end());
1746       InsertedCmp =
1747           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1748                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1749     }
1750
1751     // Replace a use of the cmp with a use of the new cmp.
1752     TheUse = InsertedCmp;
1753     MadeChange = true;
1754     ++NumCmpUses;
1755   }
1756
1757   // If we removed all uses, nuke the cmp.
1758   if (CI->use_empty()) {
1759     CI->eraseFromParent();
1760     MadeChange = true;
1761   }
1762
1763   return MadeChange;
1764 }
1765
1766 static bool OptimizeCmpExpression(CmpInst *CI) {
1767   if (SinkCmpExpression(CI))
1768     return true;
1769
1770   if (CombineUAddWithOverflow(CI))
1771     return true;
1772
1773   return false;
1774 }
1775
1776 /// Check if the candidates could be combined with a shift instruction, which
1777 /// includes:
1778 /// 1. Truncate instruction
1779 /// 2. And instruction and the imm is a mask of the low bits:
1780 /// imm & (imm+1) == 0
1781 static bool isExtractBitsCandidateUse(Instruction *User) {
1782   if (!isa<TruncInst>(User)) {
1783     if (User->getOpcode() != Instruction::And ||
1784         !isa<ConstantInt>(User->getOperand(1)))
1785       return false;
1786
1787     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1788
1789     if ((Cimm & (Cimm + 1)).getBoolValue())
1790       return false;
1791   }
1792   return true;
1793 }
1794
1795 /// Sink both shift and truncate instruction to the use of truncate's BB.
1796 static bool
1797 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1798                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1799                      const TargetLowering &TLI, const DataLayout &DL) {
1800   BasicBlock *UserBB = User->getParent();
1801   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1802   TruncInst *TruncI = dyn_cast<TruncInst>(User);
1803   bool MadeChange = false;
1804
1805   for (Value::user_iterator TruncUI = TruncI->user_begin(),
1806                             TruncE = TruncI->user_end();
1807        TruncUI != TruncE;) {
1808
1809     Use &TruncTheUse = TruncUI.getUse();
1810     Instruction *TruncUser = cast<Instruction>(*TruncUI);
1811     // Preincrement use iterator so we don't invalidate it.
1812
1813     ++TruncUI;
1814
1815     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1816     if (!ISDOpcode)
1817       continue;
1818
1819     // If the use is actually a legal node, there will not be an
1820     // implicit truncate.
1821     // FIXME: always querying the result type is just an
1822     // approximation; some nodes' legality is determined by the
1823     // operand or other means. There's no good way to find out though.
1824     if (TLI.isOperationLegalOrCustom(
1825             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1826       continue;
1827
1828     // Don't bother for PHI nodes.
1829     if (isa<PHINode>(TruncUser))
1830       continue;
1831
1832     BasicBlock *TruncUserBB = TruncUser->getParent();
1833
1834     if (UserBB == TruncUserBB)
1835       continue;
1836
1837     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1838     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1839
1840     if (!InsertedShift && !InsertedTrunc) {
1841       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1842       assert(InsertPt != TruncUserBB->end());
1843       // Sink the shift
1844       if (ShiftI->getOpcode() == Instruction::AShr)
1845         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1846                                                    "", &*InsertPt);
1847       else
1848         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1849                                                    "", &*InsertPt);
1850
1851       // Sink the trunc
1852       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1853       TruncInsertPt++;
1854       assert(TruncInsertPt != TruncUserBB->end());
1855
1856       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1857                                        TruncI->getType(), "", &*TruncInsertPt);
1858
1859       MadeChange = true;
1860
1861       TruncTheUse = InsertedTrunc;
1862     }
1863   }
1864   return MadeChange;
1865 }
1866
1867 /// Sink the shift *right* instruction into user blocks if the uses could
1868 /// potentially be combined with this shift instruction and generate BitExtract
1869 /// instruction. It will only be applied if the architecture supports BitExtract
1870 /// instruction. Here is an example:
1871 /// BB1:
1872 ///   %x.extract.shift = lshr i64 %arg1, 32
1873 /// BB2:
1874 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
1875 /// ==>
1876 ///
1877 /// BB2:
1878 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
1879 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1880 ///
1881 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1882 /// instruction.
1883 /// Return true if any changes are made.
1884 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1885                                 const TargetLowering &TLI,
1886                                 const DataLayout &DL) {
1887   BasicBlock *DefBB = ShiftI->getParent();
1888
1889   /// Only insert instructions in each block once.
1890   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1891
1892   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1893
1894   bool MadeChange = false;
1895   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1896        UI != E;) {
1897     Use &TheUse = UI.getUse();
1898     Instruction *User = cast<Instruction>(*UI);
1899     // Preincrement use iterator so we don't invalidate it.
1900     ++UI;
1901
1902     // Don't bother for PHI nodes.
1903     if (isa<PHINode>(User))
1904       continue;
1905
1906     if (!isExtractBitsCandidateUse(User))
1907       continue;
1908
1909     BasicBlock *UserBB = User->getParent();
1910
1911     if (UserBB == DefBB) {
1912       // If the shift and truncate instruction are in the same BB. The use of
1913       // the truncate(TruncUse) may still introduce another truncate if not
1914       // legal. In this case, we would like to sink both shift and truncate
1915       // instruction to the BB of TruncUse.
1916       // for example:
1917       // BB1:
1918       // i64 shift.result = lshr i64 opnd, imm
1919       // trunc.result = trunc shift.result to i16
1920       //
1921       // BB2:
1922       //   ----> We will have an implicit truncate here if the architecture does
1923       //   not have i16 compare.
1924       // cmp i16 trunc.result, opnd2
1925       //
1926       if (isa<TruncInst>(User) && shiftIsLegal
1927           // If the type of the truncate is legal, no trucate will be
1928           // introduced in other basic blocks.
1929           &&
1930           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1931         MadeChange =
1932             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1933
1934       continue;
1935     }
1936     // If we have already inserted a shift into this block, use it.
1937     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1938
1939     if (!InsertedShift) {
1940       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1941       assert(InsertPt != UserBB->end());
1942
1943       if (ShiftI->getOpcode() == Instruction::AShr)
1944         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1945                                                    "", &*InsertPt);
1946       else
1947         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1948                                                    "", &*InsertPt);
1949
1950       MadeChange = true;
1951     }
1952
1953     // Replace a use of the shift with a use of the new shift.
1954     TheUse = InsertedShift;
1955   }
1956
1957   // If we removed all uses, nuke the shift.
1958   if (ShiftI->use_empty())
1959     ShiftI->eraseFromParent();
1960
1961   return MadeChange;
1962 }
1963
1964 // Translate a masked load intrinsic like
1965 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1966 //                               <16 x i1> %mask, <16 x i32> %passthru)
1967 // to a chain of basic blocks, with loading element one-by-one if
1968 // the appropriate mask bit is set
1969 //
1970 //  %1 = bitcast i8* %addr to i32*
1971 //  %2 = extractelement <16 x i1> %mask, i32 0
1972 //  %3 = icmp eq i1 %2, true
1973 //  br i1 %3, label %cond.load, label %else
1974 //
1975 //cond.load:                                        ; preds = %0
1976 //  %4 = getelementptr i32* %1, i32 0
1977 //  %5 = load i32* %4
1978 //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1979 //  br label %else
1980 //
1981 //else:                                             ; preds = %0, %cond.load
1982 //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1983 //  %7 = extractelement <16 x i1> %mask, i32 1
1984 //  %8 = icmp eq i1 %7, true
1985 //  br i1 %8, label %cond.load1, label %else2
1986 //
1987 //cond.load1:                                       ; preds = %else
1988 //  %9 = getelementptr i32* %1, i32 1
1989 //  %10 = load i32* %9
1990 //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1991 //  br label %else2
1992 //
1993 //else2:                                            ; preds = %else, %cond.load1
1994 //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1995 //  %12 = extractelement <16 x i1> %mask, i32 2
1996 //  %13 = icmp eq i1 %12, true
1997 //  br i1 %13, label %cond.load4, label %else5
1998 //
1999 static void ScalarizeMaskedLoad(CallInst *CI) {
2000   Value *Ptr  = CI->getArgOperand(0);
2001   Value *Alignment = CI->getArgOperand(1);
2002   Value *Mask = CI->getArgOperand(2);
2003   Value *Src0 = CI->getArgOperand(3);
2004
2005   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2006   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2007   assert(VecType && "Unexpected return type of masked load intrinsic");
2008
2009   Type *EltTy = CI->getType()->getVectorElementType();
2010
2011   IRBuilder<> Builder(CI->getContext());
2012   Instruction *InsertPt = CI;
2013   BasicBlock *IfBlock = CI->getParent();
2014   BasicBlock *CondBlock = nullptr;
2015   BasicBlock *PrevIfBlock = CI->getParent();
2016
2017   Builder.SetInsertPoint(InsertPt);
2018   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2019
2020   // Short-cut if the mask is all-true.
2021   bool IsAllOnesMask = isa<Constant>(Mask) &&
2022     cast<Constant>(Mask)->isAllOnesValue();
2023
2024   if (IsAllOnesMask) {
2025     Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
2026     CI->replaceAllUsesWith(NewI);
2027     CI->eraseFromParent();
2028     return;
2029   }
2030
2031   // Adjust alignment for the scalar instruction.
2032   AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
2033   // Bitcast %addr fron i8* to EltTy*
2034   Type *NewPtrType =
2035     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2036   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2037   unsigned VectorWidth = VecType->getNumElements();
2038
2039   Value *UndefVal = UndefValue::get(VecType);
2040
2041   // The result vector
2042   Value *VResult = UndefVal;
2043
2044   if (isa<ConstantVector>(Mask)) {
2045     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2046       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2047           continue;
2048       Value *Gep =
2049           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2050       LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2051       VResult = Builder.CreateInsertElement(VResult, Load,
2052                                             Builder.getInt32(Idx));
2053     }
2054     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2055     CI->replaceAllUsesWith(NewI);
2056     CI->eraseFromParent();
2057     return;
2058   }
2059
2060   PHINode *Phi = nullptr;
2061   Value *PrevPhi = UndefVal;
2062
2063   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2064
2065     // Fill the "else" block, created in the previous iteration
2066     //
2067     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
2068     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2069     //  %to_load = icmp eq i1 %mask_1, true
2070     //  br i1 %to_load, label %cond.load, label %else
2071     //
2072     if (Idx > 0) {
2073       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2074       Phi->addIncoming(VResult, CondBlock);
2075       Phi->addIncoming(PrevPhi, PrevIfBlock);
2076       PrevPhi = Phi;
2077       VResult = Phi;
2078     }
2079
2080     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2081     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2082                                     ConstantInt::get(Predicate->getType(), 1));
2083
2084     // Create "cond" block
2085     //
2086     //  %EltAddr = getelementptr i32* %1, i32 0
2087     //  %Elt = load i32* %EltAddr
2088     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2089     //
2090     CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
2091     Builder.SetInsertPoint(InsertPt);
2092
2093     Value *Gep =
2094         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2095     LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
2096     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
2097
2098     // Create "else" block, fill it in the next iteration
2099     BasicBlock *NewIfBlock =
2100         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2101     Builder.SetInsertPoint(InsertPt);
2102     Instruction *OldBr = IfBlock->getTerminator();
2103     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2104     OldBr->eraseFromParent();
2105     PrevIfBlock = IfBlock;
2106     IfBlock = NewIfBlock;
2107   }
2108
2109   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2110   Phi->addIncoming(VResult, CondBlock);
2111   Phi->addIncoming(PrevPhi, PrevIfBlock);
2112   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2113   CI->replaceAllUsesWith(NewI);
2114   CI->eraseFromParent();
2115 }
2116
2117 // Translate a masked store intrinsic, like
2118 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
2119 //                               <16 x i1> %mask)
2120 // to a chain of basic blocks, that stores element one-by-one if
2121 // the appropriate mask bit is set
2122 //
2123 //   %1 = bitcast i8* %addr to i32*
2124 //   %2 = extractelement <16 x i1> %mask, i32 0
2125 //   %3 = icmp eq i1 %2, true
2126 //   br i1 %3, label %cond.store, label %else
2127 //
2128 // cond.store:                                       ; preds = %0
2129 //   %4 = extractelement <16 x i32> %val, i32 0
2130 //   %5 = getelementptr i32* %1, i32 0
2131 //   store i32 %4, i32* %5
2132 //   br label %else
2133 //
2134 // else:                                             ; preds = %0, %cond.store
2135 //   %6 = extractelement <16 x i1> %mask, i32 1
2136 //   %7 = icmp eq i1 %6, true
2137 //   br i1 %7, label %cond.store1, label %else2
2138 //
2139 // cond.store1:                                      ; preds = %else
2140 //   %8 = extractelement <16 x i32> %val, i32 1
2141 //   %9 = getelementptr i32* %1, i32 1
2142 //   store i32 %8, i32* %9
2143 //   br label %else2
2144 //   . . .
2145 static void ScalarizeMaskedStore(CallInst *CI) {
2146   Value *Src = CI->getArgOperand(0);
2147   Value *Ptr  = CI->getArgOperand(1);
2148   Value *Alignment = CI->getArgOperand(2);
2149   Value *Mask = CI->getArgOperand(3);
2150
2151   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2152   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
2153   assert(VecType && "Unexpected data type in masked store intrinsic");
2154
2155   Type *EltTy = VecType->getElementType();
2156
2157   IRBuilder<> Builder(CI->getContext());
2158   Instruction *InsertPt = CI;
2159   BasicBlock *IfBlock = CI->getParent();
2160   Builder.SetInsertPoint(InsertPt);
2161   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2162
2163   // Short-cut if the mask is all-true.
2164   bool IsAllOnesMask = isa<Constant>(Mask) &&
2165     cast<Constant>(Mask)->isAllOnesValue();
2166
2167   if (IsAllOnesMask) {
2168     Builder.CreateAlignedStore(Src, Ptr, AlignVal);
2169     CI->eraseFromParent();
2170     return;
2171   }
2172
2173   // Adjust alignment for the scalar instruction.
2174   AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
2175   // Bitcast %addr fron i8* to EltTy*
2176   Type *NewPtrType =
2177     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
2178   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
2179   unsigned VectorWidth = VecType->getNumElements();
2180
2181   if (isa<ConstantVector>(Mask)) {
2182     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2183       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2184           continue;
2185       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2186       Value *Gep =
2187           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2188       Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2189     }
2190     CI->eraseFromParent();
2191     return;
2192   }
2193
2194   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2195
2196     // Fill the "else" block, created in the previous iteration
2197     //
2198     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
2199     //  %to_store = icmp eq i1 %mask_1, true
2200     //  br i1 %to_store, label %cond.store, label %else
2201     //
2202     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
2203     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2204                                     ConstantInt::get(Predicate->getType(), 1));
2205
2206     // Create "cond" block
2207     //
2208     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
2209     //  %EltAddr = getelementptr i32* %1, i32 0
2210     //  %store i32 %OneElt, i32* %EltAddr
2211     //
2212     BasicBlock *CondBlock =
2213         IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
2214     Builder.SetInsertPoint(InsertPt);
2215
2216     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
2217     Value *Gep =
2218         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
2219     Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
2220
2221     // Create "else" block, fill it in the next iteration
2222     BasicBlock *NewIfBlock =
2223         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
2224     Builder.SetInsertPoint(InsertPt);
2225     Instruction *OldBr = IfBlock->getTerminator();
2226     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2227     OldBr->eraseFromParent();
2228     IfBlock = NewIfBlock;
2229   }
2230   CI->eraseFromParent();
2231 }
2232
2233 // Translate a masked gather intrinsic like
2234 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
2235 //                               <16 x i1> %Mask, <16 x i32> %Src)
2236 // to a chain of basic blocks, with loading element one-by-one if
2237 // the appropriate mask bit is set
2238 //
2239 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
2240 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
2241 // % ToLoad0 = icmp eq i1 % Mask0, true
2242 // br i1 % ToLoad0, label %cond.load, label %else
2243 //
2244 // cond.load:
2245 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2246 // % Load0 = load i32, i32* % Ptr0, align 4
2247 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
2248 // br label %else
2249 //
2250 // else:
2251 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
2252 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
2253 // % ToLoad1 = icmp eq i1 % Mask1, true
2254 // br i1 % ToLoad1, label %cond.load1, label %else2
2255 //
2256 // cond.load1:
2257 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2258 // % Load1 = load i32, i32* % Ptr1, align 4
2259 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
2260 // br label %else2
2261 // . . .
2262 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
2263 // ret <16 x i32> %Result
2264 static void ScalarizeMaskedGather(CallInst *CI) {
2265   Value *Ptrs = CI->getArgOperand(0);
2266   Value *Alignment = CI->getArgOperand(1);
2267   Value *Mask = CI->getArgOperand(2);
2268   Value *Src0 = CI->getArgOperand(3);
2269
2270   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
2271
2272   assert(VecType && "Unexpected return type of masked load intrinsic");
2273
2274   IRBuilder<> Builder(CI->getContext());
2275   Instruction *InsertPt = CI;
2276   BasicBlock *IfBlock = CI->getParent();
2277   BasicBlock *CondBlock = nullptr;
2278   BasicBlock *PrevIfBlock = CI->getParent();
2279   Builder.SetInsertPoint(InsertPt);
2280   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2281
2282   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2283
2284   Value *UndefVal = UndefValue::get(VecType);
2285
2286   // The result vector
2287   Value *VResult = UndefVal;
2288   unsigned VectorWidth = VecType->getNumElements();
2289
2290   // Shorten the way if the mask is a vector of constants.
2291   bool IsConstMask = isa<ConstantVector>(Mask);
2292
2293   if (IsConstMask) {
2294     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2295       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2296         continue;
2297       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2298                                                 "Ptr" + Twine(Idx));
2299       LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2300                                                  "Load" + Twine(Idx));
2301       VResult = Builder.CreateInsertElement(VResult, Load,
2302                                             Builder.getInt32(Idx),
2303                                             "Res" + Twine(Idx));
2304     }
2305     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
2306     CI->replaceAllUsesWith(NewI);
2307     CI->eraseFromParent();
2308     return;
2309   }
2310
2311   PHINode *Phi = nullptr;
2312   Value *PrevPhi = UndefVal;
2313
2314   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2315
2316     // Fill the "else" block, created in the previous iteration
2317     //
2318     //  %Mask1 = extractelement <16 x i1> %Mask, i32 1
2319     //  %ToLoad1 = icmp eq i1 %Mask1, true
2320     //  br i1 %ToLoad1, label %cond.load, label %else
2321     //
2322     if (Idx > 0) {
2323       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
2324       Phi->addIncoming(VResult, CondBlock);
2325       Phi->addIncoming(PrevPhi, PrevIfBlock);
2326       PrevPhi = Phi;
2327       VResult = Phi;
2328     }
2329
2330     Value *Predicate = Builder.CreateExtractElement(Mask,
2331                                                     Builder.getInt32(Idx),
2332                                                     "Mask" + Twine(Idx));
2333     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2334                                     ConstantInt::get(Predicate->getType(), 1),
2335                                     "ToLoad" + Twine(Idx));
2336
2337     // Create "cond" block
2338     //
2339     //  %EltAddr = getelementptr i32* %1, i32 0
2340     //  %Elt = load i32* %EltAddr
2341     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
2342     //
2343     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
2344     Builder.SetInsertPoint(InsertPt);
2345
2346     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2347                                               "Ptr" + Twine(Idx));
2348     LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
2349                                                "Load" + Twine(Idx));
2350     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
2351                                           "Res" + Twine(Idx));
2352
2353     // Create "else" block, fill it in the next iteration
2354     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2355     Builder.SetInsertPoint(InsertPt);
2356     Instruction *OldBr = IfBlock->getTerminator();
2357     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2358     OldBr->eraseFromParent();
2359     PrevIfBlock = IfBlock;
2360     IfBlock = NewIfBlock;
2361   }
2362
2363   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
2364   Phi->addIncoming(VResult, CondBlock);
2365   Phi->addIncoming(PrevPhi, PrevIfBlock);
2366   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
2367   CI->replaceAllUsesWith(NewI);
2368   CI->eraseFromParent();
2369 }
2370
2371 // Translate a masked scatter intrinsic, like
2372 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
2373 //                                  <16 x i1> %Mask)
2374 // to a chain of basic blocks, that stores element one-by-one if
2375 // the appropriate mask bit is set.
2376 //
2377 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
2378 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
2379 // % ToStore0 = icmp eq i1 % Mask0, true
2380 // br i1 %ToStore0, label %cond.store, label %else
2381 //
2382 // cond.store:
2383 // % Elt0 = extractelement <16 x i32> %Src, i32 0
2384 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
2385 // store i32 %Elt0, i32* % Ptr0, align 4
2386 // br label %else
2387 //
2388 // else:
2389 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
2390 // % ToStore1 = icmp eq i1 % Mask1, true
2391 // br i1 % ToStore1, label %cond.store1, label %else2
2392 //
2393 // cond.store1:
2394 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2395 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2396 // store i32 % Elt1, i32* % Ptr1, align 4
2397 // br label %else2
2398 //   . . .
2399 static void ScalarizeMaskedScatter(CallInst *CI) {
2400   Value *Src = CI->getArgOperand(0);
2401   Value *Ptrs = CI->getArgOperand(1);
2402   Value *Alignment = CI->getArgOperand(2);
2403   Value *Mask = CI->getArgOperand(3);
2404
2405   assert(isa<VectorType>(Src->getType()) &&
2406          "Unexpected data type in masked scatter intrinsic");
2407   assert(isa<VectorType>(Ptrs->getType()) &&
2408          isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
2409          "Vector of pointers is expected in masked scatter intrinsic");
2410
2411   IRBuilder<> Builder(CI->getContext());
2412   Instruction *InsertPt = CI;
2413   BasicBlock *IfBlock = CI->getParent();
2414   Builder.SetInsertPoint(InsertPt);
2415   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
2416
2417   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
2418   unsigned VectorWidth = Src->getType()->getVectorNumElements();
2419
2420   // Shorten the way if the mask is a vector of constants.
2421   bool IsConstMask = isa<ConstantVector>(Mask);
2422
2423   if (IsConstMask) {
2424     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2425       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
2426         continue;
2427       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2428                                                    "Elt" + Twine(Idx));
2429       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2430                                                 "Ptr" + Twine(Idx));
2431       Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2432     }
2433     CI->eraseFromParent();
2434     return;
2435   }
2436   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
2437     // Fill the "else" block, created in the previous iteration
2438     //
2439     //  % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
2440     //  % ToStore = icmp eq i1 % Mask1, true
2441     //  br i1 % ToStore, label %cond.store, label %else
2442     //
2443     Value *Predicate = Builder.CreateExtractElement(Mask,
2444                                                     Builder.getInt32(Idx),
2445                                                     "Mask" + Twine(Idx));
2446     Value *Cmp =
2447        Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
2448                           ConstantInt::get(Predicate->getType(), 1),
2449                           "ToStore" + Twine(Idx));
2450
2451     // Create "cond" block
2452     //
2453     //  % Elt1 = extractelement <16 x i32> %Src, i32 1
2454     //  % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2455     //  %store i32 % Elt1, i32* % Ptr1
2456     //
2457     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2458     Builder.SetInsertPoint(InsertPt);
2459
2460     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2461                                                  "Elt" + Twine(Idx));
2462     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2463                                               "Ptr" + Twine(Idx));
2464     Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2465
2466     // Create "else" block, fill it in the next iteration
2467     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2468     Builder.SetInsertPoint(InsertPt);
2469     Instruction *OldBr = IfBlock->getTerminator();
2470     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2471     OldBr->eraseFromParent();
2472     IfBlock = NewIfBlock;
2473   }
2474   CI->eraseFromParent();
2475 }
2476
2477 /// If counting leading or trailing zeros is an expensive operation and a zero
2478 /// input is defined, add a check for zero to avoid calling the intrinsic.
2479 ///
2480 /// We want to transform:
2481 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2482 ///
2483 /// into:
2484 ///   entry:
2485 ///     %cmpz = icmp eq i64 %A, 0
2486 ///     br i1 %cmpz, label %cond.end, label %cond.false
2487 ///   cond.false:
2488 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2489 ///     br label %cond.end
2490 ///   cond.end:
2491 ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2492 ///
2493 /// If the transform is performed, return true and set ModifiedDT to true.
2494 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2495                                   const TargetLowering *TLI,
2496                                   const DataLayout *DL,
2497                                   bool &ModifiedDT) {
2498   if (!TLI || !DL)
2499     return false;
2500
2501   // If a zero input is undefined, it doesn't make sense to despeculate that.
2502   if (match(CountZeros->getOperand(1), m_One()))
2503     return false;
2504
2505   // If it's cheap to speculate, there's nothing to do.
2506   auto IntrinsicID = CountZeros->getIntrinsicID();
2507   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2508       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2509     return false;
2510
2511   // Only handle legal scalar cases. Anything else requires too much work.
2512   Type *Ty = CountZeros->getType();
2513   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2514   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
2515     return false;
2516
2517   // The intrinsic will be sunk behind a compare against zero and branch.
2518   BasicBlock *StartBlock = CountZeros->getParent();
2519   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2520
2521   // Create another block after the count zero intrinsic. A PHI will be added
2522   // in this block to select the result of the intrinsic or the bit-width
2523   // constant if the input to the intrinsic is zero.
2524   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2525   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2526
2527   // Set up a builder to create a compare, conditional branch, and PHI.
2528   IRBuilder<> Builder(CountZeros->getContext());
2529   Builder.SetInsertPoint(StartBlock->getTerminator());
2530   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2531
2532   // Replace the unconditional branch that was created by the first split with
2533   // a compare against zero and a conditional branch.
2534   Value *Zero = Constant::getNullValue(Ty);
2535   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2536   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2537   StartBlock->getTerminator()->eraseFromParent();
2538
2539   // Create a PHI in the end block to select either the output of the intrinsic
2540   // or the bit width of the operand.
2541   Builder.SetInsertPoint(&EndBlock->front());
2542   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2543   CountZeros->replaceAllUsesWith(PN);
2544   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2545   PN->addIncoming(BitWidth, StartBlock);
2546   PN->addIncoming(CountZeros, CallBlock);
2547
2548   // We are explicitly handling the zero case, so we can set the intrinsic's
2549   // undefined zero argument to 'true'. This will also prevent reprocessing the
2550   // intrinsic; we only despeculate when a zero input is defined.
2551   CountZeros->setArgOperand(1, Builder.getTrue());
2552   ModifiedDT = true;
2553   return true;
2554 }
2555
2556 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
2557   BasicBlock *BB = CI->getParent();
2558
2559   // Lower inline assembly if we can.
2560   // If we found an inline asm expession, and if the target knows how to
2561   // lower it to normal LLVM code, do so now.
2562   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2563     if (TLI->ExpandInlineAsm(CI)) {
2564       // Avoid invalidating the iterator.
2565       CurInstIterator = BB->begin();
2566       // Avoid processing instructions out of order, which could cause
2567       // reuse before a value is defined.
2568       SunkAddrs.clear();
2569       return true;
2570     }
2571     // Sink address computing for memory operands into the block.
2572     if (optimizeInlineAsmInst(CI))
2573       return true;
2574   }
2575
2576   // Align the pointer arguments to this call if the target thinks it's a good
2577   // idea
2578   unsigned MinSize, PrefAlign;
2579   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2580     for (auto &Arg : CI->arg_operands()) {
2581       // We want to align both objects whose address is used directly and
2582       // objects whose address is used in casts and GEPs, though it only makes
2583       // sense for GEPs if the offset is a multiple of the desired alignment and
2584       // if size - offset meets the size threshold.
2585       if (!Arg->getType()->isPointerTy())
2586         continue;
2587       APInt Offset(DL->getPointerSizeInBits(
2588                        cast<PointerType>(Arg->getType())->getAddressSpace()),
2589                    0);
2590       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2591       uint64_t Offset2 = Offset.getLimitedValue();
2592       if ((Offset2 & (PrefAlign-1)) != 0)
2593         continue;
2594       AllocaInst *AI;
2595       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2596           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2597         AI->setAlignment(PrefAlign);
2598       // Global variables can only be aligned if they are defined in this
2599       // object (i.e. they are uniquely initialized in this object), and
2600       // over-aligning global variables that have an explicit section is
2601       // forbidden.
2602       GlobalVariable *GV;
2603       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2604           GV->getAlignment() < PrefAlign &&
2605           DL->getTypeAllocSize(GV->getType()->getElementType()) >=
2606               MinSize + Offset2)
2607         GV->setAlignment(PrefAlign);
2608     }
2609     // If this is a memcpy (or similar) then we may be able to improve the
2610     // alignment
2611     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2612       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2613       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2614         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2615       if (Align > MI->getAlignment())
2616         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2617     }
2618   }
2619
2620   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2621   if (II) {
2622     switch (II->getIntrinsicID()) {
2623     default: break;
2624     case Intrinsic::objectsize: {
2625       // Lower all uses of llvm.objectsize.*
2626       bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
2627       Type *ReturnTy = CI->getType();
2628       Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
2629
2630       // Substituting this can cause recursive simplifications, which can
2631       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
2632       // happens.
2633       WeakVH IterHandle(&*CurInstIterator);
2634
2635       replaceAndRecursivelySimplify(CI, RetVal,
2636                                     TLInfo, nullptr);
2637
2638       // If the iterator instruction was recursively deleted, start over at the
2639       // start of the block.
2640       if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
2641         CurInstIterator = BB->begin();
2642         SunkAddrs.clear();
2643       }
2644       return true;
2645     }
2646     case Intrinsic::masked_load: {
2647       // Scalarize unsupported vector masked load
2648       if (!TTI->isLegalMaskedLoad(CI->getType())) {
2649         ScalarizeMaskedLoad(CI);
2650         ModifiedDT = true;
2651         return true;
2652       }
2653       return false;
2654     }
2655     case Intrinsic::masked_store: {
2656       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
2657         ScalarizeMaskedStore(CI);
2658         ModifiedDT = true;
2659         return true;
2660       }
2661       return false;
2662     }
2663     case Intrinsic::masked_gather: {
2664       if (!TTI->isLegalMaskedGather(CI->getType())) {
2665         ScalarizeMaskedGather(CI);
2666         ModifiedDT = true;
2667         return true;
2668       }
2669       return false;
2670     }
2671     case Intrinsic::masked_scatter: {
2672       if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
2673         ScalarizeMaskedScatter(CI);
2674         ModifiedDT = true;
2675         return true;
2676       }
2677       return false;
2678     }
2679     case Intrinsic::aarch64_stlxr:
2680     case Intrinsic::aarch64_stxr: {
2681       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2682       if (!ExtVal || !ExtVal->hasOneUse() ||
2683           ExtVal->getParent() == CI->getParent())
2684         return false;
2685       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2686       ExtVal->moveBefore(CI);
2687       // Mark this instruction as "inserted by CGP", so that other
2688       // optimizations don't touch it.
2689       InsertedInsts.insert(ExtVal);
2690       return true;
2691     }
2692     case Intrinsic::invariant_group_barrier:
2693       II->replaceAllUsesWith(II->getArgOperand(0));
2694       II->eraseFromParent();
2695       return true;
2696
2697     case Intrinsic::cttz:
2698     case Intrinsic::ctlz:
2699       // If counting zeros is expensive, try to avoid it.
2700       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2701     }
2702
2703     if (TLI) {
2704       // Unknown address space.
2705       // TODO: Target hook to pick which address space the intrinsic cares
2706       // about?
2707       unsigned AddrSpace = ~0u;
2708       SmallVector<Value*, 2> PtrOps;
2709       Type *AccessTy;
2710       if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
2711         while (!PtrOps.empty())
2712           if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
2713             return true;
2714     }
2715   }
2716
2717   // From here on out we're working with named functions.
2718   if (!CI->getCalledFunction()) return false;
2719
2720   // Lower all default uses of _chk calls.  This is very similar
2721   // to what InstCombineCalls does, but here we are only lowering calls
2722   // to fortified library functions (e.g. __memcpy_chk) that have the default
2723   // "don't know" as the objectsize.  Anything else should be left alone.
2724   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2725   if (Value *V = Simplifier.optimizeCall(CI)) {
2726     CI->replaceAllUsesWith(V);
2727     CI->eraseFromParent();
2728     return true;
2729   }
2730   return false;
2731 }
2732
2733 /// Look for opportunities to duplicate return instructions to the predecessor
2734 /// to enable tail call optimizations. The case it is currently looking for is:
2735 /// @code
2736 /// bb0:
2737 ///   %tmp0 = tail call i32 @f0()
2738 ///   br label %return
2739 /// bb1:
2740 ///   %tmp1 = tail call i32 @f1()
2741 ///   br label %return
2742 /// bb2:
2743 ///   %tmp2 = tail call i32 @f2()
2744 ///   br label %return
2745 /// return:
2746 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2747 ///   ret i32 %retval
2748 /// @endcode
2749 ///
2750 /// =>
2751 ///
2752 /// @code
2753 /// bb0:
2754 ///   %tmp0 = tail call i32 @f0()
2755 ///   ret i32 %tmp0
2756 /// bb1:
2757 ///   %tmp1 = tail call i32 @f1()
2758 ///   ret i32 %tmp1
2759 /// bb2:
2760 ///   %tmp2 = tail call i32 @f2()
2761 ///   ret i32 %tmp2
2762 /// @endcode
2763 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
2764   if (!TLI)
2765     return false;
2766
2767   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
2768   if (!RI)
2769     return false;
2770
2771   PHINode *PN = nullptr;
2772   BitCastInst *BCI = nullptr;
2773   Value *V = RI->getReturnValue();
2774   if (V) {
2775     BCI = dyn_cast<BitCastInst>(V);
2776     if (BCI)
2777       V = BCI->getOperand(0);
2778
2779     PN = dyn_cast<PHINode>(V);
2780     if (!PN)
2781       return false;
2782   }
2783
2784   if (PN && PN->getParent() != BB)
2785     return false;
2786
2787   // It's not safe to eliminate the sign / zero extension of the return value.
2788   // See llvm::isInTailCallPosition().
2789   const Function *F = BB->getParent();
2790   AttributeSet CallerAttrs = F->getAttributes();
2791   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
2792       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
2793     return false;
2794
2795   // Make sure there are no instructions between the PHI and return, or that the
2796   // return is the first instruction in the block.
2797   if (PN) {
2798     BasicBlock::iterator BI = BB->begin();
2799     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
2800     if (&*BI == BCI)
2801       // Also skip over the bitcast.
2802       ++BI;
2803     if (&*BI != RI)
2804       return false;
2805   } else {
2806     BasicBlock::iterator BI = BB->begin();
2807     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2808     if (&*BI != RI)
2809       return false;
2810   }
2811
2812   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2813   /// call.
2814   SmallVector<CallInst*, 4> TailCalls;
2815   if (PN) {
2816     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2817       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2818       // Make sure the phi value is indeed produced by the tail call.
2819       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2820           TLI->mayBeEmittedAsTailCall(CI))
2821         TailCalls.push_back(CI);
2822     }
2823   } else {
2824     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2825     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
2826       if (!VisitedBBs.insert(*PI).second)
2827         continue;
2828
2829       BasicBlock::InstListType &InstList = (*PI)->getInstList();
2830       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2831       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2832       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2833       if (RI == RE)
2834         continue;
2835
2836       CallInst *CI = dyn_cast<CallInst>(&*RI);
2837       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
2838         TailCalls.push_back(CI);
2839     }
2840   }
2841
2842   bool Changed = false;
2843   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2844     CallInst *CI = TailCalls[i];
2845     CallSite CS(CI);
2846
2847     // Conservatively require the attributes of the call to match those of the
2848     // return. Ignore noalias because it doesn't affect the call sequence.
2849     AttributeSet CalleeAttrs = CS.getAttributes();
2850     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2851           removeAttribute(Attribute::NoAlias) !=
2852         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
2853           removeAttribute(Attribute::NoAlias))
2854       continue;
2855
2856     // Make sure the call instruction is followed by an unconditional branch to
2857     // the return block.
2858     BasicBlock *CallBB = CI->getParent();
2859     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2860     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2861       continue;
2862
2863     // Duplicate the return into CallBB.
2864     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
2865     ModifiedDT = Changed = true;
2866     ++NumRetsDup;
2867   }
2868
2869   // If we eliminated all predecessors of the block, delete the block now.
2870   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
2871     BB->eraseFromParent();
2872
2873   return Changed;
2874 }
2875
2876 //===----------------------------------------------------------------------===//
2877 // Memory Optimization
2878 //===----------------------------------------------------------------------===//
2879
2880 namespace {
2881
2882 /// This is an extended version of TargetLowering::AddrMode
2883 /// which holds actual Value*'s for register values.
2884 struct ExtAddrMode : public TargetLowering::AddrMode {
2885   Value *BaseReg;
2886   Value *ScaledReg;
2887   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2888   void print(raw_ostream &OS) const;
2889   void dump() const;
2890
2891   bool operator==(const ExtAddrMode& O) const {
2892     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2893            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2894            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2895   }
2896 };
2897
2898 #ifndef NDEBUG
2899 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2900   AM.print(OS);
2901   return OS;
2902 }
2903 #endif
2904
2905 void ExtAddrMode::print(raw_ostream &OS) const {
2906   bool NeedPlus = false;
2907   OS << "[";
2908   if (BaseGV) {
2909     OS << (NeedPlus ? " + " : "")
2910        << "GV:";
2911     BaseGV->printAsOperand(OS, /*PrintType=*/false);
2912     NeedPlus = true;
2913   }
2914
2915   if (BaseOffs) {
2916     OS << (NeedPlus ? " + " : "")
2917        << BaseOffs;
2918     NeedPlus = true;
2919   }
2920
2921   if (BaseReg) {
2922     OS << (NeedPlus ? " + " : "")
2923        << "Base:";
2924     BaseReg->printAsOperand(OS, /*PrintType=*/false);
2925     NeedPlus = true;
2926   }
2927   if (Scale) {
2928     OS << (NeedPlus ? " + " : "")
2929        << Scale << "*";
2930     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2931   }
2932
2933   OS << ']';
2934 }
2935
2936 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2937 void ExtAddrMode::dump() const {
2938   print(dbgs());
2939   dbgs() << '\n';
2940 }
2941 #endif
2942
2943 /// \brief This class provides transaction based operation on the IR.
2944 /// Every change made through this class is recorded in the internal state and
2945 /// can be undone (rollback) until commit is called.
2946 class TypePromotionTransaction {
2947
2948   /// \brief This represents the common interface of the individual transaction.
2949   /// Each class implements the logic for doing one specific modification on
2950   /// the IR via the TypePromotionTransaction.
2951   class TypePromotionAction {
2952   protected:
2953     /// The Instruction modified.
2954     Instruction *Inst;
2955
2956   public:
2957     /// \brief Constructor of the action.
2958     /// The constructor performs the related action on the IR.
2959     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2960
2961     virtual ~TypePromotionAction() {}
2962
2963     /// \brief Undo the modification done by this action.
2964     /// When this method is called, the IR must be in the same state as it was
2965     /// before this action was applied.
2966     /// \pre Undoing the action works if and only if the IR is in the exact same
2967     /// state as it was directly after this action was applied.
2968     virtual void undo() = 0;
2969
2970     /// \brief Advocate every change made by this action.
2971     /// When the results on the IR of the action are to be kept, it is important
2972     /// to call this function, otherwise hidden information may be kept forever.
2973     virtual void commit() {
2974       // Nothing to be done, this action is not doing anything.
2975     }
2976   };
2977
2978   /// \brief Utility to remember the position of an instruction.
2979   class InsertionHandler {
2980     /// Position of an instruction.
2981     /// Either an instruction:
2982     /// - Is the first in a basic block: BB is used.
2983     /// - Has a previous instructon: PrevInst is used.
2984     union {
2985       Instruction *PrevInst;
2986       BasicBlock *BB;
2987     } Point;
2988     /// Remember whether or not the instruction had a previous instruction.
2989     bool HasPrevInstruction;
2990
2991   public:
2992     /// \brief Record the position of \p Inst.
2993     InsertionHandler(Instruction *Inst) {
2994       BasicBlock::iterator It = Inst->getIterator();
2995       HasPrevInstruction = (It != (Inst->getParent()->begin()));
2996       if (HasPrevInstruction)
2997         Point.PrevInst = &*--It;
2998       else
2999         Point.BB = Inst->getParent();
3000     }
3001
3002     /// \brief Insert \p Inst at the recorded position.
3003     void insert(Instruction *Inst) {
3004       if (HasPrevInstruction) {
3005         if (Inst->getParent())
3006           Inst->removeFromParent();
3007         Inst->insertAfter(Point.PrevInst);
3008       } else {
3009         Instruction *Position = &*Point.BB->getFirstInsertionPt();
3010         if (Inst->getParent())
3011           Inst->moveBefore(Position);
3012         else
3013           Inst->insertBefore(Position);
3014       }
3015     }
3016   };
3017
3018   /// \brief Move an instruction before another.
3019   class InstructionMoveBefore : public TypePromotionAction {
3020     /// Original position of the instruction.
3021     InsertionHandler Position;
3022
3023   public:
3024     /// \brief Move \p Inst before \p Before.
3025     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
3026         : TypePromotionAction(Inst), Position(Inst) {
3027       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
3028       Inst->moveBefore(Before);
3029     }
3030
3031     /// \brief Move the instruction back to its original position.
3032     void undo() override {
3033       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3034       Position.insert(Inst);
3035     }
3036   };
3037
3038   /// \brief Set the operand of an instruction with a new value.
3039   class OperandSetter : public TypePromotionAction {
3040     /// Original operand of the instruction.
3041     Value *Origin;
3042     /// Index of the modified instruction.
3043     unsigned Idx;
3044
3045   public:
3046     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
3047     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3048         : TypePromotionAction(Inst), Idx(Idx) {
3049       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3050                    << "for:" << *Inst << "\n"
3051                    << "with:" << *NewVal << "\n");
3052       Origin = Inst->getOperand(Idx);
3053       Inst->setOperand(Idx, NewVal);
3054     }
3055
3056     /// \brief Restore the original value of the instruction.
3057     void undo() override {
3058       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3059                    << "for: " << *Inst << "\n"
3060                    << "with: " << *Origin << "\n");
3061       Inst->setOperand(Idx, Origin);
3062     }
3063   };
3064
3065   /// \brief Hide the operands of an instruction.
3066   /// Do as if this instruction was not using any of its operands.
3067   class OperandsHider : public TypePromotionAction {
3068     /// The list of original operands.
3069     SmallVector<Value *, 4> OriginalValues;
3070
3071   public:
3072     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
3073     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3074       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3075       unsigned NumOpnds = Inst->getNumOperands();
3076       OriginalValues.reserve(NumOpnds);
3077       for (unsigned It = 0; It < NumOpnds; ++It) {
3078         // Save the current operand.
3079         Value *Val = Inst->getOperand(It);
3080         OriginalValues.push_back(Val);
3081         // Set a dummy one.
3082         // We could use OperandSetter here, but that would imply an overhead
3083         // that we are not willing to pay.
3084         Inst->setOperand(It, UndefValue::get(Val->getType()));
3085       }
3086     }
3087
3088     /// \brief Restore the original list of uses.
3089     void undo() override {
3090       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3091       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3092         Inst->setOperand(It, OriginalValues[It]);
3093     }
3094   };
3095
3096   /// \brief Build a truncate instruction.
3097   class TruncBuilder : public TypePromotionAction {
3098     Value *Val;
3099   public:
3100     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
3101     /// result.
3102     /// trunc Opnd to Ty.
3103     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3104       IRBuilder<> Builder(Opnd);
3105       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3106       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3107     }
3108
3109     /// \brief Get the built value.
3110     Value *getBuiltValue() { return Val; }
3111
3112     /// \brief Remove the built instruction.
3113     void undo() override {
3114       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3115       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3116         IVal->eraseFromParent();
3117     }
3118   };
3119
3120   /// \brief Build a sign extension instruction.
3121   class SExtBuilder : public TypePromotionAction {
3122     Value *Val;
3123   public:
3124     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
3125     /// result.
3126     /// sext Opnd to Ty.
3127     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3128         : TypePromotionAction(InsertPt) {
3129       IRBuilder<> Builder(InsertPt);
3130       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3131       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3132     }
3133
3134     /// \brief Get the built value.
3135     Value *getBuiltValue() { return Val; }
3136
3137     /// \brief Remove the built instruction.
3138     void undo() override {
3139       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3140       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3141         IVal->eraseFromParent();
3142     }
3143   };
3144
3145   /// \brief Build a zero extension instruction.
3146   class ZExtBuilder : public TypePromotionAction {
3147     Value *Val;
3148   public:
3149     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
3150     /// result.
3151     /// zext Opnd to Ty.
3152     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3153         : TypePromotionAction(InsertPt) {
3154       IRBuilder<> Builder(InsertPt);
3155       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3156       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3157     }
3158
3159     /// \brief Get the built value.
3160     Value *getBuiltValue() { return Val; }
3161
3162     /// \brief Remove the built instruction.
3163     void undo() override {
3164       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3165       if (Instruction *IVal = dyn_cast<Instruction>(Val))
3166         IVal->eraseFromParent();
3167     }
3168   };
3169
3170   /// \brief Mutate an instruction to another type.
3171   class TypeMutator : public TypePromotionAction {
3172     /// Record the original type.
3173     Type *OrigTy;
3174
3175   public:
3176     /// \brief Mutate the type of \p Inst into \p NewTy.
3177     TypeMutator(Instruction *Inst, Type *NewTy)
3178         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3179       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3180                    << "\n");
3181       Inst->mutateType(NewTy);
3182     }
3183
3184     /// \brief Mutate the instruction back to its original type.
3185     void undo() override {
3186       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3187                    << "\n");
3188       Inst->mutateType(OrigTy);
3189     }
3190   };
3191
3192   /// \brief Replace the uses of an instruction by another instruction.
3193   class UsesReplacer : public TypePromotionAction {
3194     /// Helper structure to keep track of the replaced uses.
3195     struct InstructionAndIdx {
3196       /// The instruction using the instruction.
3197       Instruction *Inst;
3198       /// The index where this instruction is used for Inst.
3199       unsigned Idx;
3200       InstructionAndIdx(Instruction *Inst, unsigned Idx)
3201           : Inst(Inst), Idx(Idx) {}
3202     };
3203
3204     /// Keep track of the original uses (pair Instruction, Index).
3205     SmallVector<InstructionAndIdx, 4> OriginalUses;
3206     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
3207
3208   public:
3209     /// \brief Replace all the use of \p Inst by \p New.
3210     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
3211       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3212                    << "\n");
3213       // Record the original uses.
3214       for (Use &U : Inst->uses()) {
3215         Instruction *UserI = cast<Instruction>(U.getUser());
3216         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3217       }
3218       // Now, we can replace the uses.
3219       Inst->replaceAllUsesWith(New);
3220     }
3221
3222     /// \brief Reassign the original uses of Inst to Inst.
3223     void undo() override {
3224       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3225       for (use_iterator UseIt = OriginalUses.begin(),
3226                         EndIt = OriginalUses.end();
3227            UseIt != EndIt; ++UseIt) {
3228         UseIt->Inst->setOperand(UseIt->Idx, Inst);
3229       }
3230     }
3231   };
3232
3233   /// \brief Remove an instruction from the IR.
3234   class InstructionRemover : public TypePromotionAction {
3235     /// Original position of the instruction.
3236     InsertionHandler Inserter;
3237     /// Helper structure to hide all the link to the instruction. In other
3238     /// words, this helps to do as if the instruction was removed.
3239     OperandsHider Hider;
3240     /// Keep track of the uses replaced, if any.
3241     UsesReplacer *Replacer;
3242
3243   public:
3244     /// \brief Remove all reference of \p Inst and optinally replace all its
3245     /// uses with New.
3246     /// \pre If !Inst->use_empty(), then New != nullptr
3247     InstructionRemover(Instruction *Inst, Value *New = nullptr)
3248         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3249           Replacer(nullptr) {
3250       if (New)
3251         Replacer = new UsesReplacer(Inst, New);
3252       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3253       Inst->removeFromParent();
3254     }
3255
3256     ~InstructionRemover() override { delete Replacer; }
3257
3258     /// \brief Really remove the instruction.
3259     void commit() override { delete Inst; }
3260
3261     /// \brief Resurrect the instruction and reassign it to the proper uses if
3262     /// new value was provided when build this action.
3263     void undo() override {
3264       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3265       Inserter.insert(Inst);
3266       if (Replacer)
3267         Replacer->undo();
3268       Hider.undo();
3269     }
3270   };
3271
3272 public:
3273   /// Restoration point.
3274   /// The restoration point is a pointer to an action instead of an iterator
3275   /// because the iterator may be invalidated but not the pointer.
3276   typedef const TypePromotionAction *ConstRestorationPt;
3277   /// Advocate every changes made in that transaction.
3278   void commit();
3279   /// Undo all the changes made after the given point.
3280   void rollback(ConstRestorationPt Point);
3281   /// Get the current restoration point.
3282   ConstRestorationPt getRestorationPoint() const;
3283
3284   /// \name API for IR modification with state keeping to support rollback.
3285   /// @{
3286   /// Same as Instruction::setOperand.
3287   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3288   /// Same as Instruction::eraseFromParent.
3289   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3290   /// Same as Value::replaceAllUsesWith.
3291   void replaceAllUsesWith(Instruction *Inst, Value *New);
3292   /// Same as Value::mutateType.
3293   void mutateType(Instruction *Inst, Type *NewTy);
3294   /// Same as IRBuilder::createTrunc.
3295   Value *createTrunc(Instruction *Opnd, Type *Ty);
3296   /// Same as IRBuilder::createSExt.
3297   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3298   /// Same as IRBuilder::createZExt.
3299   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3300   /// Same as Instruction::moveBefore.
3301   void moveBefore(Instruction *Inst, Instruction *Before);
3302   /// @}
3303
3304 private:
3305   /// The ordered list of actions made so far.
3306   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3307   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
3308 };
3309
3310 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3311                                           Value *NewVal) {
3312   Actions.push_back(
3313       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3314 }
3315
3316 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3317                                                 Value *NewVal) {
3318   Actions.push_back(
3319       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
3320 }
3321
3322 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3323                                                   Value *New) {
3324   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3325 }
3326
3327 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3328   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3329 }
3330
3331 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3332                                              Type *Ty) {
3333   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3334   Value *Val = Ptr->getBuiltValue();
3335   Actions.push_back(std::move(Ptr));
3336   return Val;
3337 }
3338
3339 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3340                                             Value *Opnd, Type *Ty) {
3341   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3342   Value *Val = Ptr->getBuiltValue();
3343   Actions.push_back(std::move(Ptr));
3344   return Val;
3345 }
3346
3347 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3348                                             Value *Opnd, Type *Ty) {
3349   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3350   Value *Val = Ptr->getBuiltValue();
3351   Actions.push_back(std::move(Ptr));
3352   return Val;
3353 }
3354
3355 void TypePromotionTransaction::moveBefore(Instruction *Inst,
3356                                           Instruction *Before) {
3357   Actions.push_back(
3358       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3359 }
3360
3361 TypePromotionTransaction::ConstRestorationPt
3362 TypePromotionTransaction::getRestorationPoint() const {
3363   return !Actions.empty() ? Actions.back().get() : nullptr;
3364 }
3365
3366 void TypePromotionTransaction::commit() {
3367   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3368        ++It)
3369     (*It)->commit();
3370   Actions.clear();
3371 }
3372
3373 void TypePromotionTransaction::rollback(
3374     TypePromotionTransaction::ConstRestorationPt Point) {
3375   while (!Actions.empty() && Point != Actions.back().get()) {
3376     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3377     Curr->undo();
3378   }
3379 }
3380
3381 /// \brief A helper class for matching addressing modes.
3382 ///
3383 /// This encapsulates the logic for matching the target-legal addressing modes.
3384 class AddressingModeMatcher {
3385   SmallVectorImpl<Instruction*> &AddrModeInsts;
3386   const TargetMachine &TM;
3387   const TargetLowering &TLI;
3388   const DataLayout &DL;
3389
3390   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3391   /// the memory instruction that we're computing this address for.
3392   Type *AccessTy;
3393   unsigned AddrSpace;
3394   Instruction *MemoryInst;
3395
3396   /// This is the addressing mode that we're building up. This is
3397   /// part of the return value of this addressing mode matching stuff.
3398   ExtAddrMode &AddrMode;
3399
3400   /// The instructions inserted by other CodeGenPrepare optimizations.
3401   const SetOfInstrs &InsertedInsts;
3402   /// A map from the instructions to their type before promotion.
3403   InstrToOrigTy &PromotedInsts;
3404   /// The ongoing transaction where every action should be registered.
3405   TypePromotionTransaction &TPT;
3406
3407   /// This is set to true when we should not do profitability checks.
3408   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3409   bool IgnoreProfitability;
3410
3411   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
3412                         const TargetMachine &TM, Type *AT, unsigned AS,
3413                         Instruction *MI, ExtAddrMode &AM,
3414                         const SetOfInstrs &InsertedInsts,
3415                         InstrToOrigTy &PromotedInsts,
3416                         TypePromotionTransaction &TPT)
3417       : AddrModeInsts(AMI), TM(TM),
3418         TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
3419                  ->getTargetLowering()),
3420         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3421         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3422         PromotedInsts(PromotedInsts), TPT(TPT) {
3423     IgnoreProfitability = false;
3424   }
3425 public:
3426
3427   /// Find the maximal addressing mode that a load/store of V can fold,
3428   /// give an access type of AccessTy.  This returns a list of involved
3429   /// instructions in AddrModeInsts.
3430   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3431   /// optimizations.
3432   /// \p PromotedInsts maps the instructions to their type before promotion.
3433   /// \p The ongoing transaction where every action should be registered.
3434   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
3435                            Instruction *MemoryInst,
3436                            SmallVectorImpl<Instruction*> &AddrModeInsts,
3437                            const TargetMachine &TM,
3438                            const SetOfInstrs &InsertedInsts,
3439                            InstrToOrigTy &PromotedInsts,
3440                            TypePromotionTransaction &TPT) {
3441     ExtAddrMode Result;
3442
3443     bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
3444                                          MemoryInst, Result, InsertedInsts,
3445                                          PromotedInsts, TPT).matchAddr(V, 0);
3446     (void)Success; assert(Success && "Couldn't select *anything*?");
3447     return Result;
3448   }
3449 private:
3450   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3451   bool matchAddr(Value *V, unsigned Depth);
3452   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
3453                           bool *MovedAway = nullptr);
3454   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3455                                             ExtAddrMode &AMBefore,
3456                                             ExtAddrMode &AMAfter);
3457   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3458   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3459                              Value *PromotedOperand) const;
3460 };
3461
3462 /// Try adding ScaleReg*Scale to the current addressing mode.
3463 /// Return true and update AddrMode if this addr mode is legal for the target,
3464 /// false if not.
3465 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3466                                              unsigned Depth) {
3467   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3468   // mode.  Just process that directly.
3469   if (Scale == 1)
3470     return matchAddr(ScaleReg, Depth);
3471
3472   // If the scale is 0, it takes nothing to add this.
3473   if (Scale == 0)
3474     return true;
3475
3476   // If we already have a scale of this value, we can add to it, otherwise, we
3477   // need an available scale field.
3478   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3479     return false;
3480
3481   ExtAddrMode TestAddrMode = AddrMode;
3482
3483   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
3484   // [A+B + A*7] -> [B+A*8].
3485   TestAddrMode.Scale += Scale;
3486   TestAddrMode.ScaledReg = ScaleReg;
3487
3488   // If the new address isn't legal, bail out.
3489   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3490     return false;
3491
3492   // It was legal, so commit it.
3493   AddrMode = TestAddrMode;
3494
3495   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
3496   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
3497   // X*Scale + C*Scale to addr mode.
3498   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3499   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
3500       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3501     TestAddrMode.ScaledReg = AddLHS;
3502     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
3503
3504     // If this addressing mode is legal, commit it and remember that we folded
3505     // this instruction.
3506     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3507       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3508       AddrMode = TestAddrMode;
3509       return true;
3510     }
3511   }
3512
3513   // Otherwise, not (x+c)*scale, just return what we have.
3514   return true;
3515 }
3516
3517 /// This is a little filter, which returns true if an addressing computation
3518 /// involving I might be folded into a load/store accessing it.
3519 /// This doesn't need to be perfect, but needs to accept at least
3520 /// the set of instructions that MatchOperationAddr can.
3521 static bool MightBeFoldableInst(Instruction *I) {
3522   switch (I->getOpcode()) {
3523   case Instruction::BitCast:
3524   case Instruction::AddrSpaceCast:
3525     // Don't touch identity bitcasts.
3526     if (I->getType() == I->getOperand(0)->getType())
3527       return false;
3528     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3529   case Instruction::PtrToInt:
3530     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3531     return true;
3532   case Instruction::IntToPtr:
3533     // We know the input is intptr_t, so this is foldable.
3534     return true;
3535   case Instruction::Add:
3536     return true;
3537   case Instruction::Mul:
3538   case Instruction::Shl:
3539     // Can only handle X*C and X << C.
3540     return isa<ConstantInt>(I->getOperand(1));
3541   case Instruction::GetElementPtr:
3542     return true;
3543   default:
3544     return false;
3545   }
3546 }
3547
3548 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3549 /// \note \p Val is assumed to be the product of some type promotion.
3550 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3551 /// to be legal, as the non-promoted value would have had the same state.
3552 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3553                                        const DataLayout &DL, Value *Val) {
3554   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3555   if (!PromotedInst)
3556     return false;
3557   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3558   // If the ISDOpcode is undefined, it was undefined before the promotion.
3559   if (!ISDOpcode)
3560     return true;
3561   // Otherwise, check if the promoted instruction is legal or not.
3562   return TLI.isOperationLegalOrCustom(
3563       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
3564 }
3565
3566 /// \brief Hepler class to perform type promotion.
3567 class TypePromotionHelper {
3568   /// \brief Utility function to check whether or not a sign or zero extension
3569   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3570   /// either using the operands of \p Inst or promoting \p Inst.
3571   /// The type of the extension is defined by \p IsSExt.
3572   /// In other words, check if:
3573   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
3574   /// #1 Promotion applies:
3575   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
3576   /// #2 Operand reuses:
3577   /// ext opnd1 to ConsideredExtType.
3578   /// \p PromotedInsts maps the instructions to their type before promotion.
3579   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3580                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
3581
3582   /// \brief Utility function to determine if \p OpIdx should be promoted when
3583   /// promoting \p Inst.
3584   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
3585     return !(isa<SelectInst>(Inst) && OpIdx == 0);
3586   }
3587
3588   /// \brief Utility function to promote the operand of \p Ext when this
3589   /// operand is a promotable trunc or sext or zext.
3590   /// \p PromotedInsts maps the instructions to their type before promotion.
3591   /// \p CreatedInstsCost[out] contains the cost of all instructions
3592   /// created to promote the operand of Ext.
3593   /// Newly added extensions are inserted in \p Exts.
3594   /// Newly added truncates are inserted in \p Truncs.
3595   /// Should never be called directly.
3596   /// \return The promoted value which is used instead of Ext.
3597   static Value *promoteOperandForTruncAndAnyExt(
3598       Instruction *Ext, TypePromotionTransaction &TPT,
3599       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3600       SmallVectorImpl<Instruction *> *Exts,
3601       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
3602
3603   /// \brief Utility function to promote the operand of \p Ext when this
3604   /// operand is promotable and is not a supported trunc or sext.
3605   /// \p PromotedInsts maps the instructions to their type before promotion.
3606   /// \p CreatedInstsCost[out] contains the cost of all the instructions
3607   /// created to promote the operand of Ext.
3608   /// Newly added extensions are inserted in \p Exts.
3609   /// Newly added truncates are inserted in \p Truncs.
3610   /// Should never be called directly.
3611   /// \return The promoted value which is used instead of Ext.
3612   static Value *promoteOperandForOther(Instruction *Ext,
3613                                        TypePromotionTransaction &TPT,
3614                                        InstrToOrigTy &PromotedInsts,
3615                                        unsigned &CreatedInstsCost,
3616                                        SmallVectorImpl<Instruction *> *Exts,
3617                                        SmallVectorImpl<Instruction *> *Truncs,
3618                                        const TargetLowering &TLI, bool IsSExt);
3619
3620   /// \see promoteOperandForOther.
3621   static Value *signExtendOperandForOther(
3622       Instruction *Ext, TypePromotionTransaction &TPT,
3623       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3624       SmallVectorImpl<Instruction *> *Exts,
3625       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3626     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3627                                   Exts, Truncs, TLI, true);
3628   }
3629
3630   /// \see promoteOperandForOther.
3631   static Value *zeroExtendOperandForOther(
3632       Instruction *Ext, TypePromotionTransaction &TPT,
3633       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3634       SmallVectorImpl<Instruction *> *Exts,
3635       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3636     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3637                                   Exts, Truncs, TLI, false);
3638   }
3639
3640 public:
3641   /// Type for the utility function that promotes the operand of Ext.
3642   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3643                            InstrToOrigTy &PromotedInsts,
3644                            unsigned &CreatedInstsCost,
3645                            SmallVectorImpl<Instruction *> *Exts,
3646                            SmallVectorImpl<Instruction *> *Truncs,
3647                            const TargetLowering &TLI);
3648   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3649   /// action to promote the operand of \p Ext instead of using Ext.
3650   /// \return NULL if no promotable action is possible with the current
3651   /// sign extension.
3652   /// \p InsertedInsts keeps track of all the instructions inserted by the
3653   /// other CodeGenPrepare optimizations. This information is important
3654   /// because we do not want to promote these instructions as CodeGenPrepare
3655   /// will reinsert them later. Thus creating an infinite loop: create/remove.
3656   /// \p PromotedInsts maps the instructions to their type before promotion.
3657   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
3658                           const TargetLowering &TLI,
3659                           const InstrToOrigTy &PromotedInsts);
3660 };
3661
3662 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
3663                                         Type *ConsideredExtType,
3664                                         const InstrToOrigTy &PromotedInsts,
3665                                         bool IsSExt) {
3666   // The promotion helper does not know how to deal with vector types yet.
3667   // To be able to fix that, we would need to fix the places where we
3668   // statically extend, e.g., constants and such.
3669   if (Inst->getType()->isVectorTy())
3670     return false;
3671
3672   // We can always get through zext.
3673   if (isa<ZExtInst>(Inst))
3674     return true;
3675
3676   // sext(sext) is ok too.
3677   if (IsSExt && isa<SExtInst>(Inst))
3678     return true;
3679
3680   // We can get through binary operator, if it is legal. In other words, the
3681   // binary operator must have a nuw or nsw flag.
3682   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3683   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3684       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3685        (IsSExt && BinOp->hasNoSignedWrap())))
3686     return true;
3687
3688   // Check if we can do the following simplification.
3689   // ext(trunc(opnd)) --> ext(opnd)
3690   if (!isa<TruncInst>(Inst))
3691     return false;
3692
3693   Value *OpndVal = Inst->getOperand(0);
3694   // Check if we can use this operand in the extension.
3695   // If the type is larger than the result type of the extension, we cannot.
3696   if (!OpndVal->getType()->isIntegerTy() ||
3697       OpndVal->getType()->getIntegerBitWidth() >
3698           ConsideredExtType->getIntegerBitWidth())
3699     return false;
3700
3701   // If the operand of the truncate is not an instruction, we will not have
3702   // any information on the dropped bits.
3703   // (Actually we could for constant but it is not worth the extra logic).
3704   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3705   if (!Opnd)
3706     return false;
3707
3708   // Check if the source of the type is narrow enough.
3709   // I.e., check that trunc just drops extended bits of the same kind of
3710   // the extension.
3711   // #1 get the type of the operand and check the kind of the extended bits.
3712   const Type *OpndType;
3713   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3714   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3715     OpndType = It->second.getPointer();
3716   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3717     OpndType = Opnd->getOperand(0)->getType();
3718   else
3719     return false;
3720
3721   // #2 check that the truncate just drops extended bits.
3722   return Inst->getType()->getIntegerBitWidth() >=
3723          OpndType->getIntegerBitWidth();
3724 }
3725
3726 TypePromotionHelper::Action TypePromotionHelper::getAction(
3727     Instruction *Ext, const SetOfInstrs &InsertedInsts,
3728     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
3729   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3730          "Unexpected instruction type");
3731   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3732   Type *ExtTy = Ext->getType();
3733   bool IsSExt = isa<SExtInst>(Ext);
3734   // If the operand of the extension is not an instruction, we cannot
3735   // get through.
3736   // If it, check we can get through.
3737   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3738     return nullptr;
3739
3740   // Do not promote if the operand has been added by codegenprepare.
3741   // Otherwise, it means we are undoing an optimization that is likely to be
3742   // redone, thus causing potential infinite loop.
3743   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3744     return nullptr;
3745
3746   // SExt or Trunc instructions.
3747   // Return the related handler.
3748   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3749       isa<ZExtInst>(ExtOpnd))
3750     return promoteOperandForTruncAndAnyExt;
3751
3752   // Regular instruction.
3753   // Abort early if we will have to insert non-free instructions.
3754   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
3755     return nullptr;
3756   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3757 }
3758
3759 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3760     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3761     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3762     SmallVectorImpl<Instruction *> *Exts,
3763     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3764   // By construction, the operand of SExt is an instruction. Otherwise we cannot
3765   // get through it and this method should not be called.
3766   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
3767   Value *ExtVal = SExt;
3768   bool HasMergedNonFreeExt = false;
3769   if (isa<ZExtInst>(SExtOpnd)) {
3770     // Replace s|zext(zext(opnd))
3771     // => zext(opnd).
3772     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
3773     Value *ZExt =
3774         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3775     TPT.replaceAllUsesWith(SExt, ZExt);
3776     TPT.eraseInstruction(SExt);
3777     ExtVal = ZExt;
3778   } else {
3779     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3780     // => z|sext(opnd).
3781     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3782   }
3783   CreatedInstsCost = 0;
3784
3785   // Remove dead code.
3786   if (SExtOpnd->use_empty())
3787     TPT.eraseInstruction(SExtOpnd);
3788
3789   // Check if the extension is still needed.
3790   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
3791   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3792     if (ExtInst) {
3793       if (Exts)
3794         Exts->push_back(ExtInst);
3795       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3796     }
3797     return ExtVal;
3798   }
3799
3800   // At this point we have: ext ty opnd to ty.
3801   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3802   Value *NextVal = ExtInst->getOperand(0);
3803   TPT.eraseInstruction(ExtInst, NextVal);
3804   return NextVal;
3805 }
3806
3807 Value *TypePromotionHelper::promoteOperandForOther(
3808     Instruction *Ext, TypePromotionTransaction &TPT,
3809     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3810     SmallVectorImpl<Instruction *> *Exts,
3811     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3812     bool IsSExt) {
3813   // By construction, the operand of Ext is an instruction. Otherwise we cannot
3814   // get through it and this method should not be called.
3815   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3816   CreatedInstsCost = 0;
3817   if (!ExtOpnd->hasOneUse()) {
3818     // ExtOpnd will be promoted.
3819     // All its uses, but Ext, will need to use a truncated value of the
3820     // promoted version.
3821     // Create the truncate now.
3822     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
3823     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3824       ITrunc->removeFromParent();
3825       // Insert it just after the definition.
3826       ITrunc->insertAfter(ExtOpnd);
3827       if (Truncs)
3828         Truncs->push_back(ITrunc);
3829     }
3830
3831     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3832     // Restore the operand of Ext (which has been replaced by the previous call
3833     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
3834     TPT.setOperand(Ext, 0, ExtOpnd);
3835   }
3836
3837   // Get through the Instruction:
3838   // 1. Update its type.
3839   // 2. Replace the uses of Ext by Inst.
3840   // 3. Extend each operand that needs to be extended.
3841
3842   // Remember the original type of the instruction before promotion.
3843   // This is useful to know that the high bits are sign extended bits.
3844   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3845       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
3846   // Step #1.
3847   TPT.mutateType(ExtOpnd, Ext->getType());
3848   // Step #2.
3849   TPT.replaceAllUsesWith(Ext, ExtOpnd);
3850   // Step #3.
3851   Instruction *ExtForOpnd = Ext;
3852
3853   DEBUG(dbgs() << "Propagate Ext to operands\n");
3854   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
3855        ++OpIdx) {
3856     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3857     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3858         !shouldExtOperand(ExtOpnd, OpIdx)) {
3859       DEBUG(dbgs() << "No need to propagate\n");
3860       continue;
3861     }
3862     // Check if we can statically extend the operand.
3863     Value *Opnd = ExtOpnd->getOperand(OpIdx);
3864     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3865       DEBUG(dbgs() << "Statically extend\n");
3866       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3867       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3868                             : Cst->getValue().zext(BitWidth);
3869       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
3870       continue;
3871     }
3872     // UndefValue are typed, so we have to statically sign extend them.
3873     if (isa<UndefValue>(Opnd)) {
3874       DEBUG(dbgs() << "Statically extend\n");
3875       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
3876       continue;
3877     }
3878
3879     // Otherwise we have to explicity sign extend the operand.
3880     // Check if Ext was reused to extend an operand.
3881     if (!ExtForOpnd) {
3882       // If yes, create a new one.
3883       DEBUG(dbgs() << "More operands to ext\n");
3884       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3885         : TPT.createZExt(Ext, Opnd, Ext->getType());
3886       if (!isa<Instruction>(ValForExtOpnd)) {
3887         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3888         continue;
3889       }
3890       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3891     }
3892     if (Exts)
3893       Exts->push_back(ExtForOpnd);
3894     TPT.setOperand(ExtForOpnd, 0, Opnd);
3895
3896     // Move the sign extension before the insertion point.
3897     TPT.moveBefore(ExtForOpnd, ExtOpnd);
3898     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3899     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
3900     // If more sext are required, new instructions will have to be created.
3901     ExtForOpnd = nullptr;
3902   }
3903   if (ExtForOpnd == Ext) {
3904     DEBUG(dbgs() << "Extension is useless now\n");
3905     TPT.eraseInstruction(Ext);
3906   }
3907   return ExtOpnd;
3908 }
3909
3910 /// Check whether or not promoting an instruction to a wider type is profitable.
3911 /// \p NewCost gives the cost of extension instructions created by the
3912 /// promotion.
3913 /// \p OldCost gives the cost of extension instructions before the promotion
3914 /// plus the number of instructions that have been
3915 /// matched in the addressing mode the promotion.
3916 /// \p PromotedOperand is the value that has been promoted.
3917 /// \return True if the promotion is profitable, false otherwise.
3918 bool AddressingModeMatcher::isPromotionProfitable(
3919     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3920   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3921   // The cost of the new extensions is greater than the cost of the
3922   // old extension plus what we folded.
3923   // This is not profitable.
3924   if (NewCost > OldCost)
3925     return false;
3926   if (NewCost < OldCost)
3927     return true;
3928   // The promotion is neutral but it may help folding the sign extension in
3929   // loads for instance.
3930   // Check that we did not create an illegal instruction.
3931   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3932 }
3933
3934 /// Given an instruction or constant expr, see if we can fold the operation
3935 /// into the addressing mode. If so, update the addressing mode and return
3936 /// true, otherwise return false without modifying AddrMode.
3937 /// If \p MovedAway is not NULL, it contains the information of whether or
3938 /// not AddrInst has to be folded into the addressing mode on success.
3939 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3940 /// because it has been moved away.
3941 /// Thus AddrInst must not be added in the matched instructions.
3942 /// This state can happen when AddrInst is a sext, since it may be moved away.
3943 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
3944 /// not be referenced anymore.
3945 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
3946                                                unsigned Depth,
3947                                                bool *MovedAway) {
3948   // Avoid exponential behavior on extremely deep expression trees.
3949   if (Depth >= 5) return false;
3950
3951   // By default, all matched instructions stay in place.
3952   if (MovedAway)
3953     *MovedAway = false;
3954
3955   switch (Opcode) {
3956   case Instruction::PtrToInt:
3957     // PtrToInt is always a noop, as we know that the int type is pointer sized.
3958     return matchAddr(AddrInst->getOperand(0), Depth);
3959   case Instruction::IntToPtr: {
3960     auto AS = AddrInst->getType()->getPointerAddressSpace();
3961     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
3962     // This inttoptr is a no-op if the integer type is pointer sized.
3963     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
3964       return matchAddr(AddrInst->getOperand(0), Depth);
3965     return false;
3966   }
3967   case Instruction::BitCast:
3968     // BitCast is always a noop, and we can handle it as long as it is
3969     // int->int or pointer->pointer (we don't want int<->fp or something).
3970     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3971          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3972         // Don't touch identity bitcasts.  These were probably put here by LSR,
3973         // and we don't want to mess around with them.  Assume it knows what it
3974         // is doing.
3975         AddrInst->getOperand(0)->getType() != AddrInst->getType())
3976       return matchAddr(AddrInst->getOperand(0), Depth);
3977     return false;
3978   case Instruction::AddrSpaceCast: {
3979     unsigned SrcAS
3980       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3981     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3982     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3983       return matchAddr(AddrInst->getOperand(0), Depth);
3984     return false;
3985   }
3986   case Instruction::Add: {
3987     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
3988     ExtAddrMode BackupAddrMode = AddrMode;
3989     unsigned OldSize = AddrModeInsts.size();
3990     // Start a transaction at this point.
3991     // The LHS may match but not the RHS.
3992     // Therefore, we need a higher level restoration point to undo partially
3993     // matched operation.
3994     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3995         TPT.getRestorationPoint();
3996
3997     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3998         matchAddr(AddrInst->getOperand(0), Depth+1))
3999       return true;
4000
4001     // Restore the old addr mode info.
4002     AddrMode = BackupAddrMode;
4003     AddrModeInsts.resize(OldSize);
4004     TPT.rollback(LastKnownGood);
4005
4006     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
4007     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4008         matchAddr(AddrInst->getOperand(1), Depth+1))
4009       return true;
4010
4011     // Otherwise we definitely can't merge the ADD in.
4012     AddrMode = BackupAddrMode;
4013     AddrModeInsts.resize(OldSize);
4014     TPT.rollback(LastKnownGood);
4015     break;
4016   }
4017   //case Instruction::Or:
4018   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4019   //break;
4020   case Instruction::Mul:
4021   case Instruction::Shl: {
4022     // Can only handle X*C and X << C.
4023     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4024     if (!RHS)
4025       return false;
4026     int64_t Scale = RHS->getSExtValue();
4027     if (Opcode == Instruction::Shl)
4028       Scale = 1LL << Scale;
4029
4030     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4031   }
4032   case Instruction::GetElementPtr: {
4033     // Scan the GEP.  We check it if it contains constant offsets and at most
4034     // one variable offset.
4035     int VariableOperand = -1;
4036     unsigned VariableScale = 0;
4037
4038     int64_t ConstantOffset = 0;
4039     gep_type_iterator GTI = gep_type_begin(AddrInst);
4040     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4041       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
4042         const StructLayout *SL = DL.getStructLayout(STy);
4043         unsigned Idx =
4044           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4045         ConstantOffset += SL->getElementOffset(Idx);
4046       } else {
4047         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
4048         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4049           ConstantOffset += CI->getSExtValue()*TypeSize;
4050         } else if (TypeSize) {  // Scales of zero don't do anything.
4051           // We only allow one variable index at the moment.
4052           if (VariableOperand != -1)
4053             return false;
4054
4055           // Remember the variable index.
4056           VariableOperand = i;
4057           VariableScale = TypeSize;
4058         }
4059       }
4060     }
4061
4062     // A common case is for the GEP to only do a constant offset.  In this case,
4063     // just add it to the disp field and check validity.
4064     if (VariableOperand == -1) {
4065       AddrMode.BaseOffs += ConstantOffset;
4066       if (ConstantOffset == 0 ||
4067           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4068         // Check to see if we can fold the base pointer in too.
4069         if (matchAddr(AddrInst->getOperand(0), Depth+1))
4070           return true;
4071       }
4072       AddrMode.BaseOffs -= ConstantOffset;
4073       return false;
4074     }
4075
4076     // Save the valid addressing mode in case we can't match.
4077     ExtAddrMode BackupAddrMode = AddrMode;
4078     unsigned OldSize = AddrModeInsts.size();
4079
4080     // See if the scale and offset amount is valid for this target.
4081     AddrMode.BaseOffs += ConstantOffset;
4082
4083     // Match the base operand of the GEP.
4084     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4085       // If it couldn't be matched, just stuff the value in a register.
4086       if (AddrMode.HasBaseReg) {
4087         AddrMode = BackupAddrMode;
4088         AddrModeInsts.resize(OldSize);
4089         return false;
4090       }
4091       AddrMode.HasBaseReg = true;
4092       AddrMode.BaseReg = AddrInst->getOperand(0);
4093     }
4094
4095     // Match the remaining variable portion of the GEP.
4096     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4097                           Depth)) {
4098       // If it couldn't be matched, try stuffing the base into a register
4099       // instead of matching it, and retrying the match of the scale.
4100       AddrMode = BackupAddrMode;
4101       AddrModeInsts.resize(OldSize);
4102       if (AddrMode.HasBaseReg)
4103         return false;
4104       AddrMode.HasBaseReg = true;
4105       AddrMode.BaseReg = AddrInst->getOperand(0);
4106       AddrMode.BaseOffs += ConstantOffset;
4107       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4108                             VariableScale, Depth)) {
4109         // If even that didn't work, bail.
4110         AddrMode = BackupAddrMode;
4111         AddrModeInsts.resize(OldSize);
4112         return false;
4113       }
4114     }
4115
4116     return true;
4117   }
4118   case Instruction::SExt:
4119   case Instruction::ZExt: {
4120     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4121     if (!Ext)
4122       return false;
4123
4124     // Try to move this ext out of the way of the addressing mode.
4125     // Ask for a method for doing so.
4126     TypePromotionHelper::Action TPH =
4127         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4128     if (!TPH)
4129       return false;
4130
4131     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4132         TPT.getRestorationPoint();
4133     unsigned CreatedInstsCost = 0;
4134     unsigned ExtCost = !TLI.isExtFree(Ext);
4135     Value *PromotedOperand =
4136         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4137     // SExt has been moved away.
4138     // Thus either it will be rematched later in the recursive calls or it is
4139     // gone. Anyway, we must not fold it into the addressing mode at this point.
4140     // E.g.,
4141     // op = add opnd, 1
4142     // idx = ext op
4143     // addr = gep base, idx
4144     // is now:
4145     // promotedOpnd = ext opnd            <- no match here
4146     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
4147     // addr = gep base, op                <- match
4148     if (MovedAway)
4149       *MovedAway = true;
4150
4151     assert(PromotedOperand &&
4152            "TypePromotionHelper should have filtered out those cases");
4153
4154     ExtAddrMode BackupAddrMode = AddrMode;
4155     unsigned OldSize = AddrModeInsts.size();
4156
4157     if (!matchAddr(PromotedOperand, Depth) ||
4158         // The total of the new cost is equal to the cost of the created
4159         // instructions.
4160         // The total of the old cost is equal to the cost of the extension plus
4161         // what we have saved in the addressing mode.
4162         !isPromotionProfitable(CreatedInstsCost,
4163                                ExtCost + (AddrModeInsts.size() - OldSize),
4164                                PromotedOperand)) {
4165       AddrMode = BackupAddrMode;
4166       AddrModeInsts.resize(OldSize);
4167       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4168       TPT.rollback(LastKnownGood);
4169       return false;
4170     }
4171     return true;
4172   }
4173   }
4174   return false;
4175 }
4176
4177 /// If we can, try to add the value of 'Addr' into the current addressing mode.
4178 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4179 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
4180 /// for the target.
4181 ///
4182 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4183   // Start a transaction at this point that we will rollback if the matching
4184   // fails.
4185   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4186       TPT.getRestorationPoint();
4187   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4188     // Fold in immediates if legal for the target.
4189     AddrMode.BaseOffs += CI->getSExtValue();
4190     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4191       return true;
4192     AddrMode.BaseOffs -= CI->getSExtValue();
4193   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4194     // If this is a global variable, try to fold it into the addressing mode.
4195     if (!AddrMode.BaseGV) {
4196       AddrMode.BaseGV = GV;
4197       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4198         return true;
4199       AddrMode.BaseGV = nullptr;
4200     }
4201   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4202     ExtAddrMode BackupAddrMode = AddrMode;
4203     unsigned OldSize = AddrModeInsts.size();
4204
4205     // Check to see if it is possible to fold this operation.
4206     bool MovedAway = false;
4207     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4208       // This instruction may have been moved away. If so, there is nothing
4209       // to check here.
4210       if (MovedAway)
4211         return true;
4212       // Okay, it's possible to fold this.  Check to see if it is actually
4213       // *profitable* to do so.  We use a simple cost model to avoid increasing
4214       // register pressure too much.
4215       if (I->hasOneUse() ||
4216           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4217         AddrModeInsts.push_back(I);
4218         return true;
4219       }
4220
4221       // It isn't profitable to do this, roll back.
4222       //cerr << "NOT FOLDING: " << *I;
4223       AddrMode = BackupAddrMode;
4224       AddrModeInsts.resize(OldSize);
4225       TPT.rollback(LastKnownGood);
4226     }
4227   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4228     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4229       return true;
4230     TPT.rollback(LastKnownGood);
4231   } else if (isa<ConstantPointerNull>(Addr)) {
4232     // Null pointer gets folded without affecting the addressing mode.
4233     return true;
4234   }
4235
4236   // Worse case, the target should support [reg] addressing modes. :)
4237   if (!AddrMode.HasBaseReg) {
4238     AddrMode.HasBaseReg = true;
4239     AddrMode.BaseReg = Addr;
4240     // Still check for legality in case the target supports [imm] but not [i+r].
4241     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4242       return true;
4243     AddrMode.HasBaseReg = false;
4244     AddrMode.BaseReg = nullptr;
4245   }
4246
4247   // If the base register is already taken, see if we can do [r+r].
4248   if (AddrMode.Scale == 0) {
4249     AddrMode.Scale = 1;
4250     AddrMode.ScaledReg = Addr;
4251     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4252       return true;
4253     AddrMode.Scale = 0;
4254     AddrMode.ScaledReg = nullptr;
4255   }
4256   // Couldn't match.
4257   TPT.rollback(LastKnownGood);
4258   return false;
4259 }
4260
4261 /// Check to see if all uses of OpVal by the specified inline asm call are due
4262 /// to memory operands. If so, return true, otherwise return false.
4263 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4264                                     const TargetMachine &TM) {
4265   const Function *F = CI->getParent()->getParent();
4266   const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
4267   const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
4268   TargetLowering::AsmOperandInfoVector TargetConstraints =
4269       TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
4270                             ImmutableCallSite(CI));
4271   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4272     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4273
4274     // Compute the constraint code and ConstraintType to use.
4275     TLI->ComputeConstraintToUse(OpInfo, SDValue());
4276
4277     // If this asm operand is our Value*, and if it isn't an indirect memory
4278     // operand, we can't fold it!
4279     if (OpInfo.CallOperandVal == OpVal &&
4280         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4281          !OpInfo.isIndirect))
4282       return false;
4283   }
4284
4285   return true;
4286 }
4287
4288 /// Recursively walk all the uses of I until we find a memory use.
4289 /// If we find an obviously non-foldable instruction, return true.
4290 /// Add the ultimately found memory instructions to MemoryUses.
4291 static bool FindAllMemoryUses(
4292     Instruction *I,
4293     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4294     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
4295   // If we already considered this instruction, we're done.
4296   if (!ConsideredInsts.insert(I).second)
4297     return false;
4298
4299   // If this is an obviously unfoldable instruction, bail out.
4300   if (!MightBeFoldableInst(I))
4301     return true;
4302
4303   // Loop over all the uses, recursively processing them.
4304   for (Use &U : I->uses()) {
4305     Instruction *UserI = cast<Instruction>(U.getUser());
4306
4307     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4308       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4309       continue;
4310     }
4311
4312     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4313       unsigned opNo = U.getOperandNo();
4314       if (opNo == 0) return true; // Storing addr, not into addr.
4315       MemoryUses.push_back(std::make_pair(SI, opNo));
4316       continue;
4317     }
4318
4319     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4320       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4321       if (!IA) return true;
4322
4323       // If this is a memory operand, we're cool, otherwise bail out.
4324       if (!IsOperandAMemoryOperand(CI, IA, I, TM))
4325         return true;
4326       continue;
4327     }
4328
4329     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
4330       return true;
4331   }
4332
4333   return false;
4334 }
4335
4336 /// Return true if Val is already known to be live at the use site that we're
4337 /// folding it into. If so, there is no cost to include it in the addressing
4338 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4339 /// instruction already.
4340 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4341                                                    Value *KnownLive2) {
4342   // If Val is either of the known-live values, we know it is live!
4343   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4344     return true;
4345
4346   // All values other than instructions and arguments (e.g. constants) are live.
4347   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4348
4349   // If Val is a constant sized alloca in the entry block, it is live, this is
4350   // true because it is just a reference to the stack/frame pointer, which is
4351   // live for the whole function.
4352   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4353     if (AI->isStaticAlloca())
4354       return true;
4355
4356   // Check to see if this value is already used in the memory instruction's
4357   // block.  If so, it's already live into the block at the very least, so we
4358   // can reasonably fold it.
4359   return Val->isUsedInBasicBlock(MemoryInst->getParent());
4360 }
4361
4362 /// It is possible for the addressing mode of the machine to fold the specified
4363 /// instruction into a load or store that ultimately uses it.
4364 /// However, the specified instruction has multiple uses.
4365 /// Given this, it may actually increase register pressure to fold it
4366 /// into the load. For example, consider this code:
4367 ///
4368 ///     X = ...
4369 ///     Y = X+1
4370 ///     use(Y)   -> nonload/store
4371 ///     Z = Y+1
4372 ///     load Z
4373 ///
4374 /// In this case, Y has multiple uses, and can be folded into the load of Z
4375 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
4376 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
4377 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
4378 /// number of computations either.
4379 ///
4380 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
4381 /// X was live across 'load Z' for other reasons, we actually *would* want to
4382 /// fold the addressing mode in the Z case.  This would make Y die earlier.
4383 bool AddressingModeMatcher::
4384 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4385                                      ExtAddrMode &AMAfter) {
4386   if (IgnoreProfitability) return true;
4387
4388   // AMBefore is the addressing mode before this instruction was folded into it,
4389   // and AMAfter is the addressing mode after the instruction was folded.  Get
4390   // the set of registers referenced by AMAfter and subtract out those
4391   // referenced by AMBefore: this is the set of values which folding in this
4392   // address extends the lifetime of.
4393   //
4394   // Note that there are only two potential values being referenced here,
4395   // BaseReg and ScaleReg (global addresses are always available, as are any
4396   // folded immediates).
4397   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4398
4399   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4400   // lifetime wasn't extended by adding this instruction.
4401   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4402     BaseReg = nullptr;
4403   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4404     ScaledReg = nullptr;
4405
4406   // If folding this instruction (and it's subexprs) didn't extend any live
4407   // ranges, we're ok with it.
4408   if (!BaseReg && !ScaledReg)
4409     return true;
4410
4411   // If all uses of this instruction are ultimately load/store/inlineasm's,
4412   // check to see if their addressing modes will include this instruction.  If
4413   // so, we can fold it into all uses, so it doesn't matter if it has multiple
4414   // uses.
4415   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4416   SmallPtrSet<Instruction*, 16> ConsideredInsts;
4417   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
4418     return false;  // Has a non-memory, non-foldable use!
4419
4420   // Now that we know that all uses of this instruction are part of a chain of
4421   // computation involving only operations that could theoretically be folded
4422   // into a memory use, loop over each of these uses and see if they could
4423   // *actually* fold the instruction.
4424   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4425   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4426     Instruction *User = MemoryUses[i].first;
4427     unsigned OpNo = MemoryUses[i].second;
4428
4429     // Get the access type of this use.  If the use isn't a pointer, we don't
4430     // know what it accesses.
4431     Value *Address = User->getOperand(OpNo);
4432     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4433     if (!AddrTy)
4434       return false;
4435     Type *AddressAccessTy = AddrTy->getElementType();
4436     unsigned AS = AddrTy->getAddressSpace();
4437
4438     // Do a match against the root of this address, ignoring profitability. This
4439     // will tell us if the addressing mode for the memory operation will
4440     // *actually* cover the shared instruction.
4441     ExtAddrMode Result;
4442     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4443         TPT.getRestorationPoint();
4444     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
4445                                   MemoryInst, Result, InsertedInsts,
4446                                   PromotedInsts, TPT);
4447     Matcher.IgnoreProfitability = true;
4448     bool Success = Matcher.matchAddr(Address, 0);
4449     (void)Success; assert(Success && "Couldn't select *anything*?");
4450
4451     // The match was to check the profitability, the changes made are not
4452     // part of the original matcher. Therefore, they should be dropped
4453     // otherwise the original matcher will not present the right state.
4454     TPT.rollback(LastKnownGood);
4455
4456     // If the match didn't cover I, then it won't be shared by it.
4457     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
4458                   I) == MatchedAddrModeInsts.end())
4459       return false;
4460
4461     MatchedAddrModeInsts.clear();
4462   }
4463
4464   return true;
4465 }
4466
4467 } // end anonymous namespace
4468
4469 /// Return true if the specified values are defined in a
4470 /// different basic block than BB.
4471 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4472   if (Instruction *I = dyn_cast<Instruction>(V))
4473     return I->getParent() != BB;
4474   return false;
4475 }
4476
4477 /// Load and Store Instructions often have addressing modes that can do
4478 /// significant amounts of computation. As such, instruction selection will try
4479 /// to get the load or store to do as much computation as possible for the
4480 /// program. The problem is that isel can only see within a single block. As
4481 /// such, we sink as much legal addressing mode work into the block as possible.
4482 ///
4483 /// This method is used to optimize both load/store and inline asms with memory
4484 /// operands.
4485 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
4486                                         Type *AccessTy, unsigned AddrSpace) {
4487   Value *Repl = Addr;
4488
4489   // Try to collapse single-value PHI nodes.  This is necessary to undo
4490   // unprofitable PRE transformations.
4491   SmallVector<Value*, 8> worklist;
4492   SmallPtrSet<Value*, 16> Visited;
4493   worklist.push_back(Addr);
4494
4495   // Use a worklist to iteratively look through PHI nodes, and ensure that
4496   // the addressing mode obtained from the non-PHI roots of the graph
4497   // are equivalent.
4498   Value *Consensus = nullptr;
4499   unsigned NumUsesConsensus = 0;
4500   bool IsNumUsesConsensusValid = false;
4501   SmallVector<Instruction*, 16> AddrModeInsts;
4502   ExtAddrMode AddrMode;
4503   TypePromotionTransaction TPT;
4504   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4505       TPT.getRestorationPoint();
4506   while (!worklist.empty()) {
4507     Value *V = worklist.back();
4508     worklist.pop_back();
4509
4510     // Break use-def graph loops.
4511     if (!Visited.insert(V).second) {
4512       Consensus = nullptr;
4513       break;
4514     }
4515
4516     // For a PHI node, push all of its incoming values.
4517     if (PHINode *P = dyn_cast<PHINode>(V)) {
4518       for (Value *IncValue : P->incoming_values())
4519         worklist.push_back(IncValue);
4520       continue;
4521     }
4522
4523     // For non-PHIs, determine the addressing mode being computed.
4524     SmallVector<Instruction*, 16> NewAddrModeInsts;
4525     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4526       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
4527       InsertedInsts, PromotedInsts, TPT);
4528
4529     // This check is broken into two cases with very similar code to avoid using
4530     // getNumUses() as much as possible. Some values have a lot of uses, so
4531     // calling getNumUses() unconditionally caused a significant compile-time
4532     // regression.
4533     if (!Consensus) {
4534       Consensus = V;
4535       AddrMode = NewAddrMode;
4536       AddrModeInsts = NewAddrModeInsts;
4537       continue;
4538     } else if (NewAddrMode == AddrMode) {
4539       if (!IsNumUsesConsensusValid) {
4540         NumUsesConsensus = Consensus->getNumUses();
4541         IsNumUsesConsensusValid = true;
4542       }
4543
4544       // Ensure that the obtained addressing mode is equivalent to that obtained
4545       // for all other roots of the PHI traversal.  Also, when choosing one
4546       // such root as representative, select the one with the most uses in order
4547       // to keep the cost modeling heuristics in AddressingModeMatcher
4548       // applicable.
4549       unsigned NumUses = V->getNumUses();
4550       if (NumUses > NumUsesConsensus) {
4551         Consensus = V;
4552         NumUsesConsensus = NumUses;
4553         AddrModeInsts = NewAddrModeInsts;
4554       }
4555       continue;
4556     }
4557
4558     Consensus = nullptr;
4559     break;
4560   }
4561
4562   // If the addressing mode couldn't be determined, or if multiple different
4563   // ones were determined, bail out now.
4564   if (!Consensus) {
4565     TPT.rollback(LastKnownGood);
4566     return false;
4567   }
4568   TPT.commit();
4569
4570   // Check to see if any of the instructions supersumed by this addr mode are
4571   // non-local to I's BB.
4572   bool AnyNonLocal = false;
4573   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
4574     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
4575       AnyNonLocal = true;
4576       break;
4577     }
4578   }
4579
4580   // If all the instructions matched are already in this BB, don't do anything.
4581   if (!AnyNonLocal) {
4582     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
4583     return false;
4584   }
4585
4586   // Insert this computation right after this user.  Since our caller is
4587   // scanning from the top of the BB to the bottom, reuse of the expr are
4588   // guaranteed to happen later.
4589   IRBuilder<> Builder(MemoryInst);
4590
4591   // Now that we determined the addressing expression we want to use and know
4592   // that we have to sink it into this block.  Check to see if we have already
4593   // done this for some other load/store instr in this block.  If so, reuse the
4594   // computation.
4595   Value *&SunkAddr = SunkAddrs[Addr];
4596   if (SunkAddr) {
4597     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
4598                  << *MemoryInst << "\n");
4599     if (SunkAddr->getType() != Addr->getType())
4600       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4601   } else if (AddrSinkUsingGEPs ||
4602              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
4603               TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
4604                   ->useAA())) {
4605     // By default, we use the GEP-based method when AA is used later. This
4606     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4607     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4608                  << *MemoryInst << "\n");
4609     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4610     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
4611
4612     // First, find the pointer.
4613     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4614       ResultPtr = AddrMode.BaseReg;
4615       AddrMode.BaseReg = nullptr;
4616     }
4617
4618     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4619       // We can't add more than one pointer together, nor can we scale a
4620       // pointer (both of which seem meaningless).
4621       if (ResultPtr || AddrMode.Scale != 1)
4622         return false;
4623
4624       ResultPtr = AddrMode.ScaledReg;
4625       AddrMode.Scale = 0;
4626     }
4627
4628     if (AddrMode.BaseGV) {
4629       if (ResultPtr)
4630         return false;
4631
4632       ResultPtr = AddrMode.BaseGV;
4633     }
4634
4635     // If the real base value actually came from an inttoptr, then the matcher
4636     // will look through it and provide only the integer value. In that case,
4637     // use it here.
4638     if (!ResultPtr && AddrMode.BaseReg) {
4639       ResultPtr =
4640         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
4641       AddrMode.BaseReg = nullptr;
4642     } else if (!ResultPtr && AddrMode.Scale == 1) {
4643       ResultPtr =
4644         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4645       AddrMode.Scale = 0;
4646     }
4647
4648     if (!ResultPtr &&
4649         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4650       SunkAddr = Constant::getNullValue(Addr->getType());
4651     } else if (!ResultPtr) {
4652       return false;
4653     } else {
4654       Type *I8PtrTy =
4655           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4656       Type *I8Ty = Builder.getInt8Ty();
4657
4658       // Start with the base register. Do this first so that subsequent address
4659       // matching finds it last, which will prevent it from trying to match it
4660       // as the scaled value in case it happens to be a mul. That would be
4661       // problematic if we've sunk a different mul for the scale, because then
4662       // we'd end up sinking both muls.
4663       if (AddrMode.BaseReg) {
4664         Value *V = AddrMode.BaseReg;
4665         if (V->getType() != IntPtrTy)
4666           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4667
4668         ResultIndex = V;
4669       }
4670
4671       // Add the scale value.
4672       if (AddrMode.Scale) {
4673         Value *V = AddrMode.ScaledReg;
4674         if (V->getType() == IntPtrTy) {
4675           // done.
4676         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4677                    cast<IntegerType>(V->getType())->getBitWidth()) {
4678           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4679         } else {
4680           // It is only safe to sign extend the BaseReg if we know that the math
4681           // required to create it did not overflow before we extend it. Since
4682           // the original IR value was tossed in favor of a constant back when
4683           // the AddrMode was created we need to bail out gracefully if widths
4684           // do not match instead of extending it.
4685           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4686           if (I && (ResultIndex != AddrMode.BaseReg))
4687             I->eraseFromParent();
4688           return false;
4689         }
4690
4691         if (AddrMode.Scale != 1)
4692           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4693                                 "sunkaddr");
4694         if (ResultIndex)
4695           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4696         else
4697           ResultIndex = V;
4698       }
4699
4700       // Add in the Base Offset if present.
4701       if (AddrMode.BaseOffs) {
4702         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4703         if (ResultIndex) {
4704           // We need to add this separately from the scale above to help with
4705           // SDAG consecutive load/store merging.
4706           if (ResultPtr->getType() != I8PtrTy)
4707             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4708           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4709         }
4710
4711         ResultIndex = V;
4712       }
4713
4714       if (!ResultIndex) {
4715         SunkAddr = ResultPtr;
4716       } else {
4717         if (ResultPtr->getType() != I8PtrTy)
4718           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
4719         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
4720       }
4721
4722       if (SunkAddr->getType() != Addr->getType())
4723         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4724     }
4725   } else {
4726     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
4727                  << *MemoryInst << "\n");
4728     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
4729     Value *Result = nullptr;
4730
4731     // Start with the base register. Do this first so that subsequent address
4732     // matching finds it last, which will prevent it from trying to match it
4733     // as the scaled value in case it happens to be a mul. That would be
4734     // problematic if we've sunk a different mul for the scale, because then
4735     // we'd end up sinking both muls.
4736     if (AddrMode.BaseReg) {
4737       Value *V = AddrMode.BaseReg;
4738       if (V->getType()->isPointerTy())
4739         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4740       if (V->getType() != IntPtrTy)
4741         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4742       Result = V;
4743     }
4744
4745     // Add the scale value.
4746     if (AddrMode.Scale) {
4747       Value *V = AddrMode.ScaledReg;
4748       if (V->getType() == IntPtrTy) {
4749         // done.
4750       } else if (V->getType()->isPointerTy()) {
4751         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
4752       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4753                  cast<IntegerType>(V->getType())->getBitWidth()) {
4754         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4755       } else {
4756         // It is only safe to sign extend the BaseReg if we know that the math
4757         // required to create it did not overflow before we extend it. Since
4758         // the original IR value was tossed in favor of a constant back when
4759         // the AddrMode was created we need to bail out gracefully if widths
4760         // do not match instead of extending it.
4761         Instruction *I = dyn_cast_or_null<Instruction>(Result);
4762         if (I && (Result != AddrMode.BaseReg))
4763           I->eraseFromParent();
4764         return false;
4765       }
4766       if (AddrMode.Scale != 1)
4767         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4768                               "sunkaddr");
4769       if (Result)
4770         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4771       else
4772         Result = V;
4773     }
4774
4775     // Add in the BaseGV if present.
4776     if (AddrMode.BaseGV) {
4777       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
4778       if (Result)
4779         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4780       else
4781         Result = V;
4782     }
4783
4784     // Add in the Base Offset if present.
4785     if (AddrMode.BaseOffs) {
4786       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4787       if (Result)
4788         Result = Builder.CreateAdd(Result, V, "sunkaddr");
4789       else
4790         Result = V;
4791     }
4792
4793     if (!Result)
4794       SunkAddr = Constant::getNullValue(Addr->getType());
4795     else
4796       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
4797   }
4798
4799   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
4800
4801   // If we have no uses, recursively delete the value and all dead instructions
4802   // using it.
4803   if (Repl->use_empty()) {
4804     // This can cause recursive deletion, which can invalidate our iterator.
4805     // Use a WeakVH to hold onto it in case this happens.
4806     WeakVH IterHandle(&*CurInstIterator);
4807     BasicBlock *BB = CurInstIterator->getParent();
4808
4809     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
4810
4811     if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
4812       // If the iterator instruction was recursively deleted, start over at the
4813       // start of the block.
4814       CurInstIterator = BB->begin();
4815       SunkAddrs.clear();
4816     }
4817   }
4818   ++NumMemoryInsts;
4819   return true;
4820 }
4821
4822 /// If there are any memory operands, use OptimizeMemoryInst to sink their
4823 /// address computing into the block when possible / profitable.
4824 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
4825   bool MadeChange = false;
4826
4827   const TargetRegisterInfo *TRI =
4828       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
4829   TargetLowering::AsmOperandInfoVector TargetConstraints =
4830       TLI->ParseConstraints(*DL, TRI, CS);
4831   unsigned ArgNo = 0;
4832   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4833     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4834
4835     // Compute the constraint code and ConstraintType to use.
4836     TLI->ComputeConstraintToUse(OpInfo, SDValue());
4837
4838     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4839         OpInfo.isIndirect) {
4840       Value *OpVal = CS->getArgOperand(ArgNo++);
4841       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
4842     } else if (OpInfo.Type == InlineAsm::isInput)
4843       ArgNo++;
4844   }
4845
4846   return MadeChange;
4847 }
4848
4849 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4850 /// sign extensions.
4851 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4852   assert(!Inst->use_empty() && "Input must have at least one use");
4853   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4854   bool IsSExt = isa<SExtInst>(FirstUser);
4855   Type *ExtTy = FirstUser->getType();
4856   for (const User *U : Inst->users()) {
4857     const Instruction *UI = cast<Instruction>(U);
4858     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4859       return false;
4860     Type *CurTy = UI->getType();
4861     // Same input and output types: Same instruction after CSE.
4862     if (CurTy == ExtTy)
4863       continue;
4864
4865     // If IsSExt is true, we are in this situation:
4866     // a = Inst
4867     // b = sext ty1 a to ty2
4868     // c = sext ty1 a to ty3
4869     // Assuming ty2 is shorter than ty3, this could be turned into:
4870     // a = Inst
4871     // b = sext ty1 a to ty2
4872     // c = sext ty2 b to ty3
4873     // However, the last sext is not free.
4874     if (IsSExt)
4875       return false;
4876
4877     // This is a ZExt, maybe this is free to extend from one type to another.
4878     // In that case, we would not account for a different use.
4879     Type *NarrowTy;
4880     Type *LargeTy;
4881     if (ExtTy->getScalarType()->getIntegerBitWidth() >
4882         CurTy->getScalarType()->getIntegerBitWidth()) {
4883       NarrowTy = CurTy;
4884       LargeTy = ExtTy;
4885     } else {
4886       NarrowTy = ExtTy;
4887       LargeTy = CurTy;
4888     }
4889
4890     if (!TLI.isZExtFree(NarrowTy, LargeTy))
4891       return false;
4892   }
4893   // All uses are the same or can be derived from one another for free.
4894   return true;
4895 }
4896
4897 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
4898 /// load instruction.
4899 /// If an ext(load) can be formed, it is returned via \p LI for the load
4900 /// and \p Inst for the extension.
4901 /// Otherwise LI == nullptr and Inst == nullptr.
4902 /// When some promotion happened, \p TPT contains the proper state to
4903 /// revert them.
4904 ///
4905 /// \return true when promoting was necessary to expose the ext(load)
4906 /// opportunity, false otherwise.
4907 ///
4908 /// Example:
4909 /// \code
4910 /// %ld = load i32* %addr
4911 /// %add = add nuw i32 %ld, 4
4912 /// %zext = zext i32 %add to i64
4913 /// \endcode
4914 /// =>
4915 /// \code
4916 /// %ld = load i32* %addr
4917 /// %zext = zext i32 %ld to i64
4918 /// %add = add nuw i64 %zext, 4
4919 /// \encode
4920 /// Thanks to the promotion, we can match zext(load i32*) to i64.
4921 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
4922                                     LoadInst *&LI, Instruction *&Inst,
4923                                     const SmallVectorImpl<Instruction *> &Exts,
4924                                     unsigned CreatedInstsCost = 0) {
4925   // Iterate over all the extensions to see if one form an ext(load).
4926   for (auto I : Exts) {
4927     // Check if we directly have ext(load).
4928     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4929       Inst = I;
4930       // No promotion happened here.
4931       return false;
4932     }
4933     // Check whether or not we want to do any promotion.
4934     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4935       continue;
4936     // Get the action to perform the promotion.
4937     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
4938         I, InsertedInsts, *TLI, PromotedInsts);
4939     // Check if we can promote.
4940     if (!TPH)
4941       continue;
4942     // Save the current state.
4943     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4944         TPT.getRestorationPoint();
4945     SmallVector<Instruction *, 4> NewExts;
4946     unsigned NewCreatedInstsCost = 0;
4947     unsigned ExtCost = !TLI->isExtFree(I);
4948     // Promote.
4949     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4950                              &NewExts, nullptr, *TLI);
4951     assert(PromotedVal &&
4952            "TypePromotionHelper should have filtered out those cases");
4953
4954     // We would be able to merge only one extension in a load.
4955     // Therefore, if we have more than 1 new extension we heuristically
4956     // cut this search path, because it means we degrade the code quality.
4957     // With exactly 2, the transformation is neutral, because we will merge
4958     // one extension but leave one. However, we optimistically keep going,
4959     // because the new extension may be removed too.
4960     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4961     TotalCreatedInstsCost -= ExtCost;
4962     if (!StressExtLdPromotion &&
4963         (TotalCreatedInstsCost > 1 ||
4964          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4965       // The promotion is not profitable, rollback to the previous state.
4966       TPT.rollback(LastKnownGood);
4967       continue;
4968     }
4969     // The promotion is profitable.
4970     // Check if it exposes an ext(load).
4971     (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
4972     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4973                // If we have created a new extension, i.e., now we have two
4974                // extensions. We must make sure one of them is merged with
4975                // the load, otherwise we may degrade the code quality.
4976                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4977       // Promotion happened.
4978       return true;
4979     // If this does not help to expose an ext(load) then, rollback.
4980     TPT.rollback(LastKnownGood);
4981   }
4982   // None of the extension can form an ext(load).
4983   LI = nullptr;
4984   Inst = nullptr;
4985   return false;
4986 }
4987
4988 /// Move a zext or sext fed by a load into the same basic block as the load,
4989 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
4990 /// extend into the load.
4991 /// \p I[in/out] the extension may be modified during the process if some
4992 /// promotions apply.
4993 ///
4994 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
4995   // Try to promote a chain of computation if it allows to form
4996   // an extended load.
4997   TypePromotionTransaction TPT;
4998   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4999     TPT.getRestorationPoint();
5000   SmallVector<Instruction *, 1> Exts;
5001   Exts.push_back(I);
5002   // Look for a load being extended.
5003   LoadInst *LI = nullptr;
5004   Instruction *OldExt = I;
5005   bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
5006   if (!LI || !I) {
5007     assert(!HasPromoted && !LI && "If we did not match any load instruction "
5008                                   "the code must remain the same");
5009     I = OldExt;
5010     return false;
5011   }
5012
5013   // If they're already in the same block, there's nothing to do.
5014   // Make the cheap checks first if we did not promote.
5015   // If we promoted, we need to check if it is indeed profitable.
5016   if (!HasPromoted && LI->getParent() == I->getParent())
5017     return false;
5018
5019   EVT VT = TLI->getValueType(*DL, I->getType());
5020   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
5021
5022   // If the load has other users and the truncate is not free, this probably
5023   // isn't worthwhile.
5024   if (!LI->hasOneUse() && TLI &&
5025       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
5026       !TLI->isTruncateFree(I->getType(), LI->getType())) {
5027     I = OldExt;
5028     TPT.rollback(LastKnownGood);
5029     return false;
5030   }
5031
5032   // Check whether the target supports casts folded into loads.
5033   unsigned LType;
5034   if (isa<ZExtInst>(I))
5035     LType = ISD::ZEXTLOAD;
5036   else {
5037     assert(isa<SExtInst>(I) && "Unexpected ext type!");
5038     LType = ISD::SEXTLOAD;
5039   }
5040   if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
5041     I = OldExt;
5042     TPT.rollback(LastKnownGood);
5043     return false;
5044   }
5045
5046   // Move the extend into the same block as the load, so that SelectionDAG
5047   // can fold it.
5048   TPT.commit();
5049   I->removeFromParent();
5050   I->insertAfter(LI);
5051   ++NumExtsMoved;
5052   return true;
5053 }
5054
5055 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
5056   BasicBlock *DefBB = I->getParent();
5057
5058   // If the result of a {s|z}ext and its source are both live out, rewrite all
5059   // other uses of the source with result of extension.
5060   Value *Src = I->getOperand(0);
5061   if (Src->hasOneUse())
5062     return false;
5063
5064   // Only do this xform if truncating is free.
5065   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
5066     return false;
5067
5068   // Only safe to perform the optimization if the source is also defined in
5069   // this block.
5070   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
5071     return false;
5072
5073   bool DefIsLiveOut = false;
5074   for (User *U : I->users()) {
5075     Instruction *UI = cast<Instruction>(U);
5076
5077     // Figure out which BB this ext is used in.
5078     BasicBlock *UserBB = UI->getParent();
5079     if (UserBB == DefBB) continue;
5080     DefIsLiveOut = true;
5081     break;
5082   }
5083   if (!DefIsLiveOut)
5084     return false;
5085
5086   // Make sure none of the uses are PHI nodes.
5087   for (User *U : Src->users()) {
5088     Instruction *UI = cast<Instruction>(U);
5089     BasicBlock *UserBB = UI->getParent();
5090     if (UserBB == DefBB) continue;
5091     // Be conservative. We don't want this xform to end up introducing
5092     // reloads just before load / store instructions.
5093     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5094       return false;
5095   }
5096
5097   // InsertedTruncs - Only insert one trunc in each block once.
5098   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5099
5100   bool MadeChange = false;
5101   for (Use &U : Src->uses()) {
5102     Instruction *User = cast<Instruction>(U.getUser());
5103
5104     // Figure out which BB this ext is used in.
5105     BasicBlock *UserBB = User->getParent();
5106     if (UserBB == DefBB) continue;
5107
5108     // Both src and def are live in this block. Rewrite the use.
5109     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5110
5111     if (!InsertedTrunc) {
5112       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5113       assert(InsertPt != UserBB->end());
5114       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
5115       InsertedInsts.insert(InsertedTrunc);
5116     }
5117
5118     // Replace a use of the {s|z}ext source with a use of the result.
5119     U = InsertedTrunc;
5120     ++NumExtUses;
5121     MadeChange = true;
5122   }
5123
5124   return MadeChange;
5125 }
5126
5127 // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
5128 // just after the load if the target can fold this into one extload instruction,
5129 // with the hope of eliminating some of the other later "and" instructions using
5130 // the loaded value.  "and"s that are made trivially redundant by the insertion
5131 // of the new "and" are removed by this function, while others (e.g. those whose
5132 // path from the load goes through a phi) are left for isel to potentially
5133 // remove.
5134 //
5135 // For example:
5136 //
5137 // b0:
5138 //   x = load i32
5139 //   ...
5140 // b1:
5141 //   y = and x, 0xff
5142 //   z = use y
5143 //
5144 // becomes:
5145 //
5146 // b0:
5147 //   x = load i32
5148 //   x' = and x, 0xff
5149 //   ...
5150 // b1:
5151 //   z = use x'
5152 //
5153 // whereas:
5154 //
5155 // b0:
5156 //   x1 = load i32
5157 //   ...
5158 // b1:
5159 //   x2 = load i32
5160 //   ...
5161 // b2:
5162 //   x = phi x1, x2
5163 //   y = and x, 0xff
5164 //
5165 // becomes (after a call to optimizeLoadExt for each load):
5166 //
5167 // b0:
5168 //   x1 = load i32
5169 //   x1' = and x1, 0xff
5170 //   ...
5171 // b1:
5172 //   x2 = load i32
5173 //   x2' = and x2, 0xff
5174 //   ...
5175 // b2:
5176 //   x = phi x1', x2'
5177 //   y = and x, 0xff
5178 //
5179
5180 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
5181
5182   if (!Load->isSimple() ||
5183       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5184     return false;
5185
5186   // Skip loads we've already transformed or have no reason to transform.
5187   if (Load->hasOneUse()) {
5188     User *LoadUser = *Load->user_begin();
5189     if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
5190         !dyn_cast<PHINode>(LoadUser))
5191       return false;
5192   }
5193
5194   // Look at all uses of Load, looking through phis, to determine how many bits
5195   // of the loaded value are needed.
5196   SmallVector<Instruction *, 8> WorkList;
5197   SmallPtrSet<Instruction *, 16> Visited;
5198   SmallVector<Instruction *, 8> AndsToMaybeRemove;
5199   for (auto *U : Load->users())
5200     WorkList.push_back(cast<Instruction>(U));
5201
5202   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5203   unsigned BitWidth = LoadResultVT.getSizeInBits();
5204   APInt DemandBits(BitWidth, 0);
5205   APInt WidestAndBits(BitWidth, 0);
5206
5207   while (!WorkList.empty()) {
5208     Instruction *I = WorkList.back();
5209     WorkList.pop_back();
5210
5211     // Break use-def graph loops.
5212     if (!Visited.insert(I).second)
5213       continue;
5214
5215     // For a PHI node, push all of its users.
5216     if (auto *Phi = dyn_cast<PHINode>(I)) {
5217       for (auto *U : Phi->users())
5218         WorkList.push_back(cast<Instruction>(U));
5219       continue;
5220     }
5221
5222     switch (I->getOpcode()) {
5223     case llvm::Instruction::And: {
5224       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5225       if (!AndC)
5226         return false;
5227       APInt AndBits = AndC->getValue();
5228       DemandBits |= AndBits;
5229       // Keep track of the widest and mask we see.
5230       if (AndBits.ugt(WidestAndBits))
5231         WidestAndBits = AndBits;
5232       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5233         AndsToMaybeRemove.push_back(I);
5234       break;
5235     }
5236
5237     case llvm::Instruction::Shl: {
5238       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5239       if (!ShlC)
5240         return false;
5241       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
5242       auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
5243       DemandBits |= ShlDemandBits;
5244       break;
5245     }
5246
5247     case llvm::Instruction::Trunc: {
5248       EVT TruncVT = TLI->getValueType(*DL, I->getType());
5249       unsigned TruncBitWidth = TruncVT.getSizeInBits();
5250       auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
5251       DemandBits |= TruncBits;
5252       break;
5253     }
5254
5255     default:
5256       return false;
5257     }
5258   }
5259
5260   uint32_t ActiveBits = DemandBits.getActiveBits();
5261   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5262   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
5263   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5264   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5265   // followed by an AND.
5266   // TODO: Look into removing this restriction by fixing backends to either
5267   // return false for isLoadExtLegal for i1 or have them select this pattern to
5268   // a single instruction.
5269   //
5270   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5271   // mask, since these are the only ands that will be removed by isel.
5272   if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
5273       WidestAndBits != DemandBits)
5274     return false;
5275
5276   LLVMContext &Ctx = Load->getType()->getContext();
5277   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5278   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5279
5280   // Reject cases that won't be matched as extloads.
5281   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5282       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5283     return false;
5284
5285   IRBuilder<> Builder(Load->getNextNode());
5286   auto *NewAnd = dyn_cast<Instruction>(
5287       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5288
5289   // Replace all uses of load with new and (except for the use of load in the
5290   // new and itself).
5291   Load->replaceAllUsesWith(NewAnd);
5292   NewAnd->setOperand(0, Load);
5293
5294   // Remove any and instructions that are now redundant.
5295   for (auto *And : AndsToMaybeRemove)
5296     // Check that the and mask is the same as the one we decided to put on the
5297     // new and.
5298     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5299       And->replaceAllUsesWith(NewAnd);
5300       if (&*CurInstIterator == And)
5301         CurInstIterator = std::next(And->getIterator());
5302       And->eraseFromParent();
5303       ++NumAndUses;
5304     }
5305
5306   ++NumAndsAdded;
5307   return true;
5308 }
5309
5310 /// Check if V (an operand of a select instruction) is an expensive instruction
5311 /// that is only used once.
5312 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5313   auto *I = dyn_cast<Instruction>(V);
5314   // If it's safe to speculatively execute, then it should not have side
5315   // effects; therefore, it's safe to sink and possibly *not* execute.
5316   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5317          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5318 }
5319
5320 /// Returns true if a SelectInst should be turned into an explicit branch.
5321 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
5322                                                 SelectInst *SI) {
5323   // FIXME: This should use the same heuristics as IfConversion to determine
5324   // whether a select is better represented as a branch.  This requires that
5325   // branch probability metadata is preserved for the select, which is not the
5326   // case currently.
5327
5328   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5329
5330   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5331   // comparison condition. If the compare has more than one use, there's
5332   // probably another cmov or setcc around, so it's not worth emitting a branch.
5333   if (!Cmp || !Cmp->hasOneUse())
5334     return false;
5335
5336   Value *CmpOp0 = Cmp->getOperand(0);
5337   Value *CmpOp1 = Cmp->getOperand(1);
5338
5339   // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
5340   // on a load from memory. But if the load is used more than once, do not
5341   // change the select to a branch because the load is probably needed
5342   // regardless of whether the branch is taken or not.
5343   if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
5344       (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
5345     return true;
5346
5347   // If either operand of the select is expensive and only needed on one side
5348   // of the select, we should form a branch.
5349   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5350       sinkSelectOperand(TTI, SI->getFalseValue()))
5351     return true;
5352
5353   return false;
5354 }
5355
5356
5357 /// If we have a SelectInst that will likely profit from branch prediction,
5358 /// turn it into a branch.
5359 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5360   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5361
5362   // Can we convert the 'select' to CF ?
5363   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
5364     return false;
5365
5366   TargetLowering::SelectSupportKind SelectKind;
5367   if (VectorCond)
5368     SelectKind = TargetLowering::VectorMaskSelect;
5369   else if (SI->getType()->isVectorTy())
5370     SelectKind = TargetLowering::ScalarCondVectorVal;
5371   else
5372     SelectKind = TargetLowering::ScalarValSelect;
5373
5374   // Do we have efficient codegen support for this kind of 'selects' ?
5375   if (TLI->isSelectSupported(SelectKind)) {
5376     // We have efficient codegen support for the select instruction.
5377     // Check if it is profitable to keep this 'select'.
5378     if (!TLI->isPredictableSelectExpensive() ||
5379         !isFormingBranchFromSelectProfitable(TTI, SI))
5380       return false;
5381   }
5382
5383   ModifiedDT = true;
5384
5385   // Transform a sequence like this:
5386   //    start:
5387   //       %cmp = cmp uge i32 %a, %b
5388   //       %sel = select i1 %cmp, i32 %c, i32 %d
5389   //
5390   // Into:
5391   //    start:
5392   //       %cmp = cmp uge i32 %a, %b
5393   //       br i1 %cmp, label %select.true, label %select.false
5394   //    select.true:
5395   //       br label %select.end
5396   //    select.false:
5397   //       br label %select.end
5398   //    select.end:
5399   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5400   //
5401   // In addition, we may sink instructions that produce %c or %d from
5402   // the entry block into the destination(s) of the new branch.
5403   // If the true or false blocks do not contain a sunken instruction, that
5404   // block and its branch may be optimized away. In that case, one side of the
5405   // first branch will point directly to select.end, and the corresponding PHI
5406   // predecessor block will be the start block.
5407
5408   // First, we split the block containing the select into 2 blocks.
5409   BasicBlock *StartBlock = SI->getParent();
5410   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
5411   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
5412
5413   // Delete the unconditional branch that was just created by the split.
5414   StartBlock->getTerminator()->eraseFromParent();
5415
5416   // These are the new basic blocks for the conditional branch.
5417   // At least one will become an actual new basic block.
5418   BasicBlock *TrueBlock = nullptr;
5419   BasicBlock *FalseBlock = nullptr;
5420
5421   // Sink expensive instructions into the conditional blocks to avoid executing
5422   // them speculatively.
5423   if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5424     TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5425                                    EndBlock->getParent(), EndBlock);
5426     auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5427     auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5428     TrueInst->moveBefore(TrueBranch);
5429   }
5430   if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5431     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5432                                     EndBlock->getParent(), EndBlock);
5433     auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5434     auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5435     FalseInst->moveBefore(FalseBranch);
5436   }
5437
5438   // If there was nothing to sink, then arbitrarily choose the 'false' side
5439   // for a new input value to the PHI.
5440   if (TrueBlock == FalseBlock) {
5441     assert(TrueBlock == nullptr &&
5442            "Unexpected basic block transform while optimizing select");
5443
5444     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5445                                     EndBlock->getParent(), EndBlock);
5446     BranchInst::Create(EndBlock, FalseBlock);
5447   }
5448
5449   // Insert the real conditional branch based on the original condition.
5450   // If we did not create a new block for one of the 'true' or 'false' paths
5451   // of the condition, it means that side of the branch goes to the end block
5452   // directly and the path originates from the start block from the point of
5453   // view of the new PHI.
5454   if (TrueBlock == nullptr) {
5455     BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
5456     TrueBlock = StartBlock;
5457   } else if (FalseBlock == nullptr) {
5458     BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
5459     FalseBlock = StartBlock;
5460   } else {
5461     BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
5462   }
5463
5464   // The select itself is replaced with a PHI Node.
5465   PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5466   PN->takeName(SI);
5467   PN->addIncoming(SI->getTrueValue(), TrueBlock);
5468   PN->addIncoming(SI->getFalseValue(), FalseBlock);
5469
5470   SI->replaceAllUsesWith(PN);
5471   SI->eraseFromParent();
5472
5473   // Instruct OptimizeBlock to skip to the next block.
5474   CurInstIterator = StartBlock->end();
5475   ++NumSelectsExpanded;
5476   return true;
5477 }
5478
5479 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
5480   SmallVector<int, 16> Mask(SVI->getShuffleMask());
5481   int SplatElem = -1;
5482   for (unsigned i = 0; i < Mask.size(); ++i) {
5483     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5484       return false;
5485     SplatElem = Mask[i];
5486   }
5487
5488   return true;
5489 }
5490
5491 /// Some targets have expensive vector shifts if the lanes aren't all the same
5492 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5493 /// it's often worth sinking a shufflevector splat down to its use so that
5494 /// codegen can spot all lanes are identical.
5495 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
5496   BasicBlock *DefBB = SVI->getParent();
5497
5498   // Only do this xform if variable vector shifts are particularly expensive.
5499   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5500     return false;
5501
5502   // We only expect better codegen by sinking a shuffle if we can recognise a
5503   // constant splat.
5504   if (!isBroadcastShuffle(SVI))
5505     return false;
5506
5507   // InsertedShuffles - Only insert a shuffle in each block once.
5508   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5509
5510   bool MadeChange = false;
5511   for (User *U : SVI->users()) {
5512     Instruction *UI = cast<Instruction>(U);
5513
5514     // Figure out which BB this ext is used in.
5515     BasicBlock *UserBB = UI->getParent();
5516     if (UserBB == DefBB) continue;
5517
5518     // For now only apply this when the splat is used by a shift instruction.
5519     if (!UI->isShift()) continue;
5520
5521     // Everything checks out, sink the shuffle if the user's block doesn't
5522     // already have a copy.
5523     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5524
5525     if (!InsertedShuffle) {
5526       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
5527       assert(InsertPt != UserBB->end());
5528       InsertedShuffle =
5529           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5530                                 SVI->getOperand(2), "", &*InsertPt);
5531     }
5532
5533     UI->replaceUsesOfWith(SVI, InsertedShuffle);
5534     MadeChange = true;
5535   }
5536
5537   // If we removed all uses, nuke the shuffle.
5538   if (SVI->use_empty()) {
5539     SVI->eraseFromParent();
5540     MadeChange = true;
5541   }
5542
5543   return MadeChange;
5544 }
5545
5546 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5547   if (!TLI || !DL)
5548     return false;
5549
5550   Value *Cond = SI->getCondition();
5551   Type *OldType = Cond->getType();
5552   LLVMContext &Context = Cond->getContext();
5553   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5554   unsigned RegWidth = RegType.getSizeInBits();
5555
5556   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5557     return false;
5558
5559   // If the register width is greater than the type width, expand the condition
5560   // of the switch instruction and each case constant to the width of the
5561   // register. By widening the type of the switch condition, subsequent
5562   // comparisons (for case comparisons) will not need to be extended to the
5563   // preferred register width, so we will potentially eliminate N-1 extends,
5564   // where N is the number of cases in the switch.
5565   auto *NewType = Type::getIntNTy(Context, RegWidth);
5566
5567   // Zero-extend the switch condition and case constants unless the switch
5568   // condition is a function argument that is already being sign-extended.
5569   // In that case, we can avoid an unnecessary mask/extension by sign-extending
5570   // everything instead.
5571   Instruction::CastOps ExtType = Instruction::ZExt;
5572   if (auto *Arg = dyn_cast<Argument>(Cond))
5573     if (Arg->hasSExtAttr())
5574       ExtType = Instruction::SExt;
5575
5576   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5577   ExtInst->insertBefore(SI);
5578   SI->setCondition(ExtInst);
5579   for (SwitchInst::CaseIt Case : SI->cases()) {
5580     APInt NarrowConst = Case.getCaseValue()->getValue();
5581     APInt WideConst = (ExtType == Instruction::ZExt) ?
5582                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5583     Case.setValue(ConstantInt::get(Context, WideConst));
5584   }
5585
5586   return true;
5587 }
5588
5589 namespace {
5590 /// \brief Helper class to promote a scalar operation to a vector one.
5591 /// This class is used to move downward extractelement transition.
5592 /// E.g.,
5593 /// a = vector_op <2 x i32>
5594 /// b = extractelement <2 x i32> a, i32 0
5595 /// c = scalar_op b
5596 /// store c
5597 ///
5598 /// =>
5599 /// a = vector_op <2 x i32>
5600 /// c = vector_op a (equivalent to scalar_op on the related lane)
5601 /// * d = extractelement <2 x i32> c, i32 0
5602 /// * store d
5603 /// Assuming both extractelement and store can be combine, we get rid of the
5604 /// transition.
5605 class VectorPromoteHelper {
5606   /// DataLayout associated with the current module.
5607   const DataLayout &DL;
5608
5609   /// Used to perform some checks on the legality of vector operations.
5610   const TargetLowering &TLI;
5611
5612   /// Used to estimated the cost of the promoted chain.
5613   const TargetTransformInfo &TTI;
5614
5615   /// The transition being moved downwards.
5616   Instruction *Transition;
5617   /// The sequence of instructions to be promoted.
5618   SmallVector<Instruction *, 4> InstsToBePromoted;
5619   /// Cost of combining a store and an extract.
5620   unsigned StoreExtractCombineCost;
5621   /// Instruction that will be combined with the transition.
5622   Instruction *CombineInst;
5623
5624   /// \brief The instruction that represents the current end of the transition.
5625   /// Since we are faking the promotion until we reach the end of the chain
5626   /// of computation, we need a way to get the current end of the transition.
5627   Instruction *getEndOfTransition() const {
5628     if (InstsToBePromoted.empty())
5629       return Transition;
5630     return InstsToBePromoted.back();
5631   }
5632
5633   /// \brief Return the index of the original value in the transition.
5634   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5635   /// c, is at index 0.
5636   unsigned getTransitionOriginalValueIdx() const {
5637     assert(isa<ExtractElementInst>(Transition) &&
5638            "Other kind of transitions are not supported yet");
5639     return 0;
5640   }
5641
5642   /// \brief Return the index of the index in the transition.
5643   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5644   /// is at index 1.
5645   unsigned getTransitionIdx() const {
5646     assert(isa<ExtractElementInst>(Transition) &&
5647            "Other kind of transitions are not supported yet");
5648     return 1;
5649   }
5650
5651   /// \brief Get the type of the transition.
5652   /// This is the type of the original value.
5653   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5654   /// transition is <2 x i32>.
5655   Type *getTransitionType() const {
5656     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5657   }
5658
5659   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5660   /// I.e., we have the following sequence:
5661   /// Def = Transition <ty1> a to <ty2>
5662   /// b = ToBePromoted <ty2> Def, ...
5663   /// =>
5664   /// b = ToBePromoted <ty1> a, ...
5665   /// Def = Transition <ty1> ToBePromoted to <ty2>
5666   void promoteImpl(Instruction *ToBePromoted);
5667
5668   /// \brief Check whether or not it is profitable to promote all the
5669   /// instructions enqueued to be promoted.
5670   bool isProfitableToPromote() {
5671     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5672     unsigned Index = isa<ConstantInt>(ValIdx)
5673                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
5674                          : -1;
5675     Type *PromotedType = getTransitionType();
5676
5677     StoreInst *ST = cast<StoreInst>(CombineInst);
5678     unsigned AS = ST->getPointerAddressSpace();
5679     unsigned Align = ST->getAlignment();
5680     // Check if this store is supported.
5681     if (!TLI.allowsMisalignedMemoryAccesses(
5682             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5683             Align)) {
5684       // If this is not supported, there is no way we can combine
5685       // the extract with the store.
5686       return false;
5687     }
5688
5689     // The scalar chain of computation has to pay for the transition
5690     // scalar to vector.
5691     // The vector chain has to account for the combining cost.
5692     uint64_t ScalarCost =
5693         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5694     uint64_t VectorCost = StoreExtractCombineCost;
5695     for (const auto &Inst : InstsToBePromoted) {
5696       // Compute the cost.
5697       // By construction, all instructions being promoted are arithmetic ones.
5698       // Moreover, one argument is a constant that can be viewed as a splat
5699       // constant.
5700       Value *Arg0 = Inst->getOperand(0);
5701       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5702                             isa<ConstantFP>(Arg0);
5703       TargetTransformInfo::OperandValueKind Arg0OVK =
5704           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5705                          : TargetTransformInfo::OK_AnyValue;
5706       TargetTransformInfo::OperandValueKind Arg1OVK =
5707           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5708                           : TargetTransformInfo::OK_AnyValue;
5709       ScalarCost += TTI.getArithmeticInstrCost(
5710           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5711       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5712                                                Arg0OVK, Arg1OVK);
5713     }
5714     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5715                  << ScalarCost << "\nVector: " << VectorCost << '\n');
5716     return ScalarCost > VectorCost;
5717   }
5718
5719   /// \brief Generate a constant vector with \p Val with the same
5720   /// number of elements as the transition.
5721   /// \p UseSplat defines whether or not \p Val should be replicated
5722   /// across the whole vector.
5723   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5724   /// otherwise we generate a vector with as many undef as possible:
5725   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5726   /// used at the index of the extract.
5727   Value *getConstantVector(Constant *Val, bool UseSplat) const {
5728     unsigned ExtractIdx = UINT_MAX;
5729     if (!UseSplat) {
5730       // If we cannot determine where the constant must be, we have to
5731       // use a splat constant.
5732       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5733       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5734         ExtractIdx = CstVal->getSExtValue();
5735       else
5736         UseSplat = true;
5737     }
5738
5739     unsigned End = getTransitionType()->getVectorNumElements();
5740     if (UseSplat)
5741       return ConstantVector::getSplat(End, Val);
5742
5743     SmallVector<Constant *, 4> ConstVec;
5744     UndefValue *UndefVal = UndefValue::get(Val->getType());
5745     for (unsigned Idx = 0; Idx != End; ++Idx) {
5746       if (Idx == ExtractIdx)
5747         ConstVec.push_back(Val);
5748       else
5749         ConstVec.push_back(UndefVal);
5750     }
5751     return ConstantVector::get(ConstVec);
5752   }
5753
5754   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5755   /// in \p Use can trigger undefined behavior.
5756   static bool canCauseUndefinedBehavior(const Instruction *Use,
5757                                         unsigned OperandIdx) {
5758     // This is not safe to introduce undef when the operand is on
5759     // the right hand side of a division-like instruction.
5760     if (OperandIdx != 1)
5761       return false;
5762     switch (Use->getOpcode()) {
5763     default:
5764       return false;
5765     case Instruction::SDiv:
5766     case Instruction::UDiv:
5767     case Instruction::SRem:
5768     case Instruction::URem:
5769       return true;
5770     case Instruction::FDiv:
5771     case Instruction::FRem:
5772       return !Use->hasNoNaNs();
5773     }
5774     llvm_unreachable(nullptr);
5775   }
5776
5777 public:
5778   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5779                       const TargetTransformInfo &TTI, Instruction *Transition,
5780                       unsigned CombineCost)
5781       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5782         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5783     assert(Transition && "Do not know how to promote null");
5784   }
5785
5786   /// \brief Check if we can promote \p ToBePromoted to \p Type.
5787   bool canPromote(const Instruction *ToBePromoted) const {
5788     // We could support CastInst too.
5789     return isa<BinaryOperator>(ToBePromoted);
5790   }
5791
5792   /// \brief Check if it is profitable to promote \p ToBePromoted
5793   /// by moving downward the transition through.
5794   bool shouldPromote(const Instruction *ToBePromoted) const {
5795     // Promote only if all the operands can be statically expanded.
5796     // Indeed, we do not want to introduce any new kind of transitions.
5797     for (const Use &U : ToBePromoted->operands()) {
5798       const Value *Val = U.get();
5799       if (Val == getEndOfTransition()) {
5800         // If the use is a division and the transition is on the rhs,
5801         // we cannot promote the operation, otherwise we may create a
5802         // division by zero.
5803         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5804           return false;
5805         continue;
5806       }
5807       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5808           !isa<ConstantFP>(Val))
5809         return false;
5810     }
5811     // Check that the resulting operation is legal.
5812     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5813     if (!ISDOpcode)
5814       return false;
5815     return StressStoreExtract ||
5816            TLI.isOperationLegalOrCustom(
5817                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
5818   }
5819
5820   /// \brief Check whether or not \p Use can be combined
5821   /// with the transition.
5822   /// I.e., is it possible to do Use(Transition) => AnotherUse?
5823   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5824
5825   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5826   void enqueueForPromotion(Instruction *ToBePromoted) {
5827     InstsToBePromoted.push_back(ToBePromoted);
5828   }
5829
5830   /// \brief Set the instruction that will be combined with the transition.
5831   void recordCombineInstruction(Instruction *ToBeCombined) {
5832     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5833     CombineInst = ToBeCombined;
5834   }
5835
5836   /// \brief Promote all the instructions enqueued for promotion if it is
5837   /// is profitable.
5838   /// \return True if the promotion happened, false otherwise.
5839   bool promote() {
5840     // Check if there is something to promote.
5841     // Right now, if we do not have anything to combine with,
5842     // we assume the promotion is not profitable.
5843     if (InstsToBePromoted.empty() || !CombineInst)
5844       return false;
5845
5846     // Check cost.
5847     if (!StressStoreExtract && !isProfitableToPromote())
5848       return false;
5849
5850     // Promote.
5851     for (auto &ToBePromoted : InstsToBePromoted)
5852       promoteImpl(ToBePromoted);
5853     InstsToBePromoted.clear();
5854     return true;
5855   }
5856 };
5857 } // End of anonymous namespace.
5858
5859 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5860   // At this point, we know that all the operands of ToBePromoted but Def
5861   // can be statically promoted.
5862   // For Def, we need to use its parameter in ToBePromoted:
5863   // b = ToBePromoted ty1 a
5864   // Def = Transition ty1 b to ty2
5865   // Move the transition down.
5866   // 1. Replace all uses of the promoted operation by the transition.
5867   // = ... b => = ... Def.
5868   assert(ToBePromoted->getType() == Transition->getType() &&
5869          "The type of the result of the transition does not match "
5870          "the final type");
5871   ToBePromoted->replaceAllUsesWith(Transition);
5872   // 2. Update the type of the uses.
5873   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5874   Type *TransitionTy = getTransitionType();
5875   ToBePromoted->mutateType(TransitionTy);
5876   // 3. Update all the operands of the promoted operation with promoted
5877   // operands.
5878   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5879   for (Use &U : ToBePromoted->operands()) {
5880     Value *Val = U.get();
5881     Value *NewVal = nullptr;
5882     if (Val == Transition)
5883       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5884     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5885              isa<ConstantFP>(Val)) {
5886       // Use a splat constant if it is not safe to use undef.
5887       NewVal = getConstantVector(
5888           cast<Constant>(Val),
5889           isa<UndefValue>(Val) ||
5890               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5891     } else
5892       llvm_unreachable("Did you modified shouldPromote and forgot to update "
5893                        "this?");
5894     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5895   }
5896   Transition->removeFromParent();
5897   Transition->insertAfter(ToBePromoted);
5898   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5899 }
5900
5901 /// Some targets can do store(extractelement) with one instruction.
5902 /// Try to push the extractelement towards the stores when the target
5903 /// has this feature and this is profitable.
5904 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
5905   unsigned CombineCost = UINT_MAX;
5906   if (DisableStoreExtract || !TLI ||
5907       (!StressStoreExtract &&
5908        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5909                                        Inst->getOperand(1), CombineCost)))
5910     return false;
5911
5912   // At this point we know that Inst is a vector to scalar transition.
5913   // Try to move it down the def-use chain, until:
5914   // - We can combine the transition with its single use
5915   //   => we got rid of the transition.
5916   // - We escape the current basic block
5917   //   => we would need to check that we are moving it at a cheaper place and
5918   //      we do not do that for now.
5919   BasicBlock *Parent = Inst->getParent();
5920   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5921   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5922   // If the transition has more than one use, assume this is not going to be
5923   // beneficial.
5924   while (Inst->hasOneUse()) {
5925     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5926     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5927
5928     if (ToBePromoted->getParent() != Parent) {
5929       DEBUG(dbgs() << "Instruction to promote is in a different block ("
5930                    << ToBePromoted->getParent()->getName()
5931                    << ") than the transition (" << Parent->getName() << ").\n");
5932       return false;
5933     }
5934
5935     if (VPH.canCombine(ToBePromoted)) {
5936       DEBUG(dbgs() << "Assume " << *Inst << '\n'
5937                    << "will be combined with: " << *ToBePromoted << '\n');
5938       VPH.recordCombineInstruction(ToBePromoted);
5939       bool Changed = VPH.promote();
5940       NumStoreExtractExposed += Changed;
5941       return Changed;
5942     }
5943
5944     DEBUG(dbgs() << "Try promoting.\n");
5945     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5946       return false;
5947
5948     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5949
5950     VPH.enqueueForPromotion(ToBePromoted);
5951     Inst = ToBePromoted;
5952   }
5953   return false;
5954 }
5955
5956 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
5957   // Bail out if we inserted the instruction to prevent optimizations from
5958   // stepping on each other's toes.
5959   if (InsertedInsts.count(I))
5960     return false;
5961
5962   if (PHINode *P = dyn_cast<PHINode>(I)) {
5963     // It is possible for very late stage optimizations (such as SimplifyCFG)
5964     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
5965     // trivial PHI, go ahead and zap it here.
5966     if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
5967       P->replaceAllUsesWith(V);
5968       P->eraseFromParent();
5969       ++NumPHIsElim;
5970       return true;
5971     }
5972     return false;
5973   }
5974
5975   if (CastInst *CI = dyn_cast<CastInst>(I)) {
5976     // If the source of the cast is a constant, then this should have
5977     // already been constant folded.  The only reason NOT to constant fold
5978     // it is if something (e.g. LSR) was careful to place the constant
5979     // evaluation in a block other than then one that uses it (e.g. to hoist
5980     // the address of globals out of a loop).  If this is the case, we don't
5981     // want to forward-subst the cast.
5982     if (isa<Constant>(CI->getOperand(0)))
5983       return false;
5984
5985     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
5986       return true;
5987
5988     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
5989       /// Sink a zext or sext into its user blocks if the target type doesn't
5990       /// fit in one register
5991       if (TLI &&
5992           TLI->getTypeAction(CI->getContext(),
5993                              TLI->getValueType(*DL, CI->getType())) ==
5994               TargetLowering::TypeExpandInteger) {
5995         return SinkCast(CI);
5996       } else {
5997         bool MadeChange = moveExtToFormExtLoad(I);
5998         return MadeChange | optimizeExtUses(I);
5999       }
6000     }
6001     return false;
6002   }
6003
6004   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6005     if (!TLI || !TLI->hasMultipleConditionRegisters())
6006       return OptimizeCmpExpression(CI);
6007
6008   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6009     stripInvariantGroupMetadata(*LI);
6010     if (TLI) {
6011       bool Modified = optimizeLoadExt(LI);
6012       unsigned AS = LI->getPointerAddressSpace();
6013       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6014       return Modified;
6015     }
6016     return false;
6017   }
6018
6019   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6020     stripInvariantGroupMetadata(*SI);
6021     if (TLI) {
6022       unsigned AS = SI->getPointerAddressSpace();
6023       return optimizeMemoryInst(I, SI->getOperand(1),
6024                                 SI->getOperand(0)->getType(), AS);
6025     }
6026     return false;
6027   }
6028
6029   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6030
6031   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6032                 BinOp->getOpcode() == Instruction::LShr)) {
6033     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6034     if (TLI && CI && TLI->hasExtractBitsInsn())
6035       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
6036
6037     return false;
6038   }
6039
6040   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
6041     if (GEPI->hasAllZeroIndices()) {
6042       /// The GEP operand must be a pointer, so must its result -> BitCast
6043       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6044                                         GEPI->getName(), GEPI);
6045       GEPI->replaceAllUsesWith(NC);
6046       GEPI->eraseFromParent();
6047       ++NumGEPsElim;
6048       optimizeInst(NC, ModifiedDT);
6049       return true;
6050     }
6051     return false;
6052   }
6053
6054   if (CallInst *CI = dyn_cast<CallInst>(I))
6055     return optimizeCallInst(CI, ModifiedDT);
6056
6057   if (SelectInst *SI = dyn_cast<SelectInst>(I))
6058     return optimizeSelectInst(SI);
6059
6060   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
6061     return optimizeShuffleVectorInst(SVI);
6062
6063   if (auto *Switch = dyn_cast<SwitchInst>(I))
6064     return optimizeSwitchInst(Switch);
6065
6066   if (isa<ExtractElementInst>(I))
6067     return optimizeExtractElementInst(I);
6068
6069   return false;
6070 }
6071
6072 /// Given an OR instruction, check to see if this is a bitreverse
6073 /// idiom. If so, insert the new intrinsic and return true.
6074 static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6075                            const TargetLowering &TLI) {
6076   if (!I.getType()->isIntegerTy() ||
6077       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6078                                     TLI.getValueType(DL, I.getType(), true)))
6079     return false;
6080
6081   SmallVector<Instruction*, 4> Insts;
6082   if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
6083     return false;
6084   Instruction *LastInst = Insts.back();
6085   I.replaceAllUsesWith(LastInst);
6086   RecursivelyDeleteTriviallyDeadInstructions(&I);
6087   return true;
6088 }
6089
6090 // In this pass we look for GEP and cast instructions that are used
6091 // across basic blocks and rewrite them to improve basic-block-at-a-time
6092 // selection.
6093 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
6094   SunkAddrs.clear();
6095   bool MadeChange = false;
6096
6097   CurInstIterator = BB.begin();
6098   while (CurInstIterator != BB.end()) {
6099     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6100     if (ModifiedDT)
6101       return true;
6102   }
6103
6104   bool MadeBitReverse = true;
6105   while (TLI && MadeBitReverse) {
6106     MadeBitReverse = false;
6107     for (auto &I : reverse(BB)) {
6108       if (makeBitReverse(I, *DL, *TLI)) {
6109         MadeBitReverse = MadeChange = true;
6110         break;
6111       }
6112     }
6113   }
6114   MadeChange |= dupRetToEnableTailCallOpts(&BB);
6115   
6116   return MadeChange;
6117 }
6118
6119 // llvm.dbg.value is far away from the value then iSel may not be able
6120 // handle it properly. iSel will drop llvm.dbg.value if it can not
6121 // find a node corresponding to the value.
6122 bool CodeGenPrepare::placeDbgValues(Function &F) {
6123   bool MadeChange = false;
6124   for (BasicBlock &BB : F) {
6125     Instruction *PrevNonDbgInst = nullptr;
6126     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
6127       Instruction *Insn = &*BI++;
6128       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
6129       // Leave dbg.values that refer to an alloca alone. These
6130       // instrinsics describe the address of a variable (= the alloca)
6131       // being taken.  They should not be moved next to the alloca
6132       // (and to the beginning of the scope), but rather stay close to
6133       // where said address is used.
6134       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
6135         PrevNonDbgInst = Insn;
6136         continue;
6137       }
6138
6139       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6140       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
6141         // If VI is a phi in a block with an EHPad terminator, we can't insert
6142         // after it.
6143         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6144           continue;
6145         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6146         DVI->removeFromParent();
6147         if (isa<PHINode>(VI))
6148           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6149         else
6150           DVI->insertAfter(VI);
6151         MadeChange = true;
6152         ++NumDbgValueMoved;
6153       }
6154     }
6155   }
6156   return MadeChange;
6157 }
6158
6159 // If there is a sequence that branches based on comparing a single bit
6160 // against zero that can be combined into a single instruction, and the
6161 // target supports folding these into a single instruction, sink the
6162 // mask and compare into the branch uses. Do this before OptimizeBlock ->
6163 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
6164 // searched for.
6165 bool CodeGenPrepare::sinkAndCmp(Function &F) {
6166   if (!EnableAndCmpSinking)
6167     return false;
6168   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
6169     return false;
6170   bool MadeChange = false;
6171   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
6172     BasicBlock *BB = &*I++;
6173
6174     // Does this BB end with the following?
6175     //   %andVal = and %val, #single-bit-set
6176     //   %icmpVal = icmp %andResult, 0
6177     //   br i1 %cmpVal label %dest1, label %dest2"
6178     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
6179     if (!Brcc || !Brcc->isConditional())
6180       continue;
6181     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
6182     if (!Cmp || Cmp->getParent() != BB)
6183       continue;
6184     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
6185     if (!Zero || !Zero->isZero())
6186       continue;
6187     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
6188     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
6189       continue;
6190     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
6191     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
6192       continue;
6193     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
6194
6195     // Push the "and; icmp" for any users that are conditional branches.
6196     // Since there can only be one branch use per BB, we don't need to keep
6197     // track of which BBs we insert into.
6198     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
6199          UI != E; ) {
6200       Use &TheUse = *UI;
6201       // Find brcc use.
6202       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
6203       ++UI;
6204       if (!BrccUser || !BrccUser->isConditional())
6205         continue;
6206       BasicBlock *UserBB = BrccUser->getParent();
6207       if (UserBB == BB) continue;
6208       DEBUG(dbgs() << "found Brcc use\n");
6209
6210       // Sink the "and; icmp" to use.
6211       MadeChange = true;
6212       BinaryOperator *NewAnd =
6213         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
6214                                   BrccUser);
6215       CmpInst *NewCmp =
6216         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
6217                         "", BrccUser);
6218       TheUse = NewCmp;
6219       ++NumAndCmpsMoved;
6220       DEBUG(BrccUser->getParent()->dump());
6221     }
6222   }
6223   return MadeChange;
6224 }
6225
6226 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
6227 /// success, or returns false if no or invalid metadata was found.
6228 static bool extractBranchMetadata(BranchInst *BI,
6229                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
6230   assert(BI->isConditional() &&
6231          "Looking for probabilities on unconditional branch?");
6232   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
6233   if (!ProfileData || ProfileData->getNumOperands() != 3)
6234     return false;
6235
6236   const auto *CITrue =
6237       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
6238   const auto *CIFalse =
6239       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
6240   if (!CITrue || !CIFalse)
6241     return false;
6242
6243   ProbTrue = CITrue->getValue().getZExtValue();
6244   ProbFalse = CIFalse->getValue().getZExtValue();
6245
6246   return true;
6247 }
6248
6249 /// \brief Scale down both weights to fit into uint32_t.
6250 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6251   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6252   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6253   NewTrue = NewTrue / Scale;
6254   NewFalse = NewFalse / Scale;
6255 }
6256
6257 /// \brief Some targets prefer to split a conditional branch like:
6258 /// \code
6259 ///   %0 = icmp ne i32 %a, 0
6260 ///   %1 = icmp ne i32 %b, 0
6261 ///   %or.cond = or i1 %0, %1
6262 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
6263 /// \endcode
6264 /// into multiple branch instructions like:
6265 /// \code
6266 ///   bb1:
6267 ///     %0 = icmp ne i32 %a, 0
6268 ///     br i1 %0, label %TrueBB, label %bb2
6269 ///   bb2:
6270 ///     %1 = icmp ne i32 %b, 0
6271 ///     br i1 %1, label %TrueBB, label %FalseBB
6272 /// \endcode
6273 /// This usually allows instruction selection to do even further optimizations
6274 /// and combine the compare with the branch instruction. Currently this is
6275 /// applied for targets which have "cheap" jump instructions.
6276 ///
6277 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6278 ///
6279 bool CodeGenPrepare::splitBranchCondition(Function &F) {
6280   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
6281     return false;
6282
6283   bool MadeChange = false;
6284   for (auto &BB : F) {
6285     // Does this BB end with the following?
6286     //   %cond1 = icmp|fcmp|binary instruction ...
6287     //   %cond2 = icmp|fcmp|binary instruction ...
6288     //   %cond.or = or|and i1 %cond1, cond2
6289     //   br i1 %cond.or label %dest1, label %dest2"
6290     BinaryOperator *LogicOp;
6291     BasicBlock *TBB, *FBB;
6292     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6293       continue;
6294
6295     auto *Br1 = cast<BranchInst>(BB.getTerminator());
6296     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6297       continue;
6298
6299     unsigned Opc;
6300     Value *Cond1, *Cond2;
6301     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6302                              m_OneUse(m_Value(Cond2)))))
6303       Opc = Instruction::And;
6304     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6305                                  m_OneUse(m_Value(Cond2)))))
6306       Opc = Instruction::Or;
6307     else
6308       continue;
6309
6310     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6311         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
6312       continue;
6313
6314     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6315
6316     // Create a new BB.
6317     auto *InsertBefore = std::next(Function::iterator(BB))
6318         .getNodePtrUnchecked();
6319     auto TmpBB = BasicBlock::Create(BB.getContext(),
6320                                     BB.getName() + ".cond.split",
6321                                     BB.getParent(), InsertBefore);
6322
6323     // Update original basic block by using the first condition directly by the
6324     // branch instruction and removing the no longer needed and/or instruction.
6325     Br1->setCondition(Cond1);
6326     LogicOp->eraseFromParent();
6327
6328     // Depending on the conditon we have to either replace the true or the false
6329     // successor of the original branch instruction.
6330     if (Opc == Instruction::And)
6331       Br1->setSuccessor(0, TmpBB);
6332     else
6333       Br1->setSuccessor(1, TmpBB);
6334
6335     // Fill in the new basic block.
6336     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6337     if (auto *I = dyn_cast<Instruction>(Cond2)) {
6338       I->removeFromParent();
6339       I->insertBefore(Br2);
6340     }
6341
6342     // Update PHI nodes in both successors. The original BB needs to be
6343     // replaced in one succesor's PHI nodes, because the branch comes now from
6344     // the newly generated BB (NewBB). In the other successor we need to add one
6345     // incoming edge to the PHI nodes, because both branch instructions target
6346     // now the same successor. Depending on the original branch condition
6347     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6348     // we perfrom the correct update for the PHI nodes.
6349     // This doesn't change the successor order of the just created branch
6350     // instruction (or any other instruction).
6351     if (Opc == Instruction::Or)
6352       std::swap(TBB, FBB);
6353
6354     // Replace the old BB with the new BB.
6355     for (auto &I : *TBB) {
6356       PHINode *PN = dyn_cast<PHINode>(&I);
6357       if (!PN)
6358         break;
6359       int i;
6360       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6361         PN->setIncomingBlock(i, TmpBB);
6362     }
6363
6364     // Add another incoming edge form the new BB.
6365     for (auto &I : *FBB) {
6366       PHINode *PN = dyn_cast<PHINode>(&I);
6367       if (!PN)
6368         break;
6369       auto *Val = PN->getIncomingValueForBlock(&BB);
6370       PN->addIncoming(Val, TmpBB);
6371     }
6372
6373     // Update the branch weights (from SelectionDAGBuilder::
6374     // FindMergedConditions).
6375     if (Opc == Instruction::Or) {
6376       // Codegen X | Y as:
6377       // BB1:
6378       //   jmp_if_X TBB
6379       //   jmp TmpBB
6380       // TmpBB:
6381       //   jmp_if_Y TBB
6382       //   jmp FBB
6383       //
6384
6385       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6386       // The requirement is that
6387       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6388       //     = TrueProb for orignal BB.
6389       // Assuming the orignal weights are A and B, one choice is to set BB1's
6390       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6391       // assumes that
6392       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6393       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6394       // TmpBB, but the math is more complicated.
6395       uint64_t TrueWeight, FalseWeight;
6396       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6397         uint64_t NewTrueWeight = TrueWeight;
6398         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6399         scaleWeights(NewTrueWeight, NewFalseWeight);
6400         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6401                          .createBranchWeights(TrueWeight, FalseWeight));
6402
6403         NewTrueWeight = TrueWeight;
6404         NewFalseWeight = 2 * FalseWeight;
6405         scaleWeights(NewTrueWeight, NewFalseWeight);
6406         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6407                          .createBranchWeights(TrueWeight, FalseWeight));
6408       }
6409     } else {
6410       // Codegen X & Y as:
6411       // BB1:
6412       //   jmp_if_X TmpBB
6413       //   jmp FBB
6414       // TmpBB:
6415       //   jmp_if_Y TBB
6416       //   jmp FBB
6417       //
6418       //  This requires creation of TmpBB after CurBB.
6419
6420       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6421       // The requirement is that
6422       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6423       //     = FalseProb for orignal BB.
6424       // Assuming the orignal weights are A and B, one choice is to set BB1's
6425       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6426       // assumes that
6427       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6428       uint64_t TrueWeight, FalseWeight;
6429       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
6430         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6431         uint64_t NewFalseWeight = FalseWeight;
6432         scaleWeights(NewTrueWeight, NewFalseWeight);
6433         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6434                          .createBranchWeights(TrueWeight, FalseWeight));
6435
6436         NewTrueWeight = 2 * TrueWeight;
6437         NewFalseWeight = FalseWeight;
6438         scaleWeights(NewTrueWeight, NewFalseWeight);
6439         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6440                          .createBranchWeights(TrueWeight, FalseWeight));
6441       }
6442     }
6443
6444     // Note: No point in getting fancy here, since the DT info is never
6445     // available to CodeGenPrepare.
6446     ModifiedDT = true;
6447
6448     MadeChange = true;
6449
6450     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6451           TmpBB->dump());
6452   }
6453   return MadeChange;
6454 }
6455
6456 void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
6457   if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
6458     I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
6459 }