1 //===- InstCombineCalls.cpp -----------------------------------------------===//
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 file implements the visitCall, visitInvoke, and visitCallBr functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/FloatingPointMode.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumeBundleQueries.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/IntrinsicsAArch64.h"
50 #include "llvm/IR/IntrinsicsAMDGPU.h"
51 #include "llvm/IR/IntrinsicsARM.h"
52 #include "llvm/IR/IntrinsicsHexagon.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/PatternMatch.h"
56 #include "llvm/IR/Statepoint.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/KnownBits.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Transforms/InstCombine/InstCombiner.h"
71 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
72 #include "llvm/Transforms/Utils/Local.h"
73 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstdint>
77 #include <cstring>
78 #include <utility>
79 #include <vector>
80 
81 #define DEBUG_TYPE "instcombine"
82 #include "llvm/Transforms/Utils/InstructionWorklist.h"
83 
84 using namespace llvm;
85 using namespace PatternMatch;
86 
87 STATISTIC(NumSimplified, "Number of library calls simplified");
88 
89 static cl::opt<unsigned> GuardWideningWindow(
90     "instcombine-guard-widening-window",
91     cl::init(3),
92     cl::desc("How wide an instruction window to bypass looking for "
93              "another guard"));
94 
95 namespace llvm {
96 /// enable preservation of attributes in assume like:
97 /// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
98 extern cl::opt<bool> EnableKnowledgeRetention;
99 } // namespace llvm
100 
101 /// Return the specified type promoted as it would be to pass though a va_arg
102 /// area.
103 static Type *getPromotedType(Type *Ty) {
104   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
105     if (ITy->getBitWidth() < 32)
106       return Type::getInt32Ty(Ty->getContext());
107   }
108   return Ty;
109 }
110 
111 Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
112   Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
113   MaybeAlign CopyDstAlign = MI->getDestAlign();
114   if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
115     MI->setDestAlignment(DstAlign);
116     return MI;
117   }
118 
119   Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
120   MaybeAlign CopySrcAlign = MI->getSourceAlign();
121   if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
122     MI->setSourceAlignment(SrcAlign);
123     return MI;
124   }
125 
126   // If we have a store to a location which is known constant, we can conclude
127   // that the store must be storing the constant value (else the memory
128   // wouldn't be constant), and this must be a noop.
129   if (AA->pointsToConstantMemory(MI->getDest())) {
130     // Set the size of the copy to 0, it will be deleted on the next iteration.
131     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
132     return MI;
133   }
134 
135   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
136   // load/store.
137   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
138   if (!MemOpLength) return nullptr;
139 
140   // Source and destination pointer types are always "i8*" for intrinsic.  See
141   // if the size is something we can handle with a single primitive load/store.
142   // A single load+store correctly handles overlapping memory in the memmove
143   // case.
144   uint64_t Size = MemOpLength->getLimitedValue();
145   assert(Size && "0-sized memory transferring should be removed already.");
146 
147   if (Size > 8 || (Size&(Size-1)))
148     return nullptr;  // If not 1/2/4/8 bytes, exit.
149 
150   // If it is an atomic and alignment is less than the size then we will
151   // introduce the unaligned memory access which will be later transformed
152   // into libcall in CodeGen. This is not evident performance gain so disable
153   // it now.
154   if (isa<AtomicMemTransferInst>(MI))
155     if (*CopyDstAlign < Size || *CopySrcAlign < Size)
156       return nullptr;
157 
158   // Use an integer load+store unless we can find something better.
159   unsigned SrcAddrSp =
160     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
161   unsigned DstAddrSp =
162     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
163 
164   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
165   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
166   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
167 
168   // If the memcpy has metadata describing the members, see if we can get the
169   // TBAA tag describing our copy.
170   MDNode *CopyMD = nullptr;
171   if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
172     CopyMD = M;
173   } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
174     if (M->getNumOperands() == 3 && M->getOperand(0) &&
175         mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
176         mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
177         M->getOperand(1) &&
178         mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
179         mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
180         Size &&
181         M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
182       CopyMD = cast<MDNode>(M->getOperand(2));
183   }
184 
185   Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
186   Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
187   LoadInst *L = Builder.CreateLoad(IntType, Src);
188   // Alignment from the mem intrinsic will be better, so use it.
189   L->setAlignment(*CopySrcAlign);
190   if (CopyMD)
191     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
192   MDNode *LoopMemParallelMD =
193     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
194   if (LoopMemParallelMD)
195     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
196   MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
197   if (AccessGroupMD)
198     L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
199 
200   StoreInst *S = Builder.CreateStore(L, Dest);
201   // Alignment from the mem intrinsic will be better, so use it.
202   S->setAlignment(*CopyDstAlign);
203   if (CopyMD)
204     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
205   if (LoopMemParallelMD)
206     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
207   if (AccessGroupMD)
208     S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
209 
210   if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
211     // non-atomics can be volatile
212     L->setVolatile(MT->isVolatile());
213     S->setVolatile(MT->isVolatile());
214   }
215   if (isa<AtomicMemTransferInst>(MI)) {
216     // atomics have to be unordered
217     L->setOrdering(AtomicOrdering::Unordered);
218     S->setOrdering(AtomicOrdering::Unordered);
219   }
220 
221   // Set the size of the copy to 0, it will be deleted on the next iteration.
222   MI->setLength(Constant::getNullValue(MemOpLength->getType()));
223   return MI;
224 }
225 
226 Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
227   const Align KnownAlignment =
228       getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
229   MaybeAlign MemSetAlign = MI->getDestAlign();
230   if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
231     MI->setDestAlignment(KnownAlignment);
232     return MI;
233   }
234 
235   // If we have a store to a location which is known constant, we can conclude
236   // that the store must be storing the constant value (else the memory
237   // wouldn't be constant), and this must be a noop.
238   if (AA->pointsToConstantMemory(MI->getDest())) {
239     // Set the size of the copy to 0, it will be deleted on the next iteration.
240     MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241     return MI;
242   }
243 
244   // Extract the length and alignment and fill if they are constant.
245   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
247   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
248     return nullptr;
249   const uint64_t Len = LenC->getLimitedValue();
250   assert(Len && "0-sized memory setting should be removed already.");
251   const Align Alignment = assumeAligned(MI->getDestAlignment());
252 
253   // If it is an atomic and alignment is less than the size then we will
254   // introduce the unaligned memory access which will be later transformed
255   // into libcall in CodeGen. This is not evident performance gain so disable
256   // it now.
257   if (isa<AtomicMemSetInst>(MI))
258     if (Alignment < Len)
259       return nullptr;
260 
261   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
263     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
264 
265     Value *Dest = MI->getDest();
266     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
267     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
268     Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
269 
270     // Extract the fill value and store.
271     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
272     StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
273                                        MI->isVolatile());
274     S->setAlignment(Alignment);
275     if (isa<AtomicMemSetInst>(MI))
276       S->setOrdering(AtomicOrdering::Unordered);
277 
278     // Set the size of the copy to 0, it will be deleted on the next iteration.
279     MI->setLength(Constant::getNullValue(LenC->getType()));
280     return MI;
281   }
282 
283   return nullptr;
284 }
285 
286 // TODO, Obvious Missing Transforms:
287 // * Narrow width by halfs excluding zero/undef lanes
288 Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
289   Value *LoadPtr = II.getArgOperand(0);
290   const Align Alignment =
291       cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
292 
293   // If the mask is all ones or undefs, this is a plain vector load of the 1st
294   // argument.
295   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
296     LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
297                                             "unmaskedload");
298     L->copyMetadata(II);
299     return L;
300   }
301 
302   // If we can unconditionally load from this address, replace with a
303   // load/select idiom. TODO: use DT for context sensitive query
304   if (isDereferenceablePointer(LoadPtr, II.getType(),
305                                II.getModule()->getDataLayout(), &II, nullptr)) {
306     LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
307                                              "unmaskedload");
308     LI->copyMetadata(II);
309     return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
310   }
311 
312   return nullptr;
313 }
314 
315 // TODO, Obvious Missing Transforms:
316 // * Single constant active lane -> store
317 // * Narrow width by halfs excluding zero/undef lanes
318 Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
319   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
320   if (!ConstMask)
321     return nullptr;
322 
323   // If the mask is all zeros, this instruction does nothing.
324   if (ConstMask->isNullValue())
325     return eraseInstFromFunction(II);
326 
327   // If the mask is all ones, this is a plain vector store of the 1st argument.
328   if (ConstMask->isAllOnesValue()) {
329     Value *StorePtr = II.getArgOperand(1);
330     Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
331     StoreInst *S =
332         new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
333     S->copyMetadata(II);
334     return S;
335   }
336 
337   if (isa<ScalableVectorType>(ConstMask->getType()))
338     return nullptr;
339 
340   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
341   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
342   APInt UndefElts(DemandedElts.getBitWidth(), 0);
343   if (Value *V =
344           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
345     return replaceOperand(II, 0, V);
346 
347   return nullptr;
348 }
349 
350 // TODO, Obvious Missing Transforms:
351 // * Single constant active lane load -> load
352 // * Dereferenceable address & few lanes -> scalarize speculative load/selects
353 // * Adjacent vector addresses -> masked.load
354 // * Narrow width by halfs excluding zero/undef lanes
355 // * Vector incrementing address -> vector masked load
356 Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
357   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
358   if (!ConstMask)
359     return nullptr;
360 
361   // Vector splat address w/known mask -> scalar load
362   // Fold the gather to load the source vector first lane
363   // because it is reloading the same value each time
364   if (ConstMask->isAllOnesValue())
365     if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
366       auto *VecTy = cast<VectorType>(II.getType());
367       const Align Alignment =
368           cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
369       LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
370                                               Alignment, "load.scalar");
371       Value *Shuf =
372           Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
373       return replaceInstUsesWith(II, cast<Instruction>(Shuf));
374     }
375 
376   return nullptr;
377 }
378 
379 // TODO, Obvious Missing Transforms:
380 // * Single constant active lane -> store
381 // * Adjacent vector addresses -> masked.store
382 // * Narrow store width by halfs excluding zero/undef lanes
383 // * Vector incrementing address -> vector masked store
384 Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
385   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
386   if (!ConstMask)
387     return nullptr;
388 
389   // If the mask is all zeros, a scatter does nothing.
390   if (ConstMask->isNullValue())
391     return eraseInstFromFunction(II);
392 
393   // Vector splat address -> scalar store
394   if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
395     // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
396     if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
397       Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
398       StoreInst *S =
399           new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
400       S->copyMetadata(II);
401       return S;
402     }
403     // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
404     // lastlane), ptr
405     if (ConstMask->isAllOnesValue()) {
406       Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
407       VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
408       ElementCount VF = WideLoadTy->getElementCount();
409       Constant *EC =
410           ConstantInt::get(Builder.getInt32Ty(), VF.getKnownMinValue());
411       Value *RunTimeVF = VF.isScalable() ? Builder.CreateVScale(EC) : EC;
412       Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
413       Value *Extract =
414           Builder.CreateExtractElement(II.getArgOperand(0), LastLane);
415       StoreInst *S =
416           new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
417       S->copyMetadata(II);
418       return S;
419     }
420   }
421   if (isa<ScalableVectorType>(ConstMask->getType()))
422     return nullptr;
423 
424   // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
425   APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
426   APInt UndefElts(DemandedElts.getBitWidth(), 0);
427   if (Value *V =
428           SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
429     return replaceOperand(II, 0, V);
430   if (Value *V =
431           SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts))
432     return replaceOperand(II, 1, V);
433 
434   return nullptr;
435 }
436 
437 /// This function transforms launder.invariant.group and strip.invariant.group
438 /// like:
439 /// launder(launder(%x)) -> launder(%x)       (the result is not the argument)
440 /// launder(strip(%x)) -> launder(%x)
441 /// strip(strip(%x)) -> strip(%x)             (the result is not the argument)
442 /// strip(launder(%x)) -> strip(%x)
443 /// This is legal because it preserves the most recent information about
444 /// the presence or absence of invariant.group.
445 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
446                                                     InstCombinerImpl &IC) {
447   auto *Arg = II.getArgOperand(0);
448   auto *StrippedArg = Arg->stripPointerCasts();
449   auto *StrippedInvariantGroupsArg = StrippedArg;
450   while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
451     if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
452         Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
453       break;
454     StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
455   }
456   if (StrippedArg == StrippedInvariantGroupsArg)
457     return nullptr; // No launders/strips to remove.
458 
459   Value *Result = nullptr;
460 
461   if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
462     Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
463   else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
464     Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
465   else
466     llvm_unreachable(
467         "simplifyInvariantGroupIntrinsic only handles launder and strip");
468   if (Result->getType()->getPointerAddressSpace() !=
469       II.getType()->getPointerAddressSpace())
470     Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
471   if (Result->getType() != II.getType())
472     Result = IC.Builder.CreateBitCast(Result, II.getType());
473 
474   return cast<Instruction>(Result);
475 }
476 
477 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
478   assert((II.getIntrinsicID() == Intrinsic::cttz ||
479           II.getIntrinsicID() == Intrinsic::ctlz) &&
480          "Expected cttz or ctlz intrinsic");
481   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
482   Value *Op0 = II.getArgOperand(0);
483   Value *Op1 = II.getArgOperand(1);
484   Value *X;
485   // ctlz(bitreverse(x)) -> cttz(x)
486   // cttz(bitreverse(x)) -> ctlz(x)
487   if (match(Op0, m_BitReverse(m_Value(X)))) {
488     Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
489     Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
490     return CallInst::Create(F, {X, II.getArgOperand(1)});
491   }
492 
493   if (II.getType()->isIntOrIntVectorTy(1)) {
494     // ctlz/cttz i1 Op0 --> not Op0
495     if (match(Op1, m_Zero()))
496       return BinaryOperator::CreateNot(Op0);
497     // If zero is poison, then the input can be assumed to be "true", so the
498     // instruction simplifies to "false".
499     assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
500     return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));
501   }
502 
503   // If the operand is a select with constant arm(s), try to hoist ctlz/cttz.
504   if (auto *Sel = dyn_cast<SelectInst>(Op0))
505     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
506       return R;
507 
508   if (IsTZ) {
509     // cttz(-x) -> cttz(x)
510     if (match(Op0, m_Neg(m_Value(X))))
511       return IC.replaceOperand(II, 0, X);
512 
513     // cttz(sext(x)) -> cttz(zext(x))
514     if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
515       auto *Zext = IC.Builder.CreateZExt(X, II.getType());
516       auto *CttzZext =
517           IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
518       return IC.replaceInstUsesWith(II, CttzZext);
519     }
520 
521     // Zext doesn't change the number of trailing zeros, so narrow:
522     // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
523     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
524       auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
525                                                     IC.Builder.getTrue());
526       auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
527       return IC.replaceInstUsesWith(II, ZextCttz);
528     }
529 
530     // cttz(abs(x)) -> cttz(x)
531     // cttz(nabs(x)) -> cttz(x)
532     Value *Y;
533     SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
534     if (SPF == SPF_ABS || SPF == SPF_NABS)
535       return IC.replaceOperand(II, 0, X);
536 
537     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
538       return IC.replaceOperand(II, 0, X);
539   }
540 
541   KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
542 
543   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
544   unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
545                                 : Known.countMaxLeadingZeros();
546   unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
547                                 : Known.countMinLeadingZeros();
548 
549   // If all bits above (ctlz) or below (cttz) the first known one are known
550   // zero, this value is constant.
551   // FIXME: This should be in InstSimplify because we're replacing an
552   // instruction with a constant.
553   if (PossibleZeros == DefiniteZeros) {
554     auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
555     return IC.replaceInstUsesWith(II, C);
556   }
557 
558   // If the input to cttz/ctlz is known to be non-zero,
559   // then change the 'ZeroIsPoison' parameter to 'true'
560   // because we know the zero behavior can't affect the result.
561   if (!Known.One.isZero() ||
562       isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
563                      &IC.getDominatorTree())) {
564     if (!match(II.getArgOperand(1), m_One()))
565       return IC.replaceOperand(II, 1, IC.Builder.getTrue());
566   }
567 
568   // Add range metadata since known bits can't completely reflect what we know.
569   // TODO: Handle splat vectors.
570   auto *IT = dyn_cast<IntegerType>(Op0->getType());
571   if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
572     Metadata *LowAndHigh[] = {
573         ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
574         ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
575     II.setMetadata(LLVMContext::MD_range,
576                    MDNode::get(II.getContext(), LowAndHigh));
577     return &II;
578   }
579 
580   return nullptr;
581 }
582 
583 static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
584   assert(II.getIntrinsicID() == Intrinsic::ctpop &&
585          "Expected ctpop intrinsic");
586   Type *Ty = II.getType();
587   unsigned BitWidth = Ty->getScalarSizeInBits();
588   Value *Op0 = II.getArgOperand(0);
589   Value *X, *Y;
590 
591   // ctpop(bitreverse(x)) -> ctpop(x)
592   // ctpop(bswap(x)) -> ctpop(x)
593   if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
594     return IC.replaceOperand(II, 0, X);
595 
596   // ctpop(rot(x)) -> ctpop(x)
597   if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
598        match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
599       X == Y)
600     return IC.replaceOperand(II, 0, X);
601 
602   // ctpop(x | -x) -> bitwidth - cttz(x, false)
603   if (Op0->hasOneUse() &&
604       match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
605     Function *F =
606         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
607     auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
608     auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
609     return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
610   }
611 
612   // ctpop(~x & (x - 1)) -> cttz(x, false)
613   if (match(Op0,
614             m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) {
615     Function *F =
616         Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
617     return CallInst::Create(F, {X, IC.Builder.getFalse()});
618   }
619 
620   // Zext doesn't change the number of set bits, so narrow:
621   // ctpop (zext X) --> zext (ctpop X)
622   if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
623     Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
624     return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
625   }
626 
627   // If the operand is a select with constant arm(s), try to hoist ctpop.
628   if (auto *Sel = dyn_cast<SelectInst>(Op0))
629     if (Instruction *R = IC.FoldOpIntoSelect(II, Sel))
630       return R;
631 
632   KnownBits Known(BitWidth);
633   IC.computeKnownBits(Op0, Known, 0, &II);
634 
635   // If all bits are zero except for exactly one fixed bit, then the result
636   // must be 0 or 1, and we can get that answer by shifting to LSB:
637   // ctpop (X & 32) --> (X & 32) >> 5
638   if ((~Known.Zero).isPowerOf2())
639     return BinaryOperator::CreateLShr(
640         Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
641 
642   // FIXME: Try to simplify vectors of integers.
643   auto *IT = dyn_cast<IntegerType>(Ty);
644   if (!IT)
645     return nullptr;
646 
647   // Add range metadata since known bits can't completely reflect what we know.
648   unsigned MinCount = Known.countMinPopulation();
649   unsigned MaxCount = Known.countMaxPopulation();
650   if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
651     Metadata *LowAndHigh[] = {
652         ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
653         ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
654     II.setMetadata(LLVMContext::MD_range,
655                    MDNode::get(II.getContext(), LowAndHigh));
656     return &II;
657   }
658 
659   return nullptr;
660 }
661 
662 /// Convert a table lookup to shufflevector if the mask is constant.
663 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
664 /// which case we could lower the shufflevector with rev64 instructions
665 /// as it's actually a byte reverse.
666 static Value *simplifyNeonTbl1(const IntrinsicInst &II,
667                                InstCombiner::BuilderTy &Builder) {
668   // Bail out if the mask is not a constant.
669   auto *C = dyn_cast<Constant>(II.getArgOperand(1));
670   if (!C)
671     return nullptr;
672 
673   auto *VecTy = cast<FixedVectorType>(II.getType());
674   unsigned NumElts = VecTy->getNumElements();
675 
676   // Only perform this transformation for <8 x i8> vector types.
677   if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
678     return nullptr;
679 
680   int Indexes[8];
681 
682   for (unsigned I = 0; I < NumElts; ++I) {
683     Constant *COp = C->getAggregateElement(I);
684 
685     if (!COp || !isa<ConstantInt>(COp))
686       return nullptr;
687 
688     Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
689 
690     // Make sure the mask indices are in range.
691     if ((unsigned)Indexes[I] >= NumElts)
692       return nullptr;
693   }
694 
695   auto *V1 = II.getArgOperand(0);
696   auto *V2 = Constant::getNullValue(V1->getType());
697   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes));
698 }
699 
700 // Returns true iff the 2 intrinsics have the same operands, limiting the
701 // comparison to the first NumOperands.
702 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
703                              unsigned NumOperands) {
704   assert(I.arg_size() >= NumOperands && "Not enough operands");
705   assert(E.arg_size() >= NumOperands && "Not enough operands");
706   for (unsigned i = 0; i < NumOperands; i++)
707     if (I.getArgOperand(i) != E.getArgOperand(i))
708       return false;
709   return true;
710 }
711 
712 // Remove trivially empty start/end intrinsic ranges, i.e. a start
713 // immediately followed by an end (ignoring debuginfo or other
714 // start/end intrinsics in between). As this handles only the most trivial
715 // cases, tracking the nesting level is not needed:
716 //
717 //   call @llvm.foo.start(i1 0)
718 //   call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
719 //   call @llvm.foo.end(i1 0)
720 //   call @llvm.foo.end(i1 0) ; &I
721 static bool
722 removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
723                           std::function<bool(const IntrinsicInst &)> IsStart) {
724   // We start from the end intrinsic and scan backwards, so that InstCombine
725   // has already processed (and potentially removed) all the instructions
726   // before the end intrinsic.
727   BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
728   for (; BI != BE; ++BI) {
729     if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
730       if (I->isDebugOrPseudoInst() ||
731           I->getIntrinsicID() == EndI.getIntrinsicID())
732         continue;
733       if (IsStart(*I)) {
734         if (haveSameOperands(EndI, *I, EndI.arg_size())) {
735           IC.eraseInstFromFunction(*I);
736           IC.eraseInstFromFunction(EndI);
737           return true;
738         }
739         // Skip start intrinsics that don't pair with this end intrinsic.
740         continue;
741       }
742     }
743     break;
744   }
745 
746   return false;
747 }
748 
749 Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
750   removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
751     return I.getIntrinsicID() == Intrinsic::vastart ||
752            I.getIntrinsicID() == Intrinsic::vacopy;
753   });
754   return nullptr;
755 }
756 
757 static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
758   assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
759   Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
760   if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
761     Call.setArgOperand(0, Arg1);
762     Call.setArgOperand(1, Arg0);
763     return &Call;
764   }
765   return nullptr;
766 }
767 
768 /// Creates a result tuple for an overflow intrinsic \p II with a given
769 /// \p Result and a constant \p Overflow value.
770 static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
771                                         Constant *Overflow) {
772   Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
773   StructType *ST = cast<StructType>(II->getType());
774   Constant *Struct = ConstantStruct::get(ST, V);
775   return InsertValueInst::Create(Struct, Result, 0);
776 }
777 
778 Instruction *
779 InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
780   WithOverflowInst *WO = cast<WithOverflowInst>(II);
781   Value *OperationResult = nullptr;
782   Constant *OverflowResult = nullptr;
783   if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
784                             WO->getRHS(), *WO, OperationResult, OverflowResult))
785     return createOverflowTuple(WO, OperationResult, OverflowResult);
786   return nullptr;
787 }
788 
789 static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
790                                    const DataLayout &DL, AssumptionCache *AC,
791                                    DominatorTree *DT) {
792   KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
793   if (Known.isNonNegative())
794     return false;
795   if (Known.isNegative())
796     return true;
797 
798   return isImpliedByDomCondition(
799       ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
800 }
801 
802 /// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
803 /// can trigger other combines.
804 static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
805                                        InstCombiner::BuilderTy &Builder) {
806   Intrinsic::ID MinMaxID = II->getIntrinsicID();
807   assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
808           MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
809          "Expected a min or max intrinsic");
810 
811   // TODO: Match vectors with undef elements, but undef may not propagate.
812   Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
813   Value *X;
814   const APInt *C0, *C1;
815   if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
816       !match(Op1, m_APInt(C1)))
817     return nullptr;
818 
819   // Check for necessary no-wrap and overflow constraints.
820   bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
821   auto *Add = cast<BinaryOperator>(Op0);
822   if ((IsSigned && !Add->hasNoSignedWrap()) ||
823       (!IsSigned && !Add->hasNoUnsignedWrap()))
824     return nullptr;
825 
826   // If the constant difference overflows, then instsimplify should reduce the
827   // min/max to the add or C1.
828   bool Overflow;
829   APInt CDiff =
830       IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
831   assert(!Overflow && "Expected simplify of min/max");
832 
833   // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
834   // Note: the "mismatched" no-overflow setting does not propagate.
835   Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
836   Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
837   return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
838                   : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
839 }
840 
841 /// If we have a clamp pattern like max (min X, 42), 41 -- where the output
842 /// can only be one of two possible constant values -- turn that into a select
843 /// of constants.
844 static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
845                                         InstCombiner::BuilderTy &Builder) {
846   Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
847   Value *X;
848   const APInt *C0, *C1;
849   if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
850     return nullptr;
851 
852   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
853   switch (II->getIntrinsicID()) {
854   case Intrinsic::smax:
855     if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
856       Pred = ICmpInst::ICMP_SGT;
857     break;
858   case Intrinsic::smin:
859     if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
860       Pred = ICmpInst::ICMP_SLT;
861     break;
862   case Intrinsic::umax:
863     if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
864       Pred = ICmpInst::ICMP_UGT;
865     break;
866   case Intrinsic::umin:
867     if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
868       Pred = ICmpInst::ICMP_ULT;
869     break;
870   default:
871     llvm_unreachable("Expected min/max intrinsic");
872   }
873   if (Pred == CmpInst::BAD_ICMP_PREDICATE)
874     return nullptr;
875 
876   // max (min X, 42), 41 --> X > 41 ? 42 : 41
877   // min (max X, 42), 43 --> X < 43 ? 42 : 43
878   Value *Cmp = Builder.CreateICmp(Pred, X, I1);
879   return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
880 }
881 
882 /// If this min/max has a constant operand and an operand that is a matching
883 /// min/max with a constant operand, constant-fold the 2 constant operands.
884 static Instruction *reassociateMinMaxWithConstants(IntrinsicInst *II) {
885   Intrinsic::ID MinMaxID = II->getIntrinsicID();
886   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
887   if (!LHS || LHS->getIntrinsicID() != MinMaxID)
888     return nullptr;
889 
890   Constant *C0, *C1;
891   if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
892       !match(II->getArgOperand(1), m_ImmConstant(C1)))
893     return nullptr;
894 
895   // max (max X, C0), C1 --> max X, (max C0, C1) --> max X, NewC
896   ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(MinMaxID);
897   Constant *CondC = ConstantExpr::getICmp(Pred, C0, C1);
898   Constant *NewC = ConstantExpr::getSelect(CondC, C0, C1);
899 
900   Module *Mod = II->getModule();
901   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
902   return CallInst::Create(MinMax, {LHS->getArgOperand(0), NewC});
903 }
904 
905 /// Reduce a sequence of min/max intrinsics with a common operand.
906 static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
907   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
908   auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
909   auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
910   Intrinsic::ID MinMaxID = II->getIntrinsicID();
911   if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
912       RHS->getIntrinsicID() != MinMaxID ||
913       (!LHS->hasOneUse() && !RHS->hasOneUse()))
914     return nullptr;
915 
916   Value *A = LHS->getArgOperand(0);
917   Value *B = LHS->getArgOperand(1);
918   Value *C = RHS->getArgOperand(0);
919   Value *D = RHS->getArgOperand(1);
920 
921   // Look for a common operand.
922   Value *MinMaxOp = nullptr;
923   Value *ThirdOp = nullptr;
924   if (LHS->hasOneUse()) {
925     // If the LHS is only used in this chain and the RHS is used outside of it,
926     // reuse the RHS min/max because that will eliminate the LHS.
927     if (D == A || C == A) {
928       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
929       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
930       MinMaxOp = RHS;
931       ThirdOp = B;
932     } else if (D == B || C == B) {
933       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
934       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
935       MinMaxOp = RHS;
936       ThirdOp = A;
937     }
938   } else {
939     assert(RHS->hasOneUse() && "Expected one-use operand");
940     // Reuse the LHS. This will eliminate the RHS.
941     if (D == A || D == B) {
942       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
943       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
944       MinMaxOp = LHS;
945       ThirdOp = C;
946     } else if (C == A || C == B) {
947       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
948       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
949       MinMaxOp = LHS;
950       ThirdOp = D;
951     }
952   }
953 
954   if (!MinMaxOp || !ThirdOp)
955     return nullptr;
956 
957   Module *Mod = II->getModule();
958   Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());
959   return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
960 }
961 
962 /// CallInst simplification. This mostly only handles folding of intrinsic
963 /// instructions. For normal calls, it allows visitCallBase to do the heavy
964 /// lifting.
965 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
966   // Don't try to simplify calls without uses. It will not do anything useful,
967   // but will result in the following folds being skipped.
968   if (!CI.use_empty())
969     if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
970       return replaceInstUsesWith(CI, V);
971 
972   if (isFreeCall(&CI, &TLI))
973     return visitFree(CI);
974 
975   // If the caller function (i.e. us, the function that contains this CallInst)
976   // is nounwind, mark the call as nounwind, even if the callee isn't.
977   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
978     CI.setDoesNotThrow();
979     return &CI;
980   }
981 
982   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
983   if (!II) return visitCallBase(CI);
984 
985   // For atomic unordered mem intrinsics if len is not a positive or
986   // not a multiple of element size then behavior is undefined.
987   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
988     if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
989       if (NumBytes->getSExtValue() < 0 ||
990           (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
991         CreateNonTerminatorUnreachable(AMI);
992         assert(AMI->getType()->isVoidTy() &&
993                "non void atomic unordered mem intrinsic");
994         return eraseInstFromFunction(*AMI);
995       }
996 
997   // Intrinsics cannot occur in an invoke or a callbr, so handle them here
998   // instead of in visitCallBase.
999   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1000     bool Changed = false;
1001 
1002     // memmove/cpy/set of zero bytes is a noop.
1003     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1004       if (NumBytes->isNullValue())
1005         return eraseInstFromFunction(CI);
1006 
1007       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1008         if (CI->getZExtValue() == 1) {
1009           // Replace the instruction with just byte operations.  We would
1010           // transform other cases to loads/stores, but we don't know if
1011           // alignment is sufficient.
1012         }
1013     }
1014 
1015     // No other transformations apply to volatile transfers.
1016     if (auto *M = dyn_cast<MemIntrinsic>(MI))
1017       if (M->isVolatile())
1018         return nullptr;
1019 
1020     // If we have a memmove and the source operation is a constant global,
1021     // then the source and dest pointers can't alias, so we can change this
1022     // into a call to memcpy.
1023     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1024       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1025         if (GVSrc->isConstant()) {
1026           Module *M = CI.getModule();
1027           Intrinsic::ID MemCpyID =
1028               isa<AtomicMemMoveInst>(MMI)
1029                   ? Intrinsic::memcpy_element_unordered_atomic
1030                   : Intrinsic::memcpy;
1031           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1032                            CI.getArgOperand(1)->getType(),
1033                            CI.getArgOperand(2)->getType() };
1034           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1035           Changed = true;
1036         }
1037     }
1038 
1039     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1040       // memmove(x,x,size) -> noop.
1041       if (MTI->getSource() == MTI->getDest())
1042         return eraseInstFromFunction(CI);
1043     }
1044 
1045     // If we can determine a pointer alignment that is bigger than currently
1046     // set, update the alignment.
1047     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1048       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1049         return I;
1050     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1051       if (Instruction *I = SimplifyAnyMemSet(MSI))
1052         return I;
1053     }
1054 
1055     if (Changed) return II;
1056   }
1057 
1058   // For fixed width vector result intrinsics, use the generic demanded vector
1059   // support.
1060   if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1061     auto VWidth = IIFVTy->getNumElements();
1062     APInt UndefElts(VWidth, 0);
1063     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1064     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1065       if (V != II)
1066         return replaceInstUsesWith(*II, V);
1067       return II;
1068     }
1069   }
1070 
1071   if (II->isCommutative()) {
1072     if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1073       return NewCall;
1074   }
1075 
1076   Intrinsic::ID IID = II->getIntrinsicID();
1077   switch (IID) {
1078   case Intrinsic::objectsize:
1079     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1080       return replaceInstUsesWith(CI, V);
1081     return nullptr;
1082   case Intrinsic::abs: {
1083     Value *IIOperand = II->getArgOperand(0);
1084     bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1085 
1086     // abs(-x) -> abs(x)
1087     // TODO: Copy nsw if it was present on the neg?
1088     Value *X;
1089     if (match(IIOperand, m_Neg(m_Value(X))))
1090       return replaceOperand(*II, 0, X);
1091     if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
1092       return replaceOperand(*II, 0, X);
1093     if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
1094       return replaceOperand(*II, 0, X);
1095 
1096     if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
1097       // abs(x) -> x if x >= 0
1098       if (!*Sign)
1099         return replaceInstUsesWith(*II, IIOperand);
1100 
1101       // abs(x) -> -x if x < 0
1102       if (IntMinIsPoison)
1103         return BinaryOperator::CreateNSWNeg(IIOperand);
1104       return BinaryOperator::CreateNeg(IIOperand);
1105     }
1106 
1107     // abs (sext X) --> zext (abs X*)
1108     // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1109     if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1110       Value *NarrowAbs =
1111           Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1112       return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1113     }
1114 
1115     // Match a complicated way to check if a number is odd/even:
1116     // abs (srem X, 2) --> and X, 1
1117     const APInt *C;
1118     if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1119       return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1120 
1121     break;
1122   }
1123   case Intrinsic::umin: {
1124     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1125     // umin(x, 1) == zext(x != 0)
1126     if (match(I1, m_One())) {
1127       Value *Zero = Constant::getNullValue(I0->getType());
1128       Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1129       return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1130     }
1131     LLVM_FALLTHROUGH;
1132   }
1133   case Intrinsic::umax: {
1134     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1135     Value *X, *Y;
1136     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1137         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1138       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1139       return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1140     }
1141     Constant *C;
1142     if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1143         I0->hasOneUse()) {
1144       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1145       if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
1146         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1147         return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1148       }
1149     }
1150     // If both operands of unsigned min/max are sign-extended, it is still ok
1151     // to narrow the operation.
1152     LLVM_FALLTHROUGH;
1153   }
1154   case Intrinsic::smax:
1155   case Intrinsic::smin: {
1156     Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1157     Value *X, *Y;
1158     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1159         (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1160       Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1161       return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1162     }
1163 
1164     Constant *C;
1165     if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1166         I0->hasOneUse()) {
1167       Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1168       if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
1169         Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1170         return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1171       }
1172     }
1173 
1174     if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1175       // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1176       // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1177       // TODO: Canonicalize neg after min/max if I1 is constant.
1178       if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1179           (I0->hasOneUse() || I1->hasOneUse())) {
1180         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1181         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1182         return BinaryOperator::CreateNSWNeg(InvMaxMin);
1183       }
1184     }
1185 
1186     // If we can eliminate ~A and Y is free to invert:
1187     // max ~A, Y --> ~(min A, ~Y)
1188     //
1189     // Examples:
1190     // max ~A, ~Y --> ~(min A, Y)
1191     // max ~A, C --> ~(min A, ~C)
1192     // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1193     auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1194       Value *A;
1195       if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1196           !isFreeToInvert(A, A->hasOneUse()) &&
1197           isFreeToInvert(Y, Y->hasOneUse())) {
1198         Value *NotY = Builder.CreateNot(Y);
1199         Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);
1200         Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1201         return BinaryOperator::CreateNot(InvMaxMin);
1202       }
1203       return nullptr;
1204     };
1205 
1206     if (Instruction *I = moveNotAfterMinMax(I0, I1))
1207       return I;
1208     if (Instruction *I = moveNotAfterMinMax(I1, I0))
1209       return I;
1210 
1211     if (Instruction *I = moveAddAfterMinMax(II, Builder))
1212       return I;
1213 
1214     // smax(X, -X) --> abs(X)
1215     // smin(X, -X) --> -abs(X)
1216     // umax(X, -X) --> -abs(X)
1217     // umin(X, -X) --> abs(X)
1218     if (isKnownNegation(I0, I1)) {
1219       // We can choose either operand as the input to abs(), but if we can
1220       // eliminate the only use of a value, that's better for subsequent
1221       // transforms/analysis.
1222       if (I0->hasOneUse() && !I1->hasOneUse())
1223         std::swap(I0, I1);
1224 
1225       // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1226       // operation and potentially its negation.
1227       bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1228       Value *Abs = Builder.CreateBinaryIntrinsic(
1229           Intrinsic::abs, I0,
1230           ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1231 
1232       // We don't have a "nabs" intrinsic, so negate if needed based on the
1233       // max/min operation.
1234       if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1235         Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1236       return replaceInstUsesWith(CI, Abs);
1237     }
1238 
1239     if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1240       return Sel;
1241 
1242     if (Instruction *SAdd = matchSAddSubSat(*II))
1243       return SAdd;
1244 
1245     if (match(I1, m_ImmConstant()))
1246       if (auto *Sel = dyn_cast<SelectInst>(I0))
1247         if (Instruction *R = FoldOpIntoSelect(*II, Sel))
1248           return R;
1249 
1250     if (Instruction *NewMinMax = reassociateMinMaxWithConstants(II))
1251       return NewMinMax;
1252 
1253     if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1254        return NewMinMax;
1255 
1256     break;
1257   }
1258   case Intrinsic::bswap: {
1259     Value *IIOperand = II->getArgOperand(0);
1260     Value *X = nullptr;
1261 
1262     KnownBits Known = computeKnownBits(IIOperand, 0, II);
1263     uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1264     uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1265 
1266     // bswap(x) -> shift(x) if x has exactly one "active byte"
1267     if (Known.getBitWidth() - LZ - TZ == 8) {
1268       assert(LZ != TZ && "active byte cannot be in the middle");
1269       if (LZ > TZ)  // -> shl(x) if the "active byte" is in the low part of x
1270         return BinaryOperator::CreateNUWShl(
1271             IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1272       // -> lshr(x) if the "active byte" is in the high part of x
1273       return BinaryOperator::CreateExactLShr(
1274             IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1275     }
1276 
1277     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1278     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1279       unsigned C = X->getType()->getScalarSizeInBits() -
1280                    IIOperand->getType()->getScalarSizeInBits();
1281       Value *CV = ConstantInt::get(X->getType(), C);
1282       Value *V = Builder.CreateLShr(X, CV);
1283       return new TruncInst(V, IIOperand->getType());
1284     }
1285     break;
1286   }
1287   case Intrinsic::masked_load:
1288     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1289       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1290     break;
1291   case Intrinsic::masked_store:
1292     return simplifyMaskedStore(*II);
1293   case Intrinsic::masked_gather:
1294     return simplifyMaskedGather(*II);
1295   case Intrinsic::masked_scatter:
1296     return simplifyMaskedScatter(*II);
1297   case Intrinsic::launder_invariant_group:
1298   case Intrinsic::strip_invariant_group:
1299     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1300       return replaceInstUsesWith(*II, SkippedBarrier);
1301     break;
1302   case Intrinsic::powi:
1303     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1304       // 0 and 1 are handled in instsimplify
1305       // powi(x, -1) -> 1/x
1306       if (Power->isMinusOne())
1307         return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1308                                              II->getArgOperand(0), II);
1309       // powi(x, 2) -> x*x
1310       if (Power->equalsInt(2))
1311         return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),
1312                                              II->getArgOperand(0), II);
1313 
1314       if (!Power->getValue()[0]) {
1315         Value *X;
1316         // If power is even:
1317         // powi(-x, p) -> powi(x, p)
1318         // powi(fabs(x), p) -> powi(x, p)
1319         // powi(copysign(x, y), p) -> powi(x, p)
1320         if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1321             match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1322             match(II->getArgOperand(0),
1323                   m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1324           return replaceOperand(*II, 0, X);
1325       }
1326     }
1327     break;
1328 
1329   case Intrinsic::cttz:
1330   case Intrinsic::ctlz:
1331     if (auto *I = foldCttzCtlz(*II, *this))
1332       return I;
1333     break;
1334 
1335   case Intrinsic::ctpop:
1336     if (auto *I = foldCtpop(*II, *this))
1337       return I;
1338     break;
1339 
1340   case Intrinsic::fshl:
1341   case Intrinsic::fshr: {
1342     Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1343     Type *Ty = II->getType();
1344     unsigned BitWidth = Ty->getScalarSizeInBits();
1345     Constant *ShAmtC;
1346     if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) &&
1347         !ShAmtC->containsConstantExpression()) {
1348       // Canonicalize a shift amount constant operand to modulo the bit-width.
1349       Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1350       Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1351       if (ModuloC != ShAmtC)
1352         return replaceOperand(*II, 2, ModuloC);
1353 
1354       assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1355                  ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1356              "Shift amount expected to be modulo bitwidth");
1357 
1358       // Canonicalize funnel shift right by constant to funnel shift left. This
1359       // is not entirely arbitrary. For historical reasons, the backend may
1360       // recognize rotate left patterns but miss rotate right patterns.
1361       if (IID == Intrinsic::fshr) {
1362         // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1363         Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1364         Module *Mod = II->getModule();
1365         Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1366         return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1367       }
1368       assert(IID == Intrinsic::fshl &&
1369              "All funnel shifts by simple constants should go left");
1370 
1371       // fshl(X, 0, C) --> shl X, C
1372       // fshl(X, undef, C) --> shl X, C
1373       if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1374         return BinaryOperator::CreateShl(Op0, ShAmtC);
1375 
1376       // fshl(0, X, C) --> lshr X, (BW-C)
1377       // fshl(undef, X, C) --> lshr X, (BW-C)
1378       if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1379         return BinaryOperator::CreateLShr(Op1,
1380                                           ConstantExpr::getSub(WidthC, ShAmtC));
1381 
1382       // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1383       if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1384         Module *Mod = II->getModule();
1385         Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1386         return CallInst::Create(Bswap, { Op0 });
1387       }
1388     }
1389 
1390     // Left or right might be masked.
1391     if (SimplifyDemandedInstructionBits(*II))
1392       return &CI;
1393 
1394     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1395     // so only the low bits of the shift amount are demanded if the bitwidth is
1396     // a power-of-2.
1397     if (!isPowerOf2_32(BitWidth))
1398       break;
1399     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1400     KnownBits Op2Known(BitWidth);
1401     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1402       return &CI;
1403     break;
1404   }
1405   case Intrinsic::uadd_with_overflow:
1406   case Intrinsic::sadd_with_overflow: {
1407     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1408       return I;
1409 
1410     // Given 2 constant operands whose sum does not overflow:
1411     // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1412     // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1413     Value *X;
1414     const APInt *C0, *C1;
1415     Value *Arg0 = II->getArgOperand(0);
1416     Value *Arg1 = II->getArgOperand(1);
1417     bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1418     bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1419                              : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1420     if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1421       bool Overflow;
1422       APInt NewC =
1423           IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1424       if (!Overflow)
1425         return replaceInstUsesWith(
1426             *II, Builder.CreateBinaryIntrinsic(
1427                      IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1428     }
1429     break;
1430   }
1431 
1432   case Intrinsic::umul_with_overflow:
1433   case Intrinsic::smul_with_overflow:
1434   case Intrinsic::usub_with_overflow:
1435     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1436       return I;
1437     break;
1438 
1439   case Intrinsic::ssub_with_overflow: {
1440     if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1441       return I;
1442 
1443     Constant *C;
1444     Value *Arg0 = II->getArgOperand(0);
1445     Value *Arg1 = II->getArgOperand(1);
1446     // Given a constant C that is not the minimum signed value
1447     // for an integer of a given bit width:
1448     //
1449     // ssubo X, C -> saddo X, -C
1450     if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1451       Value *NegVal = ConstantExpr::getNeg(C);
1452       // Build a saddo call that is equivalent to the discovered
1453       // ssubo call.
1454       return replaceInstUsesWith(
1455           *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1456                                              Arg0, NegVal));
1457     }
1458 
1459     break;
1460   }
1461 
1462   case Intrinsic::uadd_sat:
1463   case Intrinsic::sadd_sat:
1464   case Intrinsic::usub_sat:
1465   case Intrinsic::ssub_sat: {
1466     SaturatingInst *SI = cast<SaturatingInst>(II);
1467     Type *Ty = SI->getType();
1468     Value *Arg0 = SI->getLHS();
1469     Value *Arg1 = SI->getRHS();
1470 
1471     // Make use of known overflow information.
1472     OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1473                                         Arg0, Arg1, SI);
1474     switch (OR) {
1475       case OverflowResult::MayOverflow:
1476         break;
1477       case OverflowResult::NeverOverflows:
1478         if (SI->isSigned())
1479           return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1480         else
1481           return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1482       case OverflowResult::AlwaysOverflowsLow: {
1483         unsigned BitWidth = Ty->getScalarSizeInBits();
1484         APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1485         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1486       }
1487       case OverflowResult::AlwaysOverflowsHigh: {
1488         unsigned BitWidth = Ty->getScalarSizeInBits();
1489         APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1490         return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1491       }
1492     }
1493 
1494     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1495     Constant *C;
1496     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
1497         C->isNotMinSignedValue()) {
1498       Value *NegVal = ConstantExpr::getNeg(C);
1499       return replaceInstUsesWith(
1500           *II, Builder.CreateBinaryIntrinsic(
1501               Intrinsic::sadd_sat, Arg0, NegVal));
1502     }
1503 
1504     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
1505     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
1506     // if Val and Val2 have the same sign
1507     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
1508       Value *X;
1509       const APInt *Val, *Val2;
1510       APInt NewVal;
1511       bool IsUnsigned =
1512           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
1513       if (Other->getIntrinsicID() == IID &&
1514           match(Arg1, m_APInt(Val)) &&
1515           match(Other->getArgOperand(0), m_Value(X)) &&
1516           match(Other->getArgOperand(1), m_APInt(Val2))) {
1517         if (IsUnsigned)
1518           NewVal = Val->uadd_sat(*Val2);
1519         else if (Val->isNonNegative() == Val2->isNonNegative()) {
1520           bool Overflow;
1521           NewVal = Val->sadd_ov(*Val2, Overflow);
1522           if (Overflow) {
1523             // Both adds together may add more than SignedMaxValue
1524             // without saturating the final result.
1525             break;
1526           }
1527         } else {
1528           // Cannot fold saturated addition with different signs.
1529           break;
1530         }
1531 
1532         return replaceInstUsesWith(
1533             *II, Builder.CreateBinaryIntrinsic(
1534                      IID, X, ConstantInt::get(II->getType(), NewVal)));
1535       }
1536     }
1537     break;
1538   }
1539 
1540   case Intrinsic::minnum:
1541   case Intrinsic::maxnum:
1542   case Intrinsic::minimum:
1543   case Intrinsic::maximum: {
1544     Value *Arg0 = II->getArgOperand(0);
1545     Value *Arg1 = II->getArgOperand(1);
1546     Value *X, *Y;
1547     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
1548         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
1549       // If both operands are negated, invert the call and negate the result:
1550       // min(-X, -Y) --> -(max(X, Y))
1551       // max(-X, -Y) --> -(min(X, Y))
1552       Intrinsic::ID NewIID;
1553       switch (IID) {
1554       case Intrinsic::maxnum:
1555         NewIID = Intrinsic::minnum;
1556         break;
1557       case Intrinsic::minnum:
1558         NewIID = Intrinsic::maxnum;
1559         break;
1560       case Intrinsic::maximum:
1561         NewIID = Intrinsic::minimum;
1562         break;
1563       case Intrinsic::minimum:
1564         NewIID = Intrinsic::maximum;
1565         break;
1566       default:
1567         llvm_unreachable("unexpected intrinsic ID");
1568       }
1569       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
1570       Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
1571       FNeg->copyIRFlags(II);
1572       return FNeg;
1573     }
1574 
1575     // m(m(X, C2), C1) -> m(X, C)
1576     const APFloat *C1, *C2;
1577     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
1578       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
1579           ((match(M->getArgOperand(0), m_Value(X)) &&
1580             match(M->getArgOperand(1), m_APFloat(C2))) ||
1581            (match(M->getArgOperand(1), m_Value(X)) &&
1582             match(M->getArgOperand(0), m_APFloat(C2))))) {
1583         APFloat Res(0.0);
1584         switch (IID) {
1585         case Intrinsic::maxnum:
1586           Res = maxnum(*C1, *C2);
1587           break;
1588         case Intrinsic::minnum:
1589           Res = minnum(*C1, *C2);
1590           break;
1591         case Intrinsic::maximum:
1592           Res = maximum(*C1, *C2);
1593           break;
1594         case Intrinsic::minimum:
1595           Res = minimum(*C1, *C2);
1596           break;
1597         default:
1598           llvm_unreachable("unexpected intrinsic ID");
1599         }
1600         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
1601             IID, X, ConstantFP::get(Arg0->getType(), Res), II);
1602         // TODO: Conservatively intersecting FMF. If Res == C2, the transform
1603         //       was a simplification (so Arg0 and its original flags could
1604         //       propagate?)
1605         NewCall->andIRFlags(M);
1606         return replaceInstUsesWith(*II, NewCall);
1607       }
1608     }
1609 
1610     // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
1611     if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
1612         match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
1613         X->getType() == Y->getType()) {
1614       Value *NewCall =
1615           Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
1616       return new FPExtInst(NewCall, II->getType());
1617     }
1618 
1619     // max X, -X --> fabs X
1620     // min X, -X --> -(fabs X)
1621     // TODO: Remove one-use limitation? That is obviously better for max.
1622     //       It would be an extra instruction for min (fnabs), but that is
1623     //       still likely better for analysis and codegen.
1624     if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
1625         (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
1626       Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
1627       if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
1628         R = Builder.CreateFNegFMF(R, II);
1629       return replaceInstUsesWith(*II, R);
1630     }
1631 
1632     break;
1633   }
1634   case Intrinsic::fmuladd: {
1635     // Canonicalize fast fmuladd to the separate fmul + fadd.
1636     if (II->isFast()) {
1637       BuilderTy::FastMathFlagGuard Guard(Builder);
1638       Builder.setFastMathFlags(II->getFastMathFlags());
1639       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
1640                                       II->getArgOperand(1));
1641       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
1642       Add->takeName(II);
1643       return replaceInstUsesWith(*II, Add);
1644     }
1645 
1646     // Try to simplify the underlying FMul.
1647     if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
1648                                     II->getFastMathFlags(),
1649                                     SQ.getWithInstruction(II))) {
1650       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1651       FAdd->copyFastMathFlags(II);
1652       return FAdd;
1653     }
1654 
1655     LLVM_FALLTHROUGH;
1656   }
1657   case Intrinsic::fma: {
1658     // fma fneg(x), fneg(y), z -> fma x, y, z
1659     Value *Src0 = II->getArgOperand(0);
1660     Value *Src1 = II->getArgOperand(1);
1661     Value *X, *Y;
1662     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
1663       replaceOperand(*II, 0, X);
1664       replaceOperand(*II, 1, Y);
1665       return II;
1666     }
1667 
1668     // fma fabs(x), fabs(x), z -> fma x, x, z
1669     if (match(Src0, m_FAbs(m_Value(X))) &&
1670         match(Src1, m_FAbs(m_Specific(X)))) {
1671       replaceOperand(*II, 0, X);
1672       replaceOperand(*II, 1, X);
1673       return II;
1674     }
1675 
1676     // Try to simplify the underlying FMul. We can only apply simplifications
1677     // that do not require rounding.
1678     if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
1679                                    II->getFastMathFlags(),
1680                                    SQ.getWithInstruction(II))) {
1681       auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
1682       FAdd->copyFastMathFlags(II);
1683       return FAdd;
1684     }
1685 
1686     // fma x, y, 0 -> fmul x, y
1687     // This is always valid for -0.0, but requires nsz for +0.0 as
1688     // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
1689     if (match(II->getArgOperand(2), m_NegZeroFP()) ||
1690         (match(II->getArgOperand(2), m_PosZeroFP()) &&
1691          II->getFastMathFlags().noSignedZeros()))
1692       return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
1693 
1694     break;
1695   }
1696   case Intrinsic::copysign: {
1697     Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
1698     if (SignBitMustBeZero(Sign, &TLI)) {
1699       // If we know that the sign argument is positive, reduce to FABS:
1700       // copysign Mag, +Sign --> fabs Mag
1701       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1702       return replaceInstUsesWith(*II, Fabs);
1703     }
1704     // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
1705     const APFloat *C;
1706     if (match(Sign, m_APFloat(C)) && C->isNegative()) {
1707       // If we know that the sign argument is negative, reduce to FNABS:
1708       // copysign Mag, -Sign --> fneg (fabs Mag)
1709       Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
1710       return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
1711     }
1712 
1713     // Propagate sign argument through nested calls:
1714     // copysign Mag, (copysign ?, X) --> copysign Mag, X
1715     Value *X;
1716     if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
1717       return replaceOperand(*II, 1, X);
1718 
1719     // Peek through changes of magnitude's sign-bit. This call rewrites those:
1720     // copysign (fabs X), Sign --> copysign X, Sign
1721     // copysign (fneg X), Sign --> copysign X, Sign
1722     if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
1723       return replaceOperand(*II, 0, X);
1724 
1725     break;
1726   }
1727   case Intrinsic::fabs: {
1728     Value *Cond, *TVal, *FVal;
1729     if (match(II->getArgOperand(0),
1730               m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
1731       // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
1732       if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
1733         CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
1734         CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
1735         return SelectInst::Create(Cond, AbsT, AbsF);
1736       }
1737       // fabs (select Cond, -FVal, FVal) --> fabs FVal
1738       if (match(TVal, m_FNeg(m_Specific(FVal))))
1739         return replaceOperand(*II, 0, FVal);
1740       // fabs (select Cond, TVal, -TVal) --> fabs TVal
1741       if (match(FVal, m_FNeg(m_Specific(TVal))))
1742         return replaceOperand(*II, 0, TVal);
1743     }
1744 
1745     LLVM_FALLTHROUGH;
1746   }
1747   case Intrinsic::ceil:
1748   case Intrinsic::floor:
1749   case Intrinsic::round:
1750   case Intrinsic::roundeven:
1751   case Intrinsic::nearbyint:
1752   case Intrinsic::rint:
1753   case Intrinsic::trunc: {
1754     Value *ExtSrc;
1755     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
1756       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
1757       Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
1758       return new FPExtInst(NarrowII, II->getType());
1759     }
1760     break;
1761   }
1762   case Intrinsic::cos:
1763   case Intrinsic::amdgcn_cos: {
1764     Value *X;
1765     Value *Src = II->getArgOperand(0);
1766     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
1767       // cos(-x) -> cos(x)
1768       // cos(fabs(x)) -> cos(x)
1769       return replaceOperand(*II, 0, X);
1770     }
1771     break;
1772   }
1773   case Intrinsic::sin: {
1774     Value *X;
1775     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
1776       // sin(-x) --> -sin(x)
1777       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
1778       Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
1779       FNeg->copyFastMathFlags(II);
1780       return FNeg;
1781     }
1782     break;
1783   }
1784 
1785   case Intrinsic::arm_neon_vtbl1:
1786   case Intrinsic::aarch64_neon_tbl1:
1787     if (Value *V = simplifyNeonTbl1(*II, Builder))
1788       return replaceInstUsesWith(*II, V);
1789     break;
1790 
1791   case Intrinsic::arm_neon_vmulls:
1792   case Intrinsic::arm_neon_vmullu:
1793   case Intrinsic::aarch64_neon_smull:
1794   case Intrinsic::aarch64_neon_umull: {
1795     Value *Arg0 = II->getArgOperand(0);
1796     Value *Arg1 = II->getArgOperand(1);
1797 
1798     // Handle mul by zero first:
1799     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1800       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1801     }
1802 
1803     // Check for constant LHS & RHS - in this case we just simplify.
1804     bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
1805                  IID == Intrinsic::aarch64_neon_umull);
1806     VectorType *NewVT = cast<VectorType>(II->getType());
1807     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1808       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1809         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1810         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1811 
1812         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1813       }
1814 
1815       // Couldn't simplify - canonicalize constant to the RHS.
1816       std::swap(Arg0, Arg1);
1817     }
1818 
1819     // Handle mul by one:
1820     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1821       if (ConstantInt *Splat =
1822               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1823         if (Splat->isOne())
1824           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1825                                              /*isSigned=*/!Zext);
1826 
1827     break;
1828   }
1829   case Intrinsic::arm_neon_aesd:
1830   case Intrinsic::arm_neon_aese:
1831   case Intrinsic::aarch64_crypto_aesd:
1832   case Intrinsic::aarch64_crypto_aese: {
1833     Value *DataArg = II->getArgOperand(0);
1834     Value *KeyArg  = II->getArgOperand(1);
1835 
1836     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
1837     Value *Data, *Key;
1838     if (match(KeyArg, m_ZeroInt()) &&
1839         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
1840       replaceOperand(*II, 0, Data);
1841       replaceOperand(*II, 1, Key);
1842       return II;
1843     }
1844     break;
1845   }
1846   case Intrinsic::hexagon_V6_vandvrt:
1847   case Intrinsic::hexagon_V6_vandvrt_128B: {
1848     // Simplify Q -> V -> Q conversion.
1849     if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1850       Intrinsic::ID ID0 = Op0->getIntrinsicID();
1851       if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
1852           ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
1853         break;
1854       Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
1855       uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
1856       uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
1857       // Check if every byte has common bits in Bytes and Mask.
1858       uint64_t C = Bytes1 & Mask1;
1859       if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
1860         return replaceInstUsesWith(*II, Op0->getArgOperand(0));
1861     }
1862     break;
1863   }
1864   case Intrinsic::stackrestore: {
1865     enum class ClassifyResult {
1866       None,
1867       Alloca,
1868       StackRestore,
1869       CallWithSideEffects,
1870     };
1871     auto Classify = [](const Instruction *I) {
1872       if (isa<AllocaInst>(I))
1873         return ClassifyResult::Alloca;
1874 
1875       if (auto *CI = dyn_cast<CallInst>(I)) {
1876         if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
1877           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1878             return ClassifyResult::StackRestore;
1879 
1880           if (II->mayHaveSideEffects())
1881             return ClassifyResult::CallWithSideEffects;
1882         } else {
1883           // Consider all non-intrinsic calls to be side effects
1884           return ClassifyResult::CallWithSideEffects;
1885         }
1886       }
1887 
1888       return ClassifyResult::None;
1889     };
1890 
1891     // If the stacksave and the stackrestore are in the same BB, and there is
1892     // no intervening call, alloca, or stackrestore of a different stacksave,
1893     // remove the restore. This can happen when variable allocas are DCE'd.
1894     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1895       if (SS->getIntrinsicID() == Intrinsic::stacksave &&
1896           SS->getParent() == II->getParent()) {
1897         BasicBlock::iterator BI(SS);
1898         bool CannotRemove = false;
1899         for (++BI; &*BI != II; ++BI) {
1900           switch (Classify(&*BI)) {
1901           case ClassifyResult::None:
1902             // So far so good, look at next instructions.
1903             break;
1904 
1905           case ClassifyResult::StackRestore:
1906             // If we found an intervening stackrestore for a different
1907             // stacksave, we can't remove the stackrestore. Otherwise, continue.
1908             if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
1909               CannotRemove = true;
1910             break;
1911 
1912           case ClassifyResult::Alloca:
1913           case ClassifyResult::CallWithSideEffects:
1914             // If we found an alloca, a non-intrinsic call, or an intrinsic
1915             // call with side effects, we can't remove the stackrestore.
1916             CannotRemove = true;
1917             break;
1918           }
1919           if (CannotRemove)
1920             break;
1921         }
1922 
1923         if (!CannotRemove)
1924           return eraseInstFromFunction(CI);
1925       }
1926     }
1927 
1928     // Scan down this block to see if there is another stack restore in the
1929     // same block without an intervening call/alloca.
1930     BasicBlock::iterator BI(II);
1931     Instruction *TI = II->getParent()->getTerminator();
1932     bool CannotRemove = false;
1933     for (++BI; &*BI != TI; ++BI) {
1934       switch (Classify(&*BI)) {
1935       case ClassifyResult::None:
1936         // So far so good, look at next instructions.
1937         break;
1938 
1939       case ClassifyResult::StackRestore:
1940         // If there is a stackrestore below this one, remove this one.
1941         return eraseInstFromFunction(CI);
1942 
1943       case ClassifyResult::Alloca:
1944       case ClassifyResult::CallWithSideEffects:
1945         // If we found an alloca, a non-intrinsic call, or an intrinsic call
1946         // with side effects (such as llvm.stacksave and llvm.read_register),
1947         // we can't remove the stack restore.
1948         CannotRemove = true;
1949         break;
1950       }
1951       if (CannotRemove)
1952         break;
1953     }
1954 
1955     // If the stack restore is in a return, resume, or unwind block and if there
1956     // are no allocas or calls between the restore and the return, nuke the
1957     // restore.
1958     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1959       return eraseInstFromFunction(CI);
1960     break;
1961   }
1962   case Intrinsic::lifetime_end:
1963     // Asan needs to poison memory to detect invalid access which is possible
1964     // even for empty lifetime range.
1965     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
1966         II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
1967         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
1968       break;
1969 
1970     if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
1971           return I.getIntrinsicID() == Intrinsic::lifetime_start;
1972         }))
1973       return nullptr;
1974     break;
1975   case Intrinsic::assume: {
1976     Value *IIOperand = II->getArgOperand(0);
1977     SmallVector<OperandBundleDef, 4> OpBundles;
1978     II->getOperandBundlesAsDefs(OpBundles);
1979 
1980     /// This will remove the boolean Condition from the assume given as
1981     /// argument and remove the assume if it becomes useless.
1982     /// always returns nullptr for use as a return values.
1983     auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
1984       assert(isa<AssumeInst>(Assume));
1985       if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
1986         return eraseInstFromFunction(CI);
1987       replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));
1988       return nullptr;
1989     };
1990     // Remove an assume if it is followed by an identical assume.
1991     // TODO: Do we need this? Unless there are conflicting assumptions, the
1992     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
1993     Instruction *Next = II->getNextNonDebugInstruction();
1994     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
1995       return RemoveConditionFromAssume(Next);
1996 
1997     // Canonicalize assume(a && b) -> assume(a); assume(b);
1998     // Note: New assumption intrinsics created here are registered by
1999     // the InstCombineIRInserter object.
2000     FunctionType *AssumeIntrinsicTy = II->getFunctionType();
2001     Value *AssumeIntrinsic = II->getCalledOperand();
2002     Value *A, *B;
2003     if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
2004       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
2005                          II->getName());
2006       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
2007       return eraseInstFromFunction(*II);
2008     }
2009     // assume(!(a || b)) -> assume(!a); assume(!b);
2010     if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
2011       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2012                          Builder.CreateNot(A), OpBundles, II->getName());
2013       Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2014                          Builder.CreateNot(B), II->getName());
2015       return eraseInstFromFunction(*II);
2016     }
2017 
2018     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2019     // (if assume is valid at the load)
2020     CmpInst::Predicate Pred;
2021     Instruction *LHS;
2022     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2023         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2024         LHS->getType()->isPointerTy() &&
2025         isValidAssumeForContext(II, LHS, &DT)) {
2026       MDNode *MD = MDNode::get(II->getContext(), None);
2027       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2028       return RemoveConditionFromAssume(II);
2029 
2030       // TODO: apply nonnull return attributes to calls and invokes
2031       // TODO: apply range metadata for range check patterns?
2032     }
2033 
2034     // Convert nonnull assume like:
2035     // %A = icmp ne i32* %PTR, null
2036     // call void @llvm.assume(i1 %A)
2037     // into
2038     // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
2039     if (EnableKnowledgeRetention &&
2040         match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
2041         Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
2042       if (auto *Replacement = buildAssumeFromKnowledge(
2043               {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2044 
2045         Replacement->insertBefore(Next);
2046         AC.registerAssumption(Replacement);
2047         return RemoveConditionFromAssume(II);
2048       }
2049     }
2050 
2051     // Convert alignment assume like:
2052     // %B = ptrtoint i32* %A to i64
2053     // %C = and i64 %B, Constant
2054     // %D = icmp eq i64 %C, 0
2055     // call void @llvm.assume(i1 %D)
2056     // into
2057     // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64  Constant + 1)]
2058     uint64_t AlignMask;
2059     if (EnableKnowledgeRetention &&
2060         match(IIOperand,
2061               m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2062                     m_Zero())) &&
2063         Pred == CmpInst::ICMP_EQ) {
2064       if (isPowerOf2_64(AlignMask + 1)) {
2065         uint64_t Offset = 0;
2066         match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));
2067         if (match(A, m_PtrToInt(m_Value(A)))) {
2068           /// Note: this doesn't preserve the offset information but merges
2069           /// offset and alignment.
2070           /// TODO: we can generate a GEP instead of merging the alignment with
2071           /// the offset.
2072           RetainedKnowledge RK{Attribute::Alignment,
2073                                (unsigned)MinAlign(Offset, AlignMask + 1), A};
2074           if (auto *Replacement =
2075                   buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2076 
2077             Replacement->insertAfter(II);
2078             AC.registerAssumption(Replacement);
2079           }
2080           return RemoveConditionFromAssume(II);
2081         }
2082       }
2083     }
2084 
2085     /// Canonicalize Knowledge in operand bundles.
2086     if (EnableKnowledgeRetention && II->hasOperandBundles()) {
2087       for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2088         auto &BOI = II->bundle_op_info_begin()[Idx];
2089         RetainedKnowledge RK =
2090           llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2091         if (BOI.End - BOI.Begin > 2)
2092           continue; // Prevent reducing knowledge in an align with offset since
2093                     // extracting a RetainedKnowledge form them looses offset
2094                     // information
2095         RetainedKnowledge CanonRK =
2096           llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2097                                           &getAssumptionCache(),
2098                                           &getDominatorTree());
2099         if (CanonRK == RK)
2100           continue;
2101         if (!CanonRK) {
2102           if (BOI.End - BOI.Begin > 0) {
2103             Worklist.pushValue(II->op_begin()[BOI.Begin]);
2104             Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2105           }
2106           continue;
2107         }
2108         assert(RK.AttrKind == CanonRK.AttrKind);
2109         if (BOI.End - BOI.Begin > 0)
2110           II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2111         if (BOI.End - BOI.Begin > 1)
2112           II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2113               Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2114         if (RK.WasOn)
2115           Worklist.pushValue(RK.WasOn);
2116         return II;
2117       }
2118     }
2119 
2120     // If there is a dominating assume with the same condition as this one,
2121     // then this one is redundant, and should be removed.
2122     KnownBits Known(1);
2123     computeKnownBits(IIOperand, Known, 0, II);
2124     if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2125       return eraseInstFromFunction(*II);
2126 
2127     // Update the cache of affected values for this assumption (we might be
2128     // here because we just simplified the condition).
2129     AC.updateAffectedValues(cast<AssumeInst>(II));
2130     break;
2131   }
2132   case Intrinsic::experimental_guard: {
2133     // Is this guard followed by another guard?  We scan forward over a small
2134     // fixed window of instructions to handle common cases with conditions
2135     // computed between guards.
2136     Instruction *NextInst = II->getNextNonDebugInstruction();
2137     for (unsigned i = 0; i < GuardWideningWindow; i++) {
2138       // Note: Using context-free form to avoid compile time blow up
2139       if (!isSafeToSpeculativelyExecute(NextInst))
2140         break;
2141       NextInst = NextInst->getNextNonDebugInstruction();
2142     }
2143     Value *NextCond = nullptr;
2144     if (match(NextInst,
2145               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
2146       Value *CurrCond = II->getArgOperand(0);
2147 
2148       // Remove a guard that it is immediately preceded by an identical guard.
2149       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
2150       if (CurrCond != NextCond) {
2151         Instruction *MoveI = II->getNextNonDebugInstruction();
2152         while (MoveI != NextInst) {
2153           auto *Temp = MoveI;
2154           MoveI = MoveI->getNextNonDebugInstruction();
2155           Temp->moveBefore(II);
2156         }
2157         replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
2158       }
2159       eraseInstFromFunction(*NextInst);
2160       return II;
2161     }
2162     break;
2163   }
2164   case Intrinsic::experimental_vector_insert: {
2165     Value *Vec = II->getArgOperand(0);
2166     Value *SubVec = II->getArgOperand(1);
2167     Value *Idx = II->getArgOperand(2);
2168     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2169     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2170     auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
2171 
2172     // Only canonicalize if the destination vector, Vec, and SubVec are all
2173     // fixed vectors.
2174     if (DstTy && VecTy && SubVecTy) {
2175       unsigned DstNumElts = DstTy->getNumElements();
2176       unsigned VecNumElts = VecTy->getNumElements();
2177       unsigned SubVecNumElts = SubVecTy->getNumElements();
2178       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2179 
2180       // An insert that entirely overwrites Vec with SubVec is a nop.
2181       if (VecNumElts == SubVecNumElts)
2182         return replaceInstUsesWith(CI, SubVec);
2183 
2184       // Widen SubVec into a vector of the same width as Vec, since
2185       // shufflevector requires the two input vectors to be the same width.
2186       // Elements beyond the bounds of SubVec within the widened vector are
2187       // undefined.
2188       SmallVector<int, 8> WidenMask;
2189       unsigned i;
2190       for (i = 0; i != SubVecNumElts; ++i)
2191         WidenMask.push_back(i);
2192       for (; i != VecNumElts; ++i)
2193         WidenMask.push_back(UndefMaskElem);
2194 
2195       Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
2196 
2197       SmallVector<int, 8> Mask;
2198       for (unsigned i = 0; i != IdxN; ++i)
2199         Mask.push_back(i);
2200       for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
2201         Mask.push_back(i);
2202       for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
2203         Mask.push_back(i);
2204 
2205       Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
2206       return replaceInstUsesWith(CI, Shuffle);
2207     }
2208     break;
2209   }
2210   case Intrinsic::experimental_vector_extract: {
2211     Value *Vec = II->getArgOperand(0);
2212     Value *Idx = II->getArgOperand(1);
2213 
2214     auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2215     auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2216 
2217     // Only canonicalize if the the destination vector and Vec are fixed
2218     // vectors.
2219     if (DstTy && VecTy) {
2220       unsigned DstNumElts = DstTy->getNumElements();
2221       unsigned VecNumElts = VecTy->getNumElements();
2222       unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2223 
2224       // Extracting the entirety of Vec is a nop.
2225       if (VecNumElts == DstNumElts) {
2226         replaceInstUsesWith(CI, Vec);
2227         return eraseInstFromFunction(CI);
2228       }
2229 
2230       SmallVector<int, 8> Mask;
2231       for (unsigned i = 0; i != DstNumElts; ++i)
2232         Mask.push_back(IdxN + i);
2233 
2234       Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
2235       return replaceInstUsesWith(CI, Shuffle);
2236     }
2237     break;
2238   }
2239   case Intrinsic::experimental_vector_reverse: {
2240     Value *BO0, *BO1, *X, *Y;
2241     Value *Vec = II->getArgOperand(0);
2242     if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
2243       auto *OldBinOp = cast<BinaryOperator>(Vec);
2244       if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2245                          m_Value(X)))) {
2246         // rev(binop rev(X), rev(Y)) --> binop X, Y
2247         if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2248                            m_Value(Y))))
2249           return replaceInstUsesWith(CI,
2250                                      BinaryOperator::CreateWithCopiedFlags(
2251                                          OldBinOp->getOpcode(), X, Y, OldBinOp,
2252                                          OldBinOp->getName(), II));
2253         // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
2254         if (isSplatValue(BO1))
2255           return replaceInstUsesWith(CI,
2256                                      BinaryOperator::CreateWithCopiedFlags(
2257                                          OldBinOp->getOpcode(), X, BO1,
2258                                          OldBinOp, OldBinOp->getName(), II));
2259       }
2260       // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
2261       if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2262                          m_Value(Y))) &&
2263           isSplatValue(BO0))
2264         return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(
2265                                            OldBinOp->getOpcode(), BO0, Y,
2266                                            OldBinOp, OldBinOp->getName(), II));
2267     }
2268     // rev(unop rev(X)) --> unop X
2269     if (match(Vec, m_OneUse(m_UnOp(
2270                        m_Intrinsic<Intrinsic::experimental_vector_reverse>(
2271                            m_Value(X)))))) {
2272       auto *OldUnOp = cast<UnaryOperator>(Vec);
2273       auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
2274           OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
2275       return replaceInstUsesWith(CI, NewUnOp);
2276     }
2277     break;
2278   }
2279   case Intrinsic::vector_reduce_or:
2280   case Intrinsic::vector_reduce_and: {
2281     // Canonicalize logical or/and reductions:
2282     // Or reduction for i1 is represented as:
2283     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2284     // %res = cmp ne iReduxWidth %val, 0
2285     // And reduction for i1 is represented as:
2286     // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2287     // %res = cmp eq iReduxWidth %val, 11111
2288     Value *Arg = II->getArgOperand(0);
2289     Value *Vect;
2290     if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2291       if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2292         if (FTy->getElementType() == Builder.getInt1Ty()) {
2293           Value *Res = Builder.CreateBitCast(
2294               Vect, Builder.getIntNTy(FTy->getNumElements()));
2295           if (IID == Intrinsic::vector_reduce_and) {
2296             Res = Builder.CreateICmpEQ(
2297                 Res, ConstantInt::getAllOnesValue(Res->getType()));
2298           } else {
2299             assert(IID == Intrinsic::vector_reduce_or &&
2300                    "Expected or reduction.");
2301             Res = Builder.CreateIsNotNull(Res);
2302           }
2303           if (Arg != Vect)
2304             Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2305                                      II->getType());
2306           return replaceInstUsesWith(CI, Res);
2307         }
2308     }
2309     LLVM_FALLTHROUGH;
2310   }
2311   case Intrinsic::vector_reduce_add: {
2312     if (IID == Intrinsic::vector_reduce_add) {
2313       // Convert vector_reduce_add(ZExt(<n x i1>)) to
2314       // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2315       // Convert vector_reduce_add(SExt(<n x i1>)) to
2316       // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2317       // Convert vector_reduce_add(<n x i1>) to
2318       // Trunc(ctpop(bitcast <n x i1> to in)).
2319       Value *Arg = II->getArgOperand(0);
2320       Value *Vect;
2321       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2322         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2323           if (FTy->getElementType() == Builder.getInt1Ty()) {
2324             Value *V = Builder.CreateBitCast(
2325                 Vect, Builder.getIntNTy(FTy->getNumElements()));
2326             Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
2327             if (Res->getType() != II->getType())
2328               Res = Builder.CreateZExtOrTrunc(Res, II->getType());
2329             if (Arg != Vect &&
2330                 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
2331               Res = Builder.CreateNeg(Res);
2332             return replaceInstUsesWith(CI, Res);
2333           }
2334       }
2335     }
2336     LLVM_FALLTHROUGH;
2337   }
2338   case Intrinsic::vector_reduce_xor: {
2339     if (IID == Intrinsic::vector_reduce_xor) {
2340       // Exclusive disjunction reduction over the vector with
2341       // (potentially-extended) i1 element type is actually a
2342       // (potentially-extended) arithmetic `add` reduction over the original
2343       // non-extended value:
2344       //   vector_reduce_xor(?ext(<n x i1>))
2345       //     -->
2346       //   ?ext(vector_reduce_add(<n x i1>))
2347       Value *Arg = II->getArgOperand(0);
2348       Value *Vect;
2349       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2350         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2351           if (FTy->getElementType() == Builder.getInt1Ty()) {
2352             Value *Res = Builder.CreateAddReduce(Vect);
2353             if (Arg != Vect)
2354               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2355                                        II->getType());
2356             return replaceInstUsesWith(CI, Res);
2357           }
2358       }
2359     }
2360     LLVM_FALLTHROUGH;
2361   }
2362   case Intrinsic::vector_reduce_mul: {
2363     if (IID == Intrinsic::vector_reduce_mul) {
2364       // Multiplicative reduction over the vector with (potentially-extended)
2365       // i1 element type is actually a (potentially zero-extended)
2366       // logical `and` reduction over the original non-extended value:
2367       //   vector_reduce_mul(?ext(<n x i1>))
2368       //     -->
2369       //   zext(vector_reduce_and(<n x i1>))
2370       Value *Arg = II->getArgOperand(0);
2371       Value *Vect;
2372       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2373         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2374           if (FTy->getElementType() == Builder.getInt1Ty()) {
2375             Value *Res = Builder.CreateAndReduce(Vect);
2376             if (Res->getType() != II->getType())
2377               Res = Builder.CreateZExt(Res, II->getType());
2378             return replaceInstUsesWith(CI, Res);
2379           }
2380       }
2381     }
2382     LLVM_FALLTHROUGH;
2383   }
2384   case Intrinsic::vector_reduce_umin:
2385   case Intrinsic::vector_reduce_umax: {
2386     if (IID == Intrinsic::vector_reduce_umin ||
2387         IID == Intrinsic::vector_reduce_umax) {
2388       // UMin/UMax reduction over the vector with (potentially-extended)
2389       // i1 element type is actually a (potentially-extended)
2390       // logical `and`/`or` reduction over the original non-extended value:
2391       //   vector_reduce_u{min,max}(?ext(<n x i1>))
2392       //     -->
2393       //   ?ext(vector_reduce_{and,or}(<n x i1>))
2394       Value *Arg = II->getArgOperand(0);
2395       Value *Vect;
2396       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2397         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2398           if (FTy->getElementType() == Builder.getInt1Ty()) {
2399             Value *Res = IID == Intrinsic::vector_reduce_umin
2400                              ? Builder.CreateAndReduce(Vect)
2401                              : Builder.CreateOrReduce(Vect);
2402             if (Arg != Vect)
2403               Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2404                                        II->getType());
2405             return replaceInstUsesWith(CI, Res);
2406           }
2407       }
2408     }
2409     LLVM_FALLTHROUGH;
2410   }
2411   case Intrinsic::vector_reduce_smin:
2412   case Intrinsic::vector_reduce_smax: {
2413     if (IID == Intrinsic::vector_reduce_smin ||
2414         IID == Intrinsic::vector_reduce_smax) {
2415       // SMin/SMax reduction over the vector with (potentially-extended)
2416       // i1 element type is actually a (potentially-extended)
2417       // logical `and`/`or` reduction over the original non-extended value:
2418       //   vector_reduce_s{min,max}(<n x i1>)
2419       //     -->
2420       //   vector_reduce_{or,and}(<n x i1>)
2421       // and
2422       //   vector_reduce_s{min,max}(sext(<n x i1>))
2423       //     -->
2424       //   sext(vector_reduce_{or,and}(<n x i1>))
2425       // and
2426       //   vector_reduce_s{min,max}(zext(<n x i1>))
2427       //     -->
2428       //   zext(vector_reduce_{and,or}(<n x i1>))
2429       Value *Arg = II->getArgOperand(0);
2430       Value *Vect;
2431       if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2432         if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2433           if (FTy->getElementType() == Builder.getInt1Ty()) {
2434             Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
2435             if (Arg != Vect)
2436               ExtOpc = cast<CastInst>(Arg)->getOpcode();
2437             Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
2438                           (ExtOpc == Instruction::CastOps::ZExt))
2439                              ? Builder.CreateAndReduce(Vect)
2440                              : Builder.CreateOrReduce(Vect);
2441             if (Arg != Vect)
2442               Res = Builder.CreateCast(ExtOpc, Res, II->getType());
2443             return replaceInstUsesWith(CI, Res);
2444           }
2445       }
2446     }
2447     LLVM_FALLTHROUGH;
2448   }
2449   case Intrinsic::vector_reduce_fmax:
2450   case Intrinsic::vector_reduce_fmin:
2451   case Intrinsic::vector_reduce_fadd:
2452   case Intrinsic::vector_reduce_fmul: {
2453     bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
2454                               IID != Intrinsic::vector_reduce_fmul) ||
2455                              II->hasAllowReassoc();
2456     const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
2457                              IID == Intrinsic::vector_reduce_fmul)
2458                                 ? 1
2459                                 : 0;
2460     Value *Arg = II->getArgOperand(ArgIdx);
2461     Value *V;
2462     ArrayRef<int> Mask;
2463     if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
2464         !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
2465         !cast<ShuffleVectorInst>(Arg)->isSingleSource())
2466       break;
2467     int Sz = Mask.size();
2468     SmallBitVector UsedIndices(Sz);
2469     for (int Idx : Mask) {
2470       if (Idx == UndefMaskElem || UsedIndices.test(Idx))
2471         break;
2472       UsedIndices.set(Idx);
2473     }
2474     // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
2475     // other changes.
2476     if (UsedIndices.all()) {
2477       replaceUse(II->getOperandUse(ArgIdx), V);
2478       return nullptr;
2479     }
2480     break;
2481   }
2482   default: {
2483     // Handle target specific intrinsics
2484     Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
2485     if (V.hasValue())
2486       return V.getValue();
2487     break;
2488   }
2489   }
2490   // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
2491   // context, so it is handled in visitCallBase and we should trigger it.
2492   return visitCallBase(*II);
2493 }
2494 
2495 // Fence instruction simplification
2496 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
2497   auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
2498   // This check is solely here to handle arbitrary target-dependent syncscopes.
2499   // TODO: Can remove if does not matter in practice.
2500   if (NFI && FI.isIdenticalTo(NFI))
2501     return eraseInstFromFunction(FI);
2502 
2503   // Returns true if FI1 is identical or stronger fence than FI2.
2504   auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
2505     auto FI1SyncScope = FI1->getSyncScopeID();
2506     // Consider same scope, where scope is global or single-thread.
2507     if (FI1SyncScope != FI2->getSyncScopeID() ||
2508         (FI1SyncScope != SyncScope::System &&
2509          FI1SyncScope != SyncScope::SingleThread))
2510       return false;
2511 
2512     return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
2513   };
2514   if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
2515     return eraseInstFromFunction(FI);
2516 
2517   if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
2518     if (isIdenticalOrStrongerFence(PFI, &FI))
2519       return eraseInstFromFunction(FI);
2520   return nullptr;
2521 }
2522 
2523 // InvokeInst simplification
2524 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
2525   return visitCallBase(II);
2526 }
2527 
2528 // CallBrInst simplification
2529 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
2530   return visitCallBase(CBI);
2531 }
2532 
2533 /// If this cast does not affect the value passed through the varargs area, we
2534 /// can eliminate the use of the cast.
2535 static bool isSafeToEliminateVarargsCast(const CallBase &Call,
2536                                          const DataLayout &DL,
2537                                          const CastInst *const CI,
2538                                          const int ix) {
2539   if (!CI->isLosslessCast())
2540     return false;
2541 
2542   // If this is a GC intrinsic, avoid munging types.  We need types for
2543   // statepoint reconstruction in SelectionDAG.
2544   // TODO: This is probably something which should be expanded to all
2545   // intrinsics since the entire point of intrinsics is that
2546   // they are understandable by the optimizer.
2547   if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
2548       isa<GCResultInst>(Call))
2549     return false;
2550 
2551   // Opaque pointers are compatible with any byval types.
2552   PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType());
2553   if (SrcTy->isOpaque())
2554     return true;
2555 
2556   // The size of ByVal or InAlloca arguments is derived from the type, so we
2557   // can't change to a type with a different size.  If the size were
2558   // passed explicitly we could avoid this check.
2559   if (!Call.isPassPointeeByValueArgument(ix))
2560     return true;
2561 
2562   // The transform currently only handles type replacement for byval, not other
2563   // type-carrying attributes.
2564   if (!Call.isByValArgument(ix))
2565     return false;
2566 
2567   Type *SrcElemTy = SrcTy->getNonOpaquePointerElementType();
2568   Type *DstElemTy = Call.getParamByValType(ix);
2569   if (!SrcElemTy->isSized() || !DstElemTy->isSized())
2570     return false;
2571   if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy))
2572     return false;
2573   return true;
2574 }
2575 
2576 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
2577   if (!CI->getCalledFunction()) return nullptr;
2578 
2579   // Skip optimizing notail and musttail calls so
2580   // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
2581   // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
2582   if (CI->isMustTailCall() || CI->isNoTailCall())
2583     return nullptr;
2584 
2585   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2586     replaceInstUsesWith(*From, With);
2587   };
2588   auto InstCombineErase = [this](Instruction *I) {
2589     eraseInstFromFunction(*I);
2590   };
2591   LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
2592                                InstCombineErase);
2593   if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
2594     ++NumSimplified;
2595     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2596   }
2597 
2598   return nullptr;
2599 }
2600 
2601 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2602   // Strip off at most one level of pointer casts, looking for an alloca.  This
2603   // is good enough in practice and simpler than handling any number of casts.
2604   Value *Underlying = TrampMem->stripPointerCasts();
2605   if (Underlying != TrampMem &&
2606       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2607     return nullptr;
2608   if (!isa<AllocaInst>(Underlying))
2609     return nullptr;
2610 
2611   IntrinsicInst *InitTrampoline = nullptr;
2612   for (User *U : TrampMem->users()) {
2613     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2614     if (!II)
2615       return nullptr;
2616     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2617       if (InitTrampoline)
2618         // More than one init_trampoline writes to this value.  Give up.
2619         return nullptr;
2620       InitTrampoline = II;
2621       continue;
2622     }
2623     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2624       // Allow any number of calls to adjust.trampoline.
2625       continue;
2626     return nullptr;
2627   }
2628 
2629   // No call to init.trampoline found.
2630   if (!InitTrampoline)
2631     return nullptr;
2632 
2633   // Check that the alloca is being used in the expected way.
2634   if (InitTrampoline->getOperand(0) != TrampMem)
2635     return nullptr;
2636 
2637   return InitTrampoline;
2638 }
2639 
2640 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2641                                                Value *TrampMem) {
2642   // Visit all the previous instructions in the basic block, and try to find a
2643   // init.trampoline which has a direct path to the adjust.trampoline.
2644   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2645                             E = AdjustTramp->getParent()->begin();
2646        I != E;) {
2647     Instruction *Inst = &*--I;
2648     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2649       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2650           II->getOperand(0) == TrampMem)
2651         return II;
2652     if (Inst->mayWriteToMemory())
2653       return nullptr;
2654   }
2655   return nullptr;
2656 }
2657 
2658 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2659 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2660 // to a direct call to a function.  Otherwise return NULL.
2661 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2662   Callee = Callee->stripPointerCasts();
2663   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2664   if (!AdjustTramp ||
2665       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2666     return nullptr;
2667 
2668   Value *TrampMem = AdjustTramp->getOperand(0);
2669 
2670   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2671     return IT;
2672   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2673     return IT;
2674   return nullptr;
2675 }
2676 
2677 void InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
2678   // Note: We only handle cases which can't be driven from generic attributes
2679   // here.  So, for example, nonnull and noalias (which are common properties
2680   // of some allocation functions) are expected to be handled via annotation
2681   // of the respective allocator declaration with generic attributes.
2682 
2683   uint64_t Size;
2684   ObjectSizeOpts Opts;
2685   if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) {
2686     // TODO: We really should just emit deref_or_null here and then
2687     // let the generic inference code combine that with nonnull.
2688     if (Call.hasRetAttr(Attribute::NonNull))
2689       Call.addRetAttr(Attribute::getWithDereferenceableBytes(
2690           Call.getContext(), Size));
2691     else
2692       Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(
2693           Call.getContext(), Size));
2694   }
2695 
2696   // Add alignment attribute if alignment is a power of two constant.
2697   Value *Alignment = getAllocAlignment(&Call, TLI);
2698   if (!Alignment)
2699     return;
2700 
2701   ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
2702   if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
2703     uint64_t AlignmentVal = AlignOpC->getZExtValue();
2704     if (llvm::isPowerOf2_64(AlignmentVal)) {
2705       Call.removeRetAttr(Attribute::Alignment);
2706       Call.addRetAttr(Attribute::getWithAlignment(Call.getContext(),
2707                                                   Align(AlignmentVal)));
2708     }
2709   }
2710 }
2711 
2712 /// Improvements for call, callbr and invoke instructions.
2713 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
2714   if (isAllocationFn(&Call, &TLI))
2715     annotateAnyAllocSite(Call, &TLI);
2716 
2717   bool Changed = false;
2718 
2719   // Mark any parameters that are known to be non-null with the nonnull
2720   // attribute.  This is helpful for inlining calls to functions with null
2721   // checks on their arguments.
2722   SmallVector<unsigned, 4> ArgNos;
2723   unsigned ArgNo = 0;
2724 
2725   for (Value *V : Call.args()) {
2726     if (V->getType()->isPointerTy() &&
2727         !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
2728         isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
2729       ArgNos.push_back(ArgNo);
2730     ArgNo++;
2731   }
2732 
2733   assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
2734 
2735   if (!ArgNos.empty()) {
2736     AttributeList AS = Call.getAttributes();
2737     LLVMContext &Ctx = Call.getContext();
2738     AS = AS.addParamAttribute(Ctx, ArgNos,
2739                               Attribute::get(Ctx, Attribute::NonNull));
2740     Call.setAttributes(AS);
2741     Changed = true;
2742   }
2743 
2744   // If the callee is a pointer to a function, attempt to move any casts to the
2745   // arguments of the call/callbr/invoke.
2746   Value *Callee = Call.getCalledOperand();
2747   if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
2748     return nullptr;
2749 
2750   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2751     // Remove the convergent attr on calls when the callee is not convergent.
2752     if (Call.isConvergent() && !CalleeF->isConvergent() &&
2753         !CalleeF->isIntrinsic()) {
2754       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
2755                         << "\n");
2756       Call.setNotConvergent();
2757       return &Call;
2758     }
2759 
2760     // If the call and callee calling conventions don't match, and neither one
2761     // of the calling conventions is compatible with C calling convention
2762     // this call must be unreachable, as the call is undefined.
2763     if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
2764          !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
2765            TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&
2766          !(Call.getCallingConv() == llvm::CallingConv::C &&
2767            TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&
2768         // Only do this for calls to a function with a body.  A prototype may
2769         // not actually end up matching the implementation's calling conv for a
2770         // variety of reasons (e.g. it may be written in assembly).
2771         !CalleeF->isDeclaration()) {
2772       Instruction *OldCall = &Call;
2773       CreateNonTerminatorUnreachable(OldCall);
2774       // If OldCall does not return void then replaceInstUsesWith poison.
2775       // This allows ValueHandlers and custom metadata to adjust itself.
2776       if (!OldCall->getType()->isVoidTy())
2777         replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
2778       if (isa<CallInst>(OldCall))
2779         return eraseInstFromFunction(*OldCall);
2780 
2781       // We cannot remove an invoke or a callbr, because it would change thexi
2782       // CFG, just change the callee to a null pointer.
2783       cast<CallBase>(OldCall)->setCalledFunction(
2784           CalleeF->getFunctionType(),
2785           Constant::getNullValue(CalleeF->getType()));
2786       return nullptr;
2787     }
2788   }
2789 
2790   // Calling a null function pointer is undefined if a null address isn't
2791   // dereferenceable.
2792   if ((isa<ConstantPointerNull>(Callee) &&
2793        !NullPointerIsDefined(Call.getFunction())) ||
2794       isa<UndefValue>(Callee)) {
2795     // If Call does not return void then replaceInstUsesWith poison.
2796     // This allows ValueHandlers and custom metadata to adjust itself.
2797     if (!Call.getType()->isVoidTy())
2798       replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
2799 
2800     if (Call.isTerminator()) {
2801       // Can't remove an invoke or callbr because we cannot change the CFG.
2802       return nullptr;
2803     }
2804 
2805     // This instruction is not reachable, just remove it.
2806     CreateNonTerminatorUnreachable(&Call);
2807     return eraseInstFromFunction(Call);
2808   }
2809 
2810   if (IntrinsicInst *II = findInitTrampoline(Callee))
2811     return transformCallThroughTrampoline(Call, *II);
2812 
2813   // TODO: Drop this transform once opaque pointer transition is done.
2814   FunctionType *FTy = Call.getFunctionType();
2815   if (FTy->isVarArg()) {
2816     int ix = FTy->getNumParams();
2817     // See if we can optimize any arguments passed through the varargs area of
2818     // the call.
2819     for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
2820          I != E; ++I, ++ix) {
2821       CastInst *CI = dyn_cast<CastInst>(*I);
2822       if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
2823         replaceUse(*I, CI->getOperand(0));
2824 
2825         // Update the byval type to match the pointer type.
2826         // Not necessary for opaque pointers.
2827         PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType());
2828         if (!NewTy->isOpaque() && Call.isByValArgument(ix)) {
2829           Call.removeParamAttr(ix, Attribute::ByVal);
2830           Call.addParamAttr(ix, Attribute::getWithByValType(
2831                                     Call.getContext(),
2832                                     NewTy->getNonOpaquePointerElementType()));
2833         }
2834         Changed = true;
2835       }
2836     }
2837   }
2838 
2839   if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
2840     InlineAsm *IA = cast<InlineAsm>(Callee);
2841     if (!IA->canThrow()) {
2842       // Normal inline asm calls cannot throw - mark them
2843       // 'nounwind'.
2844       Call.setDoesNotThrow();
2845       Changed = true;
2846     }
2847   }
2848 
2849   // Try to optimize the call if possible, we require DataLayout for most of
2850   // this.  None of these calls are seen as possibly dead so go ahead and
2851   // delete the instruction now.
2852   if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
2853     Instruction *I = tryOptimizeCall(CI);
2854     // If we changed something return the result, etc. Otherwise let
2855     // the fallthrough check.
2856     if (I) return eraseInstFromFunction(*I);
2857   }
2858 
2859   if (!Call.use_empty() && !Call.isMustTailCall())
2860     if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
2861       Type *CallTy = Call.getType();
2862       Type *RetArgTy = ReturnedArg->getType();
2863       if (RetArgTy->canLosslesslyBitCastTo(CallTy))
2864         return replaceInstUsesWith(
2865             Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
2866     }
2867 
2868   if (isAllocationFn(&Call, &TLI) &&
2869       isAllocRemovable(&cast<CallBase>(Call), &TLI))
2870     return visitAllocSite(Call);
2871 
2872   // Handle intrinsics which can be used in both call and invoke context.
2873   switch (Call.getIntrinsicID()) {
2874   case Intrinsic::experimental_gc_statepoint: {
2875     GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
2876     SmallPtrSet<Value *, 32> LiveGcValues;
2877     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2878       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2879 
2880       // Remove the relocation if unused.
2881       if (GCR.use_empty()) {
2882         eraseInstFromFunction(GCR);
2883         continue;
2884       }
2885 
2886       Value *DerivedPtr = GCR.getDerivedPtr();
2887       Value *BasePtr = GCR.getBasePtr();
2888 
2889       // Undef is undef, even after relocation.
2890       if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
2891         replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));
2892         eraseInstFromFunction(GCR);
2893         continue;
2894       }
2895 
2896       if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
2897         // The relocation of null will be null for most any collector.
2898         // TODO: provide a hook for this in GCStrategy.  There might be some
2899         // weird collector this property does not hold for.
2900         if (isa<ConstantPointerNull>(DerivedPtr)) {
2901           // Use null-pointer of gc_relocate's type to replace it.
2902           replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));
2903           eraseInstFromFunction(GCR);
2904           continue;
2905         }
2906 
2907         // isKnownNonNull -> nonnull attribute
2908         if (!GCR.hasRetAttr(Attribute::NonNull) &&
2909             isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
2910           GCR.addRetAttr(Attribute::NonNull);
2911           // We discovered new fact, re-check users.
2912           Worklist.pushUsersToWorkList(GCR);
2913         }
2914       }
2915 
2916       // If we have two copies of the same pointer in the statepoint argument
2917       // list, canonicalize to one.  This may let us common gc.relocates.
2918       if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
2919           GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
2920         auto *OpIntTy = GCR.getOperand(2)->getType();
2921         GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
2922       }
2923 
2924       // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2925       // Canonicalize on the type from the uses to the defs
2926 
2927       // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2928       LiveGcValues.insert(BasePtr);
2929       LiveGcValues.insert(DerivedPtr);
2930     }
2931     Optional<OperandBundleUse> Bundle =
2932         GCSP.getOperandBundle(LLVMContext::OB_gc_live);
2933     unsigned NumOfGCLives = LiveGcValues.size();
2934     if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size())
2935       break;
2936     // We can reduce the size of gc live bundle.
2937     DenseMap<Value *, unsigned> Val2Idx;
2938     std::vector<Value *> NewLiveGc;
2939     for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) {
2940       Value *V = Bundle->Inputs[I];
2941       if (Val2Idx.count(V))
2942         continue;
2943       if (LiveGcValues.count(V)) {
2944         Val2Idx[V] = NewLiveGc.size();
2945         NewLiveGc.push_back(V);
2946       } else
2947         Val2Idx[V] = NumOfGCLives;
2948     }
2949     // Update all gc.relocates
2950     for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
2951       GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
2952       Value *BasePtr = GCR.getBasePtr();
2953       assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
2954              "Missed live gc for base pointer");
2955       auto *OpIntTy1 = GCR.getOperand(1)->getType();
2956       GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
2957       Value *DerivedPtr = GCR.getDerivedPtr();
2958       assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
2959              "Missed live gc for derived pointer");
2960       auto *OpIntTy2 = GCR.getOperand(2)->getType();
2961       GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
2962     }
2963     // Create new statepoint instruction.
2964     OperandBundleDef NewBundle("gc-live", NewLiveGc);
2965     return CallBase::Create(&Call, NewBundle);
2966   }
2967   default: { break; }
2968   }
2969 
2970   return Changed ? &Call : nullptr;
2971 }
2972 
2973 /// If the callee is a constexpr cast of a function, attempt to move the cast to
2974 /// the arguments of the call/callbr/invoke.
2975 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
2976   auto *Callee =
2977       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
2978   if (!Callee)
2979     return false;
2980 
2981   // If this is a call to a thunk function, don't remove the cast. Thunks are
2982   // used to transparently forward all incoming parameters and outgoing return
2983   // values, so it's important to leave the cast in place.
2984   if (Callee->hasFnAttribute("thunk"))
2985     return false;
2986 
2987   // If this is a musttail call, the callee's prototype must match the caller's
2988   // prototype with the exception of pointee types. The code below doesn't
2989   // implement that, so we can't do this transform.
2990   // TODO: Do the transform if it only requires adding pointer casts.
2991   if (Call.isMustTailCall())
2992     return false;
2993 
2994   Instruction *Caller = &Call;
2995   const AttributeList &CallerPAL = Call.getAttributes();
2996 
2997   // Okay, this is a cast from a function to a different type.  Unless doing so
2998   // would cause a type conversion of one of our arguments, change this call to
2999   // be a direct call with arguments casted to the appropriate types.
3000   FunctionType *FT = Callee->getFunctionType();
3001   Type *OldRetTy = Caller->getType();
3002   Type *NewRetTy = FT->getReturnType();
3003 
3004   // Check to see if we are changing the return type...
3005   if (OldRetTy != NewRetTy) {
3006 
3007     if (NewRetTy->isStructTy())
3008       return false; // TODO: Handle multiple return values.
3009 
3010     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3011       if (Callee->isDeclaration())
3012         return false;   // Cannot transform this return value.
3013 
3014       if (!Caller->use_empty() &&
3015           // void -> non-void is handled specially
3016           !NewRetTy->isVoidTy())
3017         return false;   // Cannot transform this return value.
3018     }
3019 
3020     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3021       AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3022       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3023         return false;   // Attribute not compatible with transformed value.
3024     }
3025 
3026     // If the callbase is an invoke/callbr instruction, and the return value is
3027     // used by a PHI node in a successor, we cannot change the return type of
3028     // the call because there is no place to put the cast instruction (without
3029     // breaking the critical edge).  Bail out in this case.
3030     if (!Caller->use_empty()) {
3031       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3032         for (User *U : II->users())
3033           if (PHINode *PN = dyn_cast<PHINode>(U))
3034             if (PN->getParent() == II->getNormalDest() ||
3035                 PN->getParent() == II->getUnwindDest())
3036               return false;
3037       // FIXME: Be conservative for callbr to avoid a quadratic search.
3038       if (isa<CallBrInst>(Caller))
3039         return false;
3040     }
3041   }
3042 
3043   unsigned NumActualArgs = Call.arg_size();
3044   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3045 
3046   // Prevent us turning:
3047   // declare void @takes_i32_inalloca(i32* inalloca)
3048   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3049   //
3050   // into:
3051   //  call void @takes_i32_inalloca(i32* null)
3052   //
3053   //  Similarly, avoid folding away bitcasts of byval calls.
3054   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3055       Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) ||
3056       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
3057     return false;
3058 
3059   auto AI = Call.arg_begin();
3060   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3061     Type *ParamTy = FT->getParamType(i);
3062     Type *ActTy = (*AI)->getType();
3063 
3064     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3065       return false;   // Cannot transform this parameter value.
3066 
3067     if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3068             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
3069       return false;   // Attribute not compatible with transformed value.
3070 
3071     if (Call.isInAllocaArgument(i))
3072       return false;   // Cannot transform to and from inalloca.
3073 
3074     if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3075       return false;
3076 
3077     // If the parameter is passed as a byval argument, then we have to have a
3078     // sized type and the sized type has to have the same size as the old type.
3079     if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3080       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
3081       if (!ParamPTy || !ParamPTy->getPointerElementType()->isSized())
3082         return false;
3083 
3084       Type *CurElTy = Call.getParamByValType(i);
3085       if (DL.getTypeAllocSize(CurElTy) !=
3086           DL.getTypeAllocSize(ParamPTy->getPointerElementType()))
3087         return false;
3088     }
3089   }
3090 
3091   if (Callee->isDeclaration()) {
3092     // Do not delete arguments unless we have a function body.
3093     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3094       return false;
3095 
3096     // If the callee is just a declaration, don't change the varargsness of the
3097     // call.  We don't want to introduce a varargs call where one doesn't
3098     // already exist.
3099     if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
3100       return false;
3101 
3102     // If both the callee and the cast type are varargs, we still have to make
3103     // sure the number of fixed parameters are the same or we have the same
3104     // ABI issues as if we introduce a varargs call.
3105     if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
3106         FT->getNumParams() != Call.getFunctionType()->getNumParams())
3107       return false;
3108   }
3109 
3110   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3111       !CallerPAL.isEmpty()) {
3112     // In this case we have more arguments than the new function type, but we
3113     // won't be dropping them.  Check that these extra arguments have attributes
3114     // that are compatible with being a vararg call argument.
3115     unsigned SRetIdx;
3116     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3117         SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3118       return false;
3119   }
3120 
3121   // Okay, we decided that this is a safe thing to do: go ahead and start
3122   // inserting cast instructions as necessary.
3123   SmallVector<Value *, 8> Args;
3124   SmallVector<AttributeSet, 8> ArgAttrs;
3125   Args.reserve(NumActualArgs);
3126   ArgAttrs.reserve(NumActualArgs);
3127 
3128   // Get any return attributes.
3129   AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3130 
3131   // If the return value is not being used, the type may not be compatible
3132   // with the existing attributes.  Wipe out any problematic attributes.
3133   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3134 
3135   LLVMContext &Ctx = Call.getContext();
3136   AI = Call.arg_begin();
3137   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3138     Type *ParamTy = FT->getParamType(i);
3139 
3140     Value *NewArg = *AI;
3141     if ((*AI)->getType() != ParamTy)
3142       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
3143     Args.push_back(NewArg);
3144 
3145     // Add any parameter attributes.
3146     if (CallerPAL.hasParamAttr(i, Attribute::ByVal)) {
3147       AttrBuilder AB(FT->getContext(), CallerPAL.getParamAttrs(i));
3148       AB.addByValAttr(NewArg->getType()->getPointerElementType());
3149       ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
3150     } else
3151       ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3152   }
3153 
3154   // If the function takes more arguments than the call was taking, add them
3155   // now.
3156   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
3157     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3158     ArgAttrs.push_back(AttributeSet());
3159   }
3160 
3161   // If we are removing arguments to the function, emit an obnoxious warning.
3162   if (FT->getNumParams() < NumActualArgs) {
3163     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3164     if (FT->isVarArg()) {
3165       // Add all of the arguments in their promoted form to the arg list.
3166       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3167         Type *PTy = getPromotedType((*AI)->getType());
3168         Value *NewArg = *AI;
3169         if (PTy != (*AI)->getType()) {
3170           // Must promote to pass through va_arg area!
3171           Instruction::CastOps opcode =
3172             CastInst::getCastOpcode(*AI, false, PTy, false);
3173           NewArg = Builder.CreateCast(opcode, *AI, PTy);
3174         }
3175         Args.push_back(NewArg);
3176 
3177         // Add any parameter attributes.
3178         ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3179       }
3180     }
3181   }
3182 
3183   AttributeSet FnAttrs = CallerPAL.getFnAttrs();
3184 
3185   if (NewRetTy->isVoidTy())
3186     Caller->setName("");   // Void type should not have a name.
3187 
3188   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
3189          "missing argument attributes");
3190   AttributeList NewCallerPAL = AttributeList::get(
3191       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
3192 
3193   SmallVector<OperandBundleDef, 1> OpBundles;
3194   Call.getOperandBundlesAsDefs(OpBundles);
3195 
3196   CallBase *NewCall;
3197   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3198     NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
3199                                    II->getUnwindDest(), Args, OpBundles);
3200   } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3201     NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
3202                                    CBI->getIndirectDests(), Args, OpBundles);
3203   } else {
3204     NewCall = Builder.CreateCall(Callee, Args, OpBundles);
3205     cast<CallInst>(NewCall)->setTailCallKind(
3206         cast<CallInst>(Caller)->getTailCallKind());
3207   }
3208   NewCall->takeName(Caller);
3209   NewCall->setCallingConv(Call.getCallingConv());
3210   NewCall->setAttributes(NewCallerPAL);
3211 
3212   // Preserve prof metadata if any.
3213   NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
3214 
3215   // Insert a cast of the return type as necessary.
3216   Instruction *NC = NewCall;
3217   Value *NV = NC;
3218   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3219     if (!NV->getType()->isVoidTy()) {
3220       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3221       NC->setDebugLoc(Caller->getDebugLoc());
3222 
3223       // If this is an invoke/callbr instruction, we should insert it after the
3224       // first non-phi instruction in the normal successor block.
3225       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3226         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3227         InsertNewInstBefore(NC, *I);
3228       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
3229         BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
3230         InsertNewInstBefore(NC, *I);
3231       } else {
3232         // Otherwise, it's a call, just insert cast right after the call.
3233         InsertNewInstBefore(NC, *Caller);
3234       }
3235       Worklist.pushUsersToWorkList(*Caller);
3236     } else {
3237       NV = UndefValue::get(Caller->getType());
3238     }
3239   }
3240 
3241   if (!Caller->use_empty())
3242     replaceInstUsesWith(*Caller, NV);
3243   else if (Caller->hasValueHandle()) {
3244     if (OldRetTy == NV->getType())
3245       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3246     else
3247       // We cannot call ValueIsRAUWd with a different type, and the
3248       // actual tracked value will disappear.
3249       ValueHandleBase::ValueIsDeleted(Caller);
3250   }
3251 
3252   eraseInstFromFunction(*Caller);
3253   return true;
3254 }
3255 
3256 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3257 /// intrinsic pair into a direct call to the underlying function.
3258 Instruction *
3259 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
3260                                                  IntrinsicInst &Tramp) {
3261   Value *Callee = Call.getCalledOperand();
3262   Type *CalleeTy = Callee->getType();
3263   FunctionType *FTy = Call.getFunctionType();
3264   AttributeList Attrs = Call.getAttributes();
3265 
3266   // If the call already has the 'nest' attribute somewhere then give up -
3267   // otherwise 'nest' would occur twice after splicing in the chain.
3268   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3269     return nullptr;
3270 
3271   Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
3272   FunctionType *NestFTy = NestF->getFunctionType();
3273 
3274   AttributeList NestAttrs = NestF->getAttributes();
3275   if (!NestAttrs.isEmpty()) {
3276     unsigned NestArgNo = 0;
3277     Type *NestTy = nullptr;
3278     AttributeSet NestAttr;
3279 
3280     // Look for a parameter marked with the 'nest' attribute.
3281     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3282                                       E = NestFTy->param_end();
3283          I != E; ++NestArgNo, ++I) {
3284       AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
3285       if (AS.hasAttribute(Attribute::Nest)) {
3286         // Record the parameter type and any other attributes.
3287         NestTy = *I;
3288         NestAttr = AS;
3289         break;
3290       }
3291     }
3292 
3293     if (NestTy) {
3294       std::vector<Value*> NewArgs;
3295       std::vector<AttributeSet> NewArgAttrs;
3296       NewArgs.reserve(Call.arg_size() + 1);
3297       NewArgAttrs.reserve(Call.arg_size());
3298 
3299       // Insert the nest argument into the call argument list, which may
3300       // mean appending it.  Likewise for attributes.
3301 
3302       {
3303         unsigned ArgNo = 0;
3304         auto I = Call.arg_begin(), E = Call.arg_end();
3305         do {
3306           if (ArgNo == NestArgNo) {
3307             // Add the chain argument and attributes.
3308             Value *NestVal = Tramp.getArgOperand(2);
3309             if (NestVal->getType() != NestTy)
3310               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
3311             NewArgs.push_back(NestVal);
3312             NewArgAttrs.push_back(NestAttr);
3313           }
3314 
3315           if (I == E)
3316             break;
3317 
3318           // Add the original argument and attributes.
3319           NewArgs.push_back(*I);
3320           NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3321 
3322           ++ArgNo;
3323           ++I;
3324         } while (true);
3325       }
3326 
3327       // The trampoline may have been bitcast to a bogus type (FTy).
3328       // Handle this by synthesizing a new function type, equal to FTy
3329       // with the chain parameter inserted.
3330 
3331       std::vector<Type*> NewTypes;
3332       NewTypes.reserve(FTy->getNumParams()+1);
3333 
3334       // Insert the chain's type into the list of parameter types, which may
3335       // mean appending it.
3336       {
3337         unsigned ArgNo = 0;
3338         FunctionType::param_iterator I = FTy->param_begin(),
3339           E = FTy->param_end();
3340 
3341         do {
3342           if (ArgNo == NestArgNo)
3343             // Add the chain's type.
3344             NewTypes.push_back(NestTy);
3345 
3346           if (I == E)
3347             break;
3348 
3349           // Add the original type.
3350           NewTypes.push_back(*I);
3351 
3352           ++ArgNo;
3353           ++I;
3354         } while (true);
3355       }
3356 
3357       // Replace the trampoline call with a direct call.  Let the generic
3358       // code sort out any function type mismatches.
3359       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3360                                                 FTy->isVarArg());
3361       Constant *NewCallee =
3362         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3363         NestF : ConstantExpr::getBitCast(NestF,
3364                                          PointerType::getUnqual(NewFTy));
3365       AttributeList NewPAL =
3366           AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
3367                              Attrs.getRetAttrs(), NewArgAttrs);
3368 
3369       SmallVector<OperandBundleDef, 1> OpBundles;
3370       Call.getOperandBundlesAsDefs(OpBundles);
3371 
3372       Instruction *NewCaller;
3373       if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
3374         NewCaller = InvokeInst::Create(NewFTy, NewCallee,
3375                                        II->getNormalDest(), II->getUnwindDest(),
3376                                        NewArgs, OpBundles);
3377         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3378         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3379       } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
3380         NewCaller =
3381             CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
3382                                CBI->getIndirectDests(), NewArgs, OpBundles);
3383         cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
3384         cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
3385       } else {
3386         NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
3387         cast<CallInst>(NewCaller)->setTailCallKind(
3388             cast<CallInst>(Call).getTailCallKind());
3389         cast<CallInst>(NewCaller)->setCallingConv(
3390             cast<CallInst>(Call).getCallingConv());
3391         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3392       }
3393       NewCaller->setDebugLoc(Call.getDebugLoc());
3394 
3395       return NewCaller;
3396     }
3397   }
3398 
3399   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3400   // parameter, there is no need to adjust the argument list.  Let the generic
3401   // code sort out any function type mismatches.
3402   Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
3403   Call.setCalledFunction(FTy, NewCallee);
3404   return &Call;
3405 }
3406