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