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