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