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