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