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