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