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