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