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