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