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