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