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