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