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