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