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