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