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