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