LLVM 17.0.0git
InstCombineCalls.cpp
Go to the documentation of this file.
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"
21#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/Loads.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/Function.h"
39#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/IntrinsicsAArch64.h"
46#include "llvm/IR/IntrinsicsAMDGPU.h"
47#include "llvm/IR/IntrinsicsARM.h"
48#include "llvm/IR/IntrinsicsHexagon.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Statepoint.h"
53#include "llvm/IR/Type.h"
54#include "llvm/IR/User.h"
55#include "llvm/IR/Value.h"
56#include "llvm/IR/ValueHandle.h"
61#include "llvm/Support/Debug.h"
70#include <algorithm>
71#include <cassert>
72#include <cstdint>
73#include <optional>
74#include <utility>
75#include <vector>
76
77#define DEBUG_TYPE "instcombine"
79
80using namespace llvm;
81using namespace PatternMatch;
82
83STATISTIC(NumSimplified, "Number of library calls simplified");
84
86 "instcombine-guard-widening-window",
87 cl::init(3),
88 cl::desc("How wide an instruction window to bypass looking for "
89 "another guard"));
90
91namespace llvm {
92/// enable preservation of attributes in assume like:
93/// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
95} // namespace llvm
96
97/// Return the specified type promoted as it would be to pass though a va_arg
98/// area.
100 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
101 if (ITy->getBitWidth() < 32)
102 return Type::getInt32Ty(Ty->getContext());
103 }
104 return Ty;
105}
106
107/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.
108/// TODO: This should probably be integrated with visitAllocSites, but that
109/// requires a deeper change to allow either unread or unwritten objects.
111 auto *Src = MI->getRawSource();
112 while (isa<GetElementPtrInst>(Src) || isa<BitCastInst>(Src)) {
113 if (!Src->hasOneUse())
114 return false;
115 Src = cast<Instruction>(Src)->getOperand(0);
116 }
117 return isa<AllocaInst>(Src) && Src->hasOneUse();
118}
119
121 Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
122 MaybeAlign CopyDstAlign = MI->getDestAlign();
123 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
124 MI->setDestAlignment(DstAlign);
125 return MI;
126 }
127
128 Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
129 MaybeAlign CopySrcAlign = MI->getSourceAlign();
130 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
131 MI->setSourceAlignment(SrcAlign);
132 return MI;
133 }
134
135 // If we have a store to a location which is known constant, we can conclude
136 // that the store must be storing the constant value (else the memory
137 // wouldn't be constant), and this must be a noop.
138 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
139 // Set the size of the copy to 0, it will be deleted on the next iteration.
140 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
141 return MI;
142 }
143
144 // If the source is provably undef, the memcpy/memmove doesn't do anything
145 // (unless the transfer is volatile).
146 if (hasUndefSource(MI) && !MI->isVolatile()) {
147 // Set the size of the copy to 0, it will be deleted on the next iteration.
148 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
149 return MI;
150 }
151
152 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
153 // load/store.
154 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
155 if (!MemOpLength) return nullptr;
156
157 // Source and destination pointer types are always "i8*" for intrinsic. See
158 // if the size is something we can handle with a single primitive load/store.
159 // A single load+store correctly handles overlapping memory in the memmove
160 // case.
161 uint64_t Size = MemOpLength->getLimitedValue();
162 assert(Size && "0-sized memory transferring should be removed already.");
163
164 if (Size > 8 || (Size&(Size-1)))
165 return nullptr; // If not 1/2/4/8 bytes, exit.
166
167 // If it is an atomic and alignment is less than the size then we will
168 // introduce the unaligned memory access which will be later transformed
169 // into libcall in CodeGen. This is not evident performance gain so disable
170 // it now.
171 if (isa<AtomicMemTransferInst>(MI))
172 if (*CopyDstAlign < Size || *CopySrcAlign < Size)
173 return nullptr;
174
175 // Use an integer load+store unless we can find something better.
176 unsigned SrcAddrSp =
177 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
178 unsigned DstAddrSp =
179 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
180
181 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
182 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
183 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
184
185 // If the memcpy has metadata describing the members, see if we can get the
186 // TBAA tag describing our copy.
187 MDNode *CopyMD = nullptr;
188 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
189 CopyMD = M;
190 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
191 if (M->getNumOperands() == 3 && M->getOperand(0) &&
192 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
193 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
194 M->getOperand(1) &&
195 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
196 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
197 Size &&
198 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
199 CopyMD = cast<MDNode>(M->getOperand(2));
200 }
201
202 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
203 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
204 LoadInst *L = Builder.CreateLoad(IntType, Src);
205 // Alignment from the mem intrinsic will be better, so use it.
206 L->setAlignment(*CopySrcAlign);
207 if (CopyMD)
208 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
209 MDNode *LoopMemParallelMD =
210 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
211 if (LoopMemParallelMD)
212 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
213 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
214 if (AccessGroupMD)
215 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
216
217 StoreInst *S = Builder.CreateStore(L, Dest);
218 // Alignment from the mem intrinsic will be better, so use it.
219 S->setAlignment(*CopyDstAlign);
220 if (CopyMD)
221 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
222 if (LoopMemParallelMD)
223 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
224 if (AccessGroupMD)
225 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
226 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
227
228 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
229 // non-atomics can be volatile
230 L->setVolatile(MT->isVolatile());
231 S->setVolatile(MT->isVolatile());
232 }
233 if (isa<AtomicMemTransferInst>(MI)) {
234 // atomics have to be unordered
235 L->setOrdering(AtomicOrdering::Unordered);
237 }
238
239 // Set the size of the copy to 0, it will be deleted on the next iteration.
240 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
241 return MI;
242}
243
245 const Align KnownAlignment =
246 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
247 MaybeAlign MemSetAlign = MI->getDestAlign();
248 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
249 MI->setDestAlignment(KnownAlignment);
250 return MI;
251 }
252
253 // If we have a store to a location which is known constant, we can conclude
254 // that the store must be storing the constant value (else the memory
255 // wouldn't be constant), and this must be a noop.
256 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
257 // Set the size of the copy to 0, it will be deleted on the next iteration.
258 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
259 return MI;
260 }
261
262 // Remove memset with an undef value.
263 // FIXME: This is technically incorrect because it might overwrite a poison
264 // value. Change to PoisonValue once #52930 is resolved.
265 if (isa<UndefValue>(MI->getValue())) {
266 // Set the size of the copy to 0, it will be deleted on the next iteration.
267 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
268 return MI;
269 }
270
271 // Extract the length and alignment and fill if they are constant.
272 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
273 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
274 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
275 return nullptr;
276 const uint64_t Len = LenC->getLimitedValue();
277 assert(Len && "0-sized memory setting should be removed already.");
278 const Align Alignment = MI->getDestAlign().valueOrOne();
279
280 // If it is an atomic and alignment is less than the size then we will
281 // introduce the unaligned memory access which will be later transformed
282 // into libcall in CodeGen. This is not evident performance gain so disable
283 // it now.
284 if (isa<AtomicMemSetInst>(MI))
285 if (Alignment < Len)
286 return nullptr;
287
288 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
289 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
290 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
291
292 Value *Dest = MI->getDest();
293 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
294 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
295 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
296
297 // Extract the fill value and store.
298 const uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
299 Constant *FillVal = ConstantInt::get(ITy, Fill);
300 StoreInst *S = Builder.CreateStore(FillVal, Dest, MI->isVolatile());
301 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
302 for (auto *DAI : at::getAssignmentMarkers(S)) {
303 if (any_of(DAI->location_ops(), [&](Value *V) { return V == FillC; }))
304 DAI->replaceVariableLocationOp(FillC, FillVal);
305 }
306
307 S->setAlignment(Alignment);
308 if (isa<AtomicMemSetInst>(MI))
310
311 // Set the size of the copy to 0, it will be deleted on the next iteration.
312 MI->setLength(Constant::getNullValue(LenC->getType()));
313 return MI;
314 }
315
316 return nullptr;
317}
318
319// TODO, Obvious Missing Transforms:
320// * Narrow width by halfs excluding zero/undef lanes
321Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
322 Value *LoadPtr = II.getArgOperand(0);
323 const Align Alignment =
324 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
325
326 // If the mask is all ones or undefs, this is a plain vector load of the 1st
327 // argument.
329 LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
330 "unmaskedload");
331 L->copyMetadata(II);
332 return L;
333 }
334
335 // If we can unconditionally load from this address, replace with a
336 // load/select idiom. TODO: use DT for context sensitive query
337 if (isDereferenceablePointer(LoadPtr, II.getType(),
338 II.getModule()->getDataLayout(), &II, &AC)) {
339 LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
340 "unmaskedload");
341 LI->copyMetadata(II);
342 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
343 }
344
345 return nullptr;
346}
347
348// TODO, Obvious Missing Transforms:
349// * Single constant active lane -> store
350// * Narrow width by halfs excluding zero/undef lanes
351Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
352 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
353 if (!ConstMask)
354 return nullptr;
355
356 // If the mask is all zeros, this instruction does nothing.
357 if (ConstMask->isNullValue())
358 return eraseInstFromFunction(II);
359
360 // If the mask is all ones, this is a plain vector store of the 1st argument.
361 if (ConstMask->isAllOnesValue()) {
362 Value *StorePtr = II.getArgOperand(1);
363 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
364 StoreInst *S =
365 new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
366 S->copyMetadata(II);
367 return S;
368 }
369
370 if (isa<ScalableVectorType>(ConstMask->getType()))
371 return nullptr;
372
373 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
374 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
375 APInt UndefElts(DemandedElts.getBitWidth(), 0);
376 if (Value *V =
377 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
378 return replaceOperand(II, 0, V);
379
380 return nullptr;
381}
382
383// TODO, Obvious Missing Transforms:
384// * Single constant active lane load -> load
385// * Dereferenceable address & few lanes -> scalarize speculative load/selects
386// * Adjacent vector addresses -> masked.load
387// * Narrow width by halfs excluding zero/undef lanes
388// * Vector incrementing address -> vector masked load
389Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
390 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
391 if (!ConstMask)
392 return nullptr;
393
394 // Vector splat address w/known mask -> scalar load
395 // Fold the gather to load the source vector first lane
396 // because it is reloading the same value each time
397 if (ConstMask->isAllOnesValue())
398 if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
399 auto *VecTy = cast<VectorType>(II.getType());
400 const Align Alignment =
401 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
402 LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
403 Alignment, "load.scalar");
404 Value *Shuf =
405 Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
406 return replaceInstUsesWith(II, cast<Instruction>(Shuf));
407 }
408
409 return nullptr;
410}
411
412// TODO, Obvious Missing Transforms:
413// * Single constant active lane -> store
414// * Adjacent vector addresses -> masked.store
415// * Narrow store width by halfs excluding zero/undef lanes
416// * Vector incrementing address -> vector masked store
417Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
418 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
419 if (!ConstMask)
420 return nullptr;
421
422 // If the mask is all zeros, a scatter does nothing.
423 if (ConstMask->isNullValue())
424 return eraseInstFromFunction(II);
425
426 // Vector splat address -> scalar store
427 if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
428 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
429 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
430 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
431 StoreInst *S =
432 new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
433 S->copyMetadata(II);
434 return S;
435 }
436 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
437 // lastlane), ptr
438 if (ConstMask->isAllOnesValue()) {
439 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
440 VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
441 ElementCount VF = WideLoadTy->getElementCount();
443 Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
444 Value *Extract =
446 StoreInst *S =
447 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
448 S->copyMetadata(II);
449 return S;
450 }
451 }
452 if (isa<ScalableVectorType>(ConstMask->getType()))
453 return nullptr;
454
455 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
456 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
457 APInt UndefElts(DemandedElts.getBitWidth(), 0);
458 if (Value *V =
459 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts))
460 return replaceOperand(II, 0, V);
461 if (Value *V =
462 SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts))
463 return replaceOperand(II, 1, V);
464
465 return nullptr;
466}
467
468/// This function transforms launder.invariant.group and strip.invariant.group
469/// like:
470/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
471/// launder(strip(%x)) -> launder(%x)
472/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
473/// strip(launder(%x)) -> strip(%x)
474/// This is legal because it preserves the most recent information about
475/// the presence or absence of invariant.group.
477 InstCombinerImpl &IC) {
478 auto *Arg = II.getArgOperand(0);
479 auto *StrippedArg = Arg->stripPointerCasts();
480 auto *StrippedInvariantGroupsArg = StrippedArg;
481 while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
482 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
483 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
484 break;
485 StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
486 }
487 if (StrippedArg == StrippedInvariantGroupsArg)
488 return nullptr; // No launders/strips to remove.
489
490 Value *Result = nullptr;
491
492 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
493 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
494 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
495 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
496 else
498 "simplifyInvariantGroupIntrinsic only handles launder and strip");
499 if (Result->getType()->getPointerAddressSpace() !=
501 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
502 if (Result->getType() != II.getType())
503 Result = IC.Builder.CreateBitCast(Result, II.getType());
504
505 return cast<Instruction>(Result);
506}
507
509 assert((II.getIntrinsicID() == Intrinsic::cttz ||
510 II.getIntrinsicID() == Intrinsic::ctlz) &&
511 "Expected cttz or ctlz intrinsic");
512 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
513 Value *Op0 = II.getArgOperand(0);
514 Value *Op1 = II.getArgOperand(1);
515 Value *X;
516 // ctlz(bitreverse(x)) -> cttz(x)
517 // cttz(bitreverse(x)) -> ctlz(x)
518 if (match(Op0, m_BitReverse(m_Value(X)))) {
519 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
521 return CallInst::Create(F, {X, II.getArgOperand(1)});
522 }
523
524 if (II.getType()->isIntOrIntVectorTy(1)) {
525 // ctlz/cttz i1 Op0 --> not Op0
526 if (match(Op1, m_Zero()))
527 return BinaryOperator::CreateNot(Op0);
528 // If zero is poison, then the input can be assumed to be "true", so the
529 // instruction simplifies to "false".
530 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
532 }
533
534 if (IsTZ) {
535 // cttz(-x) -> cttz(x)
536 if (match(Op0, m_Neg(m_Value(X))))
537 return IC.replaceOperand(II, 0, X);
538
539 // cttz(sext(x)) -> cttz(zext(x))
540 if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
541 auto *Zext = IC.Builder.CreateZExt(X, II.getType());
542 auto *CttzZext =
543 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
544 return IC.replaceInstUsesWith(II, CttzZext);
545 }
546
547 // Zext doesn't change the number of trailing zeros, so narrow:
548 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
549 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
550 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
551 IC.Builder.getTrue());
552 auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
553 return IC.replaceInstUsesWith(II, ZextCttz);
554 }
555
556 // cttz(abs(x)) -> cttz(x)
557 // cttz(nabs(x)) -> cttz(x)
558 Value *Y;
560 if (SPF == SPF_ABS || SPF == SPF_NABS)
561 return IC.replaceOperand(II, 0, X);
562
563 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
564 return IC.replaceOperand(II, 0, X);
565 }
566
567 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
568
569 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
570 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
571 : Known.countMaxLeadingZeros();
572 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
573 : Known.countMinLeadingZeros();
574
575 // If all bits above (ctlz) or below (cttz) the first known one are known
576 // zero, this value is constant.
577 // FIXME: This should be in InstSimplify because we're replacing an
578 // instruction with a constant.
579 if (PossibleZeros == DefiniteZeros) {
580 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
581 return IC.replaceInstUsesWith(II, C);
582 }
583
584 // If the input to cttz/ctlz is known to be non-zero,
585 // then change the 'ZeroIsPoison' parameter to 'true'
586 // because we know the zero behavior can't affect the result.
587 if (!Known.One.isZero() ||
588 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
589 &IC.getDominatorTree())) {
590 if (!match(II.getArgOperand(1), m_One()))
591 return IC.replaceOperand(II, 1, IC.Builder.getTrue());
592 }
593
594 // Add range metadata since known bits can't completely reflect what we know.
595 auto *IT = cast<IntegerType>(Op0->getType()->getScalarType());
596 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
597 Metadata *LowAndHigh[] = {
599 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
600 II.setMetadata(LLVMContext::MD_range,
602 return &II;
603 }
604
605 return nullptr;
606}
607
609 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
610 "Expected ctpop intrinsic");
611 Type *Ty = II.getType();
612 unsigned BitWidth = Ty->getScalarSizeInBits();
613 Value *Op0 = II.getArgOperand(0);
614 Value *X, *Y;
615
616 // ctpop(bitreverse(x)) -> ctpop(x)
617 // ctpop(bswap(x)) -> ctpop(x)
618 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
619 return IC.replaceOperand(II, 0, X);
620
621 // ctpop(rot(x)) -> ctpop(x)
622 if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
623 match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
624 X == Y)
625 return IC.replaceOperand(II, 0, X);
626
627 // ctpop(x | -x) -> bitwidth - cttz(x, false)
628 if (Op0->hasOneUse() &&
629 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
630 Function *F =
631 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
632 auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
633 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
634 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
635 }
636
637 // ctpop(~x & (x - 1)) -> cttz(x, false)
638 if (match(Op0,
640 Function *F =
641 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
642 return CallInst::Create(F, {X, IC.Builder.getFalse()});
643 }
644
645 // Zext doesn't change the number of set bits, so narrow:
646 // ctpop (zext X) --> zext (ctpop X)
647 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
648 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
649 return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
650 }
651
652 KnownBits Known(BitWidth);
653 IC.computeKnownBits(Op0, Known, 0, &II);
654
655 // If all bits are zero except for exactly one fixed bit, then the result
656 // must be 0 or 1, and we can get that answer by shifting to LSB:
657 // ctpop (X & 32) --> (X & 32) >> 5
658 // TODO: Investigate removing this as its likely unnecessary given the below
659 // `isKnownToBeAPowerOfTwo` check.
660 if ((~Known.Zero).isPowerOf2())
661 return BinaryOperator::CreateLShr(
662 Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
663
664 // More generally we can also handle non-constant power of 2 patterns such as
665 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
666 // ctpop(Pow2OrZero) --> icmp ne X, 0
667 if (IC.isKnownToBeAPowerOfTwo(Op0, /* OrZero */ true))
668 return CastInst::Create(Instruction::ZExt,
671 Ty);
672
673 // Add range metadata since known bits can't completely reflect what we know.
674 auto *IT = cast<IntegerType>(Ty->getScalarType());
675 unsigned MinCount = Known.countMinPopulation();
676 unsigned MaxCount = Known.countMaxPopulation();
677 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
678 Metadata *LowAndHigh[] = {
681 II.setMetadata(LLVMContext::MD_range,
683 return &II;
684 }
685
686 return nullptr;
687}
688
689/// Convert a table lookup to shufflevector if the mask is constant.
690/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
691/// which case we could lower the shufflevector with rev64 instructions
692/// as it's actually a byte reverse.
694 InstCombiner::BuilderTy &Builder) {
695 // Bail out if the mask is not a constant.
696 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
697 if (!C)
698 return nullptr;
699
700 auto *VecTy = cast<FixedVectorType>(II.getType());
701 unsigned NumElts = VecTy->getNumElements();
702
703 // Only perform this transformation for <8 x i8> vector types.
704 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
705 return nullptr;
706
707 int Indexes[8];
708
709 for (unsigned I = 0; I < NumElts; ++I) {
710 Constant *COp = C->getAggregateElement(I);
711
712 if (!COp || !isa<ConstantInt>(COp))
713 return nullptr;
714
715 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
716
717 // Make sure the mask indices are in range.
718 if ((unsigned)Indexes[I] >= NumElts)
719 return nullptr;
720 }
721
722 auto *V1 = II.getArgOperand(0);
723 auto *V2 = Constant::getNullValue(V1->getType());
724 return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes));
725}
726
727// Returns true iff the 2 intrinsics have the same operands, limiting the
728// comparison to the first NumOperands.
729static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
730 unsigned NumOperands) {
731 assert(I.arg_size() >= NumOperands && "Not enough operands");
732 assert(E.arg_size() >= NumOperands && "Not enough operands");
733 for (unsigned i = 0; i < NumOperands; i++)
734 if (I.getArgOperand(i) != E.getArgOperand(i))
735 return false;
736 return true;
737}
738
739// Remove trivially empty start/end intrinsic ranges, i.e. a start
740// immediately followed by an end (ignoring debuginfo or other
741// start/end intrinsics in between). As this handles only the most trivial
742// cases, tracking the nesting level is not needed:
743//
744// call @llvm.foo.start(i1 0)
745// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
746// call @llvm.foo.end(i1 0)
747// call @llvm.foo.end(i1 0) ; &I
748static bool
750 std::function<bool(const IntrinsicInst &)> IsStart) {
751 // We start from the end intrinsic and scan backwards, so that InstCombine
752 // has already processed (and potentially removed) all the instructions
753 // before the end intrinsic.
754 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
755 for (; BI != BE; ++BI) {
756 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
757 if (I->isDebugOrPseudoInst() ||
758 I->getIntrinsicID() == EndI.getIntrinsicID())
759 continue;
760 if (IsStart(*I)) {
761 if (haveSameOperands(EndI, *I, EndI.arg_size())) {
763 IC.eraseInstFromFunction(EndI);
764 return true;
765 }
766 // Skip start intrinsics that don't pair with this end intrinsic.
767 continue;
768 }
769 }
770 break;
771 }
772
773 return false;
774}
775
777 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
778 return I.getIntrinsicID() == Intrinsic::vastart ||
779 I.getIntrinsicID() == Intrinsic::vacopy;
780 });
781 return nullptr;
782}
783
785 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
786 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
787 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
788 Call.setArgOperand(0, Arg1);
789 Call.setArgOperand(1, Arg0);
790 return &Call;
791 }
792 return nullptr;
793}
794
795/// Creates a result tuple for an overflow intrinsic \p II with a given
796/// \p Result and a constant \p Overflow value.
798 Constant *Overflow) {
799 Constant *V[] = {PoisonValue::get(Result->getType()), Overflow};
800 StructType *ST = cast<StructType>(II->getType());
802 return InsertValueInst::Create(Struct, Result, 0);
803}
804
806InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
807 WithOverflowInst *WO = cast<WithOverflowInst>(II);
808 Value *OperationResult = nullptr;
809 Constant *OverflowResult = nullptr;
810 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
811 WO->getRHS(), *WO, OperationResult, OverflowResult))
812 return createOverflowTuple(WO, OperationResult, OverflowResult);
813 return nullptr;
814}
815
816static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
817 Ty = Ty->getScalarType();
818 return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;
819}
820
821static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
822 Ty = Ty->getScalarType();
823 return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();
824}
825
826/// \returns the compare predicate type if the test performed by
827/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
828/// floating-point environment assumed for \p F for type \p Ty
830 const Function &F, Type *Ty) {
831 switch (static_cast<unsigned>(Mask)) {
832 case fcZero:
833 if (inputDenormalIsIEEE(F, Ty))
834 return FCmpInst::FCMP_OEQ;
835 break;
836 case fcZero | fcSubnormal:
837 if (inputDenormalIsDAZ(F, Ty))
838 return FCmpInst::FCMP_OEQ;
839 break;
840 case fcPositive | fcNegZero:
841 if (inputDenormalIsIEEE(F, Ty))
842 return FCmpInst::FCMP_OGE;
843 break;
845 if (inputDenormalIsDAZ(F, Ty))
846 return FCmpInst::FCMP_OGE;
847 break;
849 if (inputDenormalIsIEEE(F, Ty))
850 return FCmpInst::FCMP_OGT;
851 break;
852 case fcNegative | fcPosZero:
853 if (inputDenormalIsIEEE(F, Ty))
854 return FCmpInst::FCMP_OLE;
855 break;
857 if (inputDenormalIsDAZ(F, Ty))
858 return FCmpInst::FCMP_OLE;
859 break;
861 if (inputDenormalIsIEEE(F, Ty))
862 return FCmpInst::FCMP_OLT;
863 break;
864 case fcPosNormal | fcPosInf:
865 if (inputDenormalIsDAZ(F, Ty))
866 return FCmpInst::FCMP_OGT;
867 break;
868 case fcNegNormal | fcNegInf:
869 if (inputDenormalIsDAZ(F, Ty))
870 return FCmpInst::FCMP_OLT;
871 break;
872 case ~fcZero & ~fcNan:
873 if (inputDenormalIsIEEE(F, Ty))
874 return FCmpInst::FCMP_ONE;
875 break;
876 case ~(fcZero | fcSubnormal) & ~fcNan:
877 if (inputDenormalIsDAZ(F, Ty))
878 return FCmpInst::FCMP_ONE;
879 break;
880 default:
881 break;
882 }
883
885}
886
887Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
888 Value *Src0 = II.getArgOperand(0);
889 Value *Src1 = II.getArgOperand(1);
890 const ConstantInt *CMask = cast<ConstantInt>(Src1);
891 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
892 const bool IsUnordered = (Mask & fcNan) == fcNan;
893 const bool IsOrdered = (Mask & fcNan) == fcNone;
894 const FPClassTest OrderedMask = Mask & ~fcNan;
895 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
896
897 const bool IsStrict = II.isStrictFP();
898
899 Value *FNegSrc;
900 if (match(Src0, m_FNeg(m_Value(FNegSrc)))) {
901 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
902
903 II.setArgOperand(1, ConstantInt::get(Src1->getType(), fneg(Mask)));
904 return replaceOperand(II, 0, FNegSrc);
905 }
906
907 Value *FAbsSrc;
908 if (match(Src0, m_FAbs(m_Value(FAbsSrc)))) {
909 II.setArgOperand(1, ConstantInt::get(Src1->getType(), fabs(Mask)));
910 return replaceOperand(II, 0, FAbsSrc);
911 }
912
913 // TODO: is.fpclass(x, fcInf) -> fabs(x) == inf
914
915 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
916 (IsOrdered || IsUnordered) && !IsStrict) {
917 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
918 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
919 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
920 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
921 Constant *Inf =
922 ConstantFP::getInfinity(Src0->getType(), OrderedMask == fcNegInf);
923 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(Src0, Inf)
924 : Builder.CreateFCmpOEQ(Src0, Inf);
925
926 EqInf->takeName(&II);
927 return replaceInstUsesWith(II, EqInf);
928 }
929
930 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
931 (IsOrdered || IsUnordered) && !IsStrict) {
932 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
933 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
934 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
935 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
937 OrderedInvertedMask == fcNegInf);
938 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(Src0, Inf)
939 : Builder.CreateFCmpONE(Src0, Inf);
940 NeInf->takeName(&II);
941 return replaceInstUsesWith(II, NeInf);
942 }
943
944 if (Mask == fcNan && !IsStrict) {
945 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
946 // exceptions.
947 Value *IsNan =
949 IsNan->takeName(&II);
950 return replaceInstUsesWith(II, IsNan);
951 }
952
953 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
954 // Equivalent of !isnan. Replace with standard fcmp.
955 Value *FCmp =
957 FCmp->takeName(&II);
958 return replaceInstUsesWith(II, FCmp);
959 }
960
962
963 // Try to replace with an fcmp with 0
964 //
965 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
966 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
967 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
968 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
969 //
970 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
971 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
972 //
973 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
974 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
975 //
976 if (!IsStrict && (IsOrdered || IsUnordered) &&
977 (PredType = fpclassTestIsFCmp0(OrderedMask, *II.getFunction(),
978 Src0->getType())) !=
981 // Equivalent of == 0.
982 Value *FCmp = Builder.CreateFCmp(
983 IsUnordered ? FCmpInst::getUnorderedPredicate(PredType) : PredType,
984 Src0, Zero);
985
986 FCmp->takeName(&II);
987 return replaceInstUsesWith(II, FCmp);
988 }
989
991 Src0, DL, Mask, 0, &getTargetLibraryInfo(), &AC, &II, &DT, &ORE);
992
993 // Clear test bits we know must be false from the source value.
994 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
995 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
996 if ((Mask & Known.KnownFPClasses) != Mask) {
997 II.setArgOperand(
998 1, ConstantInt::get(Src1->getType(), Mask & Known.KnownFPClasses));
999 return &II;
1000 }
1001
1002 // If none of the tests which can return false are possible, fold to true.
1003 // fp_class (nnan x), ~(qnan|snan) -> true
1004 // fp_class (ninf x), ~(ninf|pinf) -> true
1005 if (Mask == Known.KnownFPClasses)
1006 return replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));
1007
1008 return nullptr;
1009}
1010
1011static std::optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
1012 const DataLayout &DL, AssumptionCache *AC,
1013 DominatorTree *DT) {
1014 KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
1015 if (Known.isNonNegative())
1016 return false;
1017 if (Known.isNegative())
1018 return true;
1019
1020 Value *X, *Y;
1021 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1023
1025 ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
1026}
1027
1028/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1029/// can trigger other combines.
1031 InstCombiner::BuilderTy &Builder) {
1032 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1033 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1034 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1035 "Expected a min or max intrinsic");
1036
1037 // TODO: Match vectors with undef elements, but undef may not propagate.
1038 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1039 Value *X;
1040 const APInt *C0, *C1;
1041 if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
1042 !match(Op1, m_APInt(C1)))
1043 return nullptr;
1044
1045 // Check for necessary no-wrap and overflow constraints.
1046 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1047 auto *Add = cast<BinaryOperator>(Op0);
1048 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1049 (!IsSigned && !Add->hasNoUnsignedWrap()))
1050 return nullptr;
1051
1052 // If the constant difference overflows, then instsimplify should reduce the
1053 // min/max to the add or C1.
1054 bool Overflow;
1055 APInt CDiff =
1056 IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
1057 assert(!Overflow && "Expected simplify of min/max");
1058
1059 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1060 // Note: the "mismatched" no-overflow setting does not propagate.
1061 Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
1062 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
1063 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
1064 : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
1065}
1066/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1067Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1068 Type *Ty = MinMax1.getType();
1069
1070 // We are looking for a tree of:
1071 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1072 // Where the min and max could be reversed
1073 Instruction *MinMax2;
1075 const APInt *MinValue, *MaxValue;
1076 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
1077 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
1078 return nullptr;
1079 } else if (match(&MinMax1,
1080 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
1081 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
1082 return nullptr;
1083 } else
1084 return nullptr;
1085
1086 // Check that the constants clamp a saturate, and that the new type would be
1087 // sensible to convert to.
1088 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1089 return nullptr;
1090 // In what bitwidth can this be treated as saturating arithmetics?
1091 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1092 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1093 // good first approximation for what should be done there.
1094 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
1095 return nullptr;
1096
1097 // Also make sure that the inner min/max and the add/sub have one use.
1098 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1099 return nullptr;
1100
1101 // Create the new type (which can be a vector type)
1102 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1103
1104 Intrinsic::ID IntrinsicID;
1105 if (AddSub->getOpcode() == Instruction::Add)
1106 IntrinsicID = Intrinsic::sadd_sat;
1107 else if (AddSub->getOpcode() == Instruction::Sub)
1108 IntrinsicID = Intrinsic::ssub_sat;
1109 else
1110 return nullptr;
1111
1112 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1113 // is usually achieved via a sext from a smaller type.
1114 if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >
1115 NewBitWidth ||
1116 ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
1117 return nullptr;
1118
1119 // Finally create and return the sat intrinsic, truncated to the new type
1120 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
1121 Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
1122 Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
1123 Value *Sat = Builder.CreateCall(F, {AT, BT});
1124 return CastInst::Create(Instruction::SExt, Sat, Ty);
1125}
1126
1127
1128/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1129/// can only be one of two possible constant values -- turn that into a select
1130/// of constants.
1132 InstCombiner::BuilderTy &Builder) {
1133 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1134 Value *X;
1135 const APInt *C0, *C1;
1136 if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
1137 return nullptr;
1138
1140 switch (II->getIntrinsicID()) {
1141 case Intrinsic::smax:
1142 if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1143 Pred = ICmpInst::ICMP_SGT;
1144 break;
1145 case Intrinsic::smin:
1146 if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1147 Pred = ICmpInst::ICMP_SLT;
1148 break;
1149 case Intrinsic::umax:
1150 if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1151 Pred = ICmpInst::ICMP_UGT;
1152 break;
1153 case Intrinsic::umin:
1154 if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1155 Pred = ICmpInst::ICMP_ULT;
1156 break;
1157 default:
1158 llvm_unreachable("Expected min/max intrinsic");
1159 }
1160 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1161 return nullptr;
1162
1163 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1164 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1165 Value *Cmp = Builder.CreateICmp(Pred, X, I1);
1166 return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
1167}
1168
1169/// If this min/max has a constant operand and an operand that is a matching
1170/// min/max with a constant operand, constant-fold the 2 constant operands.
1172 IRBuilderBase &Builder) {
1173 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1174 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1175 if (!LHS || LHS->getIntrinsicID() != MinMaxID)
1176 return nullptr;
1177
1178 Constant *C0, *C1;
1179 if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
1180 !match(II->getArgOperand(1), m_ImmConstant(C1)))
1181 return nullptr;
1182
1183 // max (max X, C0), C1 --> max X, (max C0, C1) --> max X, NewC
1185 Value *CondC = Builder.CreateICmp(Pred, C0, C1);
1186 Value *NewC = Builder.CreateSelect(CondC, C0, C1);
1187 return Builder.CreateIntrinsic(MinMaxID, II->getType(),
1188 {LHS->getArgOperand(0), NewC});
1189}
1190
1191/// If this min/max has a matching min/max operand with a constant, try to push
1192/// the constant operand into this instruction. This can enable more folds.
1193static Instruction *
1195 InstCombiner::BuilderTy &Builder) {
1196 // Match and capture a min/max operand candidate.
1197 Value *X, *Y;
1198 Constant *C;
1199 Instruction *Inner;
1201 m_Instruction(Inner),
1203 m_Value(Y))))
1204 return nullptr;
1205
1206 // The inner op must match. Check for constants to avoid infinite loops.
1207 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1208 auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
1209 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1211 return nullptr;
1212
1213 // max (max X, C), Y --> max (max X, Y), C
1214 Function *MinMax =
1215 Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType());
1216 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
1217 NewInner->takeName(Inner);
1218 return CallInst::Create(MinMax, {NewInner, C});
1219}
1220
1221/// Reduce a sequence of min/max intrinsics with a common operand.
1223 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1224 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1225 auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
1226 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1227 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1228 RHS->getIntrinsicID() != MinMaxID ||
1229 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1230 return nullptr;
1231
1232 Value *A = LHS->getArgOperand(0);
1233 Value *B = LHS->getArgOperand(1);
1234 Value *C = RHS->getArgOperand(0);
1235 Value *D = RHS->getArgOperand(1);
1236
1237 // Look for a common operand.
1238 Value *MinMaxOp = nullptr;
1239 Value *ThirdOp = nullptr;
1240 if (LHS->hasOneUse()) {
1241 // If the LHS is only used in this chain and the RHS is used outside of it,
1242 // reuse the RHS min/max because that will eliminate the LHS.
1243 if (D == A || C == A) {
1244 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1245 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1246 MinMaxOp = RHS;
1247 ThirdOp = B;
1248 } else if (D == B || C == B) {
1249 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1250 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1251 MinMaxOp = RHS;
1252 ThirdOp = A;
1253 }
1254 } else {
1255 assert(RHS->hasOneUse() && "Expected one-use operand");
1256 // Reuse the LHS. This will eliminate the RHS.
1257 if (D == A || D == B) {
1258 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1259 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1260 MinMaxOp = LHS;
1261 ThirdOp = C;
1262 } else if (C == A || C == B) {
1263 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1264 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1265 MinMaxOp = LHS;
1266 ThirdOp = D;
1267 }
1268 }
1269
1270 if (!MinMaxOp || !ThirdOp)
1271 return nullptr;
1272
1273 Module *Mod = II->getModule();
1275 return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
1276}
1277
1278/// If all arguments of the intrinsic are unary shuffles with the same mask,
1279/// try to shuffle after the intrinsic.
1280static Instruction *
1282 InstCombiner::BuilderTy &Builder) {
1283 // TODO: This should be extended to handle other intrinsics like fshl, ctpop,
1284 // etc. Use llvm::isTriviallyVectorizable() and related to determine
1285 // which intrinsics are safe to shuffle?
1286 switch (II->getIntrinsicID()) {
1287 case Intrinsic::smax:
1288 case Intrinsic::smin:
1289 case Intrinsic::umax:
1290 case Intrinsic::umin:
1291 case Intrinsic::fma:
1292 case Intrinsic::fshl:
1293 case Intrinsic::fshr:
1294 break;
1295 default:
1296 return nullptr;
1297 }
1298
1299 Value *X;
1300 ArrayRef<int> Mask;
1301 if (!match(II->getArgOperand(0),
1302 m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))
1303 return nullptr;
1304
1305 // At least 1 operand must have 1 use because we are creating 2 instructions.
1306 if (none_of(II->args(), [](Value *V) { return V->hasOneUse(); }))
1307 return nullptr;
1308
1309 // See if all arguments are shuffled with the same mask.
1310 SmallVector<Value *, 4> NewArgs(II->arg_size());
1311 NewArgs[0] = X;
1312 Type *SrcTy = X->getType();
1313 for (unsigned i = 1, e = II->arg_size(); i != e; ++i) {
1314 if (!match(II->getArgOperand(i),
1315 m_Shuffle(m_Value(X), m_Undef(), m_SpecificMask(Mask))) ||
1316 X->getType() != SrcTy)
1317 return nullptr;
1318 NewArgs[i] = X;
1319 }
1320
1321 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1322 Instruction *FPI = isa<FPMathOperator>(II) ? II : nullptr;
1323 Value *NewIntrinsic =
1324 Builder.CreateIntrinsic(II->getIntrinsicID(), SrcTy, NewArgs, FPI);
1325 return new ShuffleVectorInst(NewIntrinsic, Mask);
1326}
1327
1328/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1329/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1330/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1331template <Intrinsic::ID IntrID>
1333 InstCombiner::BuilderTy &Builder) {
1334 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1335 "This helper only supports BSWAP and BITREVERSE intrinsics");
1336
1337 Value *X, *Y;
1338 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1339 // don't match ConstantExpr that aren't meaningful for this transform.
1341 isa<BinaryOperator>(V)) {
1342 Value *OldReorderX, *OldReorderY;
1343 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(V)->getOpcode();
1344
1345 // If both X and Y are bswap/bitreverse, the transform reduces the number
1346 // of instructions even if there's multiuse.
1347 // If only one operand is bswap/bitreverse, we need to ensure the operand
1348 // have only one use.
1349 if (match(X, m_Intrinsic<IntrID>(m_Value(OldReorderX))) &&
1350 match(Y, m_Intrinsic<IntrID>(m_Value(OldReorderY)))) {
1351 return BinaryOperator::Create(Op, OldReorderX, OldReorderY);
1352 }
1353
1354 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderX))))) {
1355 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, Y);
1356 return BinaryOperator::Create(Op, OldReorderX, NewReorder);
1357 }
1358
1359 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderY))))) {
1360 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, X);
1361 return BinaryOperator::Create(Op, NewReorder, OldReorderY);
1362 }
1363 }
1364 return nullptr;
1365}
1366
1367/// CallInst simplification. This mostly only handles folding of intrinsic
1368/// instructions. For normal calls, it allows visitCallBase to do the heavy
1369/// lifting.
1371 // Don't try to simplify calls without uses. It will not do anything useful,
1372 // but will result in the following folds being skipped.
1373 if (!CI.use_empty()) {
1375 Args.reserve(CI.arg_size());
1376 for (Value *Op : CI.args())
1377 Args.push_back(Op);
1378 if (Value *V = simplifyCall(&CI, CI.getCalledOperand(), Args,
1379 SQ.getWithInstruction(&CI)))
1380 return replaceInstUsesWith(CI, V);
1381 }
1382
1383 if (Value *FreedOp = getFreedOperand(&CI, &TLI))
1384 return visitFree(CI, FreedOp);
1385
1386 // If the caller function (i.e. us, the function that contains this CallInst)
1387 // is nounwind, mark the call as nounwind, even if the callee isn't.
1388 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1389 CI.setDoesNotThrow();
1390 return &CI;
1391 }
1392
1393 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1394 if (!II) return visitCallBase(CI);
1395
1396 // For atomic unordered mem intrinsics if len is not a positive or
1397 // not a multiple of element size then behavior is undefined.
1398 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1399 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1400 if (NumBytes->isNegative() ||
1401 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1403 assert(AMI->getType()->isVoidTy() &&
1404 "non void atomic unordered mem intrinsic");
1405 return eraseInstFromFunction(*AMI);
1406 }
1407
1408 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1409 // instead of in visitCallBase.
1410 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1411 bool Changed = false;
1412
1413 // memmove/cpy/set of zero bytes is a noop.
1414 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1415 if (NumBytes->isNullValue())
1416 return eraseInstFromFunction(CI);
1417 }
1418
1419 // No other transformations apply to volatile transfers.
1420 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1421 if (M->isVolatile())
1422 return nullptr;
1423
1424 // If we have a memmove and the source operation is a constant global,
1425 // then the source and dest pointers can't alias, so we can change this
1426 // into a call to memcpy.
1427 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1428 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1429 if (GVSrc->isConstant()) {
1430 Module *M = CI.getModule();
1431 Intrinsic::ID MemCpyID =
1432 isa<AtomicMemMoveInst>(MMI)
1433 ? Intrinsic::memcpy_element_unordered_atomic
1434 : Intrinsic::memcpy;
1435 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1436 CI.getArgOperand(1)->getType(),
1437 CI.getArgOperand(2)->getType() };
1438 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1439 Changed = true;
1440 }
1441 }
1442
1443 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1444 // memmove(x,x,size) -> noop.
1445 if (MTI->getSource() == MTI->getDest())
1446 return eraseInstFromFunction(CI);
1447 }
1448
1449 // If we can determine a pointer alignment that is bigger than currently
1450 // set, update the alignment.
1451 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1453 return I;
1454 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1455 if (Instruction *I = SimplifyAnyMemSet(MSI))
1456 return I;
1457 }
1458
1459 if (Changed) return II;
1460 }
1461
1462 // For fixed width vector result intrinsics, use the generic demanded vector
1463 // support.
1464 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1465 auto VWidth = IIFVTy->getNumElements();
1466 APInt UndefElts(VWidth, 0);
1467 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1468 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1469 if (V != II)
1470 return replaceInstUsesWith(*II, V);
1471 return II;
1472 }
1473 }
1474
1475 if (II->isCommutative()) {
1476 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1477 return NewCall;
1478 }
1479
1480 // Unused constrained FP intrinsic calls may have declared side effect, which
1481 // prevents it from being removed. In some cases however the side effect is
1482 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
1483 // returns a replacement, the call may be removed.
1484 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(CI)) {
1486 return eraseInstFromFunction(CI);
1487 }
1488
1489 Intrinsic::ID IID = II->getIntrinsicID();
1490 switch (IID) {
1491 case Intrinsic::objectsize:
1492 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false))
1493 return replaceInstUsesWith(CI, V);
1494 return nullptr;
1495 case Intrinsic::abs: {
1496 Value *IIOperand = II->getArgOperand(0);
1497 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1498
1499 // abs(-x) -> abs(x)
1500 // TODO: Copy nsw if it was present on the neg?
1501 Value *X;
1502 if (match(IIOperand, m_Neg(m_Value(X))))
1503 return replaceOperand(*II, 0, X);
1504 if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
1505 return replaceOperand(*II, 0, X);
1506 if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
1507 return replaceOperand(*II, 0, X);
1508
1509 if (std::optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) {
1510 // abs(x) -> x if x >= 0
1511 if (!*Sign)
1512 return replaceInstUsesWith(*II, IIOperand);
1513
1514 // abs(x) -> -x if x < 0
1515 if (IntMinIsPoison)
1516 return BinaryOperator::CreateNSWNeg(IIOperand);
1517 return BinaryOperator::CreateNeg(IIOperand);
1518 }
1519
1520 // abs (sext X) --> zext (abs X*)
1521 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1522 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1523 Value *NarrowAbs =
1524 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1525 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1526 }
1527
1528 // Match a complicated way to check if a number is odd/even:
1529 // abs (srem X, 2) --> and X, 1
1530 const APInt *C;
1531 if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1532 return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1533
1534 break;
1535 }
1536 case Intrinsic::umin: {
1537 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1538 // umin(x, 1) == zext(x != 0)
1539 if (match(I1, m_One())) {
1540 assert(II->getType()->getScalarSizeInBits() != 1 &&
1541 "Expected simplify of umin with max constant");
1542 Value *Zero = Constant::getNullValue(I0->getType());
1543 Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1544 return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1545 }
1546 [[fallthrough]];
1547 }
1548 case Intrinsic::umax: {
1549 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1550 Value *X, *Y;
1551 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1552 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1553 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1554 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1555 }
1556 Constant *C;
1557 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1558 I0->hasOneUse()) {
1559 Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1560 if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) {
1561 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1562 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1563 }
1564 }
1565 // If both operands of unsigned min/max are sign-extended, it is still ok
1566 // to narrow the operation.
1567 [[fallthrough]];
1568 }
1569 case Intrinsic::smax:
1570 case Intrinsic::smin: {
1571 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1572 Value *X, *Y;
1573 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1574 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1575 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1576 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1577 }
1578
1579 Constant *C;
1580 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1581 I0->hasOneUse()) {
1582 Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType());
1583 if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) {
1584 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1585 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1586 }
1587 }
1588
1589 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1590 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1591 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1592 // TODO: Canonicalize neg after min/max if I1 is constant.
1593 if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1594 (I0->hasOneUse() || I1->hasOneUse())) {
1596 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1597 return BinaryOperator::CreateNSWNeg(InvMaxMin);
1598 }
1599 }
1600
1601 // (umax X, (xor X, Pow2))
1602 // -> (or X, Pow2)
1603 // (umin X, (xor X, Pow2))
1604 // -> (and X, ~Pow2)
1605 // (smax X, (xor X, Pos_Pow2))
1606 // -> (or X, Pos_Pow2)
1607 // (smin X, (xor X, Pos_Pow2))
1608 // -> (and X, ~Pos_Pow2)
1609 // (smax X, (xor X, Neg_Pow2))
1610 // -> (and X, ~Neg_Pow2)
1611 // (smin X, (xor X, Neg_Pow2))
1612 // -> (or X, Neg_Pow2)
1613 if ((match(I0, m_c_Xor(m_Specific(I1), m_Value(X))) ||
1614 match(I1, m_c_Xor(m_Specific(I0), m_Value(X)))) &&
1615 isKnownToBeAPowerOfTwo(X, /* OrZero */ true)) {
1616 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
1617 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
1618
1619 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1620 auto KnownSign = getKnownSign(X, II, DL, &AC, &DT);
1621 if (KnownSign == std::nullopt) {
1622 UseOr = false;
1623 UseAndN = false;
1624 } else if (*KnownSign /* true is Signed. */) {
1625 UseOr ^= true;
1626 UseAndN ^= true;
1627 Type *Ty = I0->getType();
1628 // Negative power of 2 must be IntMin. It's possible to be able to
1629 // prove negative / power of 2 without actually having known bits, so
1630 // just get the value by hand.
1633 }
1634 }
1635 if (UseOr)
1636 return BinaryOperator::CreateOr(I0, X);
1637 else if (UseAndN)
1638 return BinaryOperator::CreateAnd(I0, Builder.CreateNot(X));
1639 }
1640
1641 // If we can eliminate ~A and Y is free to invert:
1642 // max ~A, Y --> ~(min A, ~Y)
1643 //
1644 // Examples:
1645 // max ~A, ~Y --> ~(min A, Y)
1646 // max ~A, C --> ~(min A, ~C)
1647 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1648 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1649 Value *A;
1650 if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1651 !isFreeToInvert(A, A->hasOneUse()) &&
1652 isFreeToInvert(Y, Y->hasOneUse())) {
1653 Value *NotY = Builder.CreateNot(Y);
1655 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1656 return BinaryOperator::CreateNot(InvMaxMin);
1657 }
1658 return nullptr;
1659 };
1660
1661 if (Instruction *I = moveNotAfterMinMax(I0, I1))
1662 return I;
1663 if (Instruction *I = moveNotAfterMinMax(I1, I0))
1664 return I;
1665
1667 return I;
1668
1669 // smax(X, -X) --> abs(X)
1670 // smin(X, -X) --> -abs(X)
1671 // umax(X, -X) --> -abs(X)
1672 // umin(X, -X) --> abs(X)
1673 if (isKnownNegation(I0, I1)) {
1674 // We can choose either operand as the input to abs(), but if we can
1675 // eliminate the only use of a value, that's better for subsequent
1676 // transforms/analysis.
1677 if (I0->hasOneUse() && !I1->hasOneUse())
1678 std::swap(I0, I1);
1679
1680 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1681 // operation and potentially its negation.
1682 bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1684 Intrinsic::abs, I0,
1685 ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1686
1687 // We don't have a "nabs" intrinsic, so negate if needed based on the
1688 // max/min operation.
1689 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1690 Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1691 return replaceInstUsesWith(CI, Abs);
1692 }
1693
1694 if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1695 return Sel;
1696
1697 if (Instruction *SAdd = matchSAddSubSat(*II))
1698 return SAdd;
1699
1700 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder))
1701 return replaceInstUsesWith(*II, NewMinMax);
1702
1704 return R;
1705
1706 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1707 return NewMinMax;
1708
1709 break;
1710 }
1711 case Intrinsic::bitreverse: {
1712 Value *IIOperand = II->getArgOperand(0);
1713 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
1714 Value *X;
1715 if (match(IIOperand, m_ZExt(m_Value(X))) &&
1716 X->getType()->isIntOrIntVectorTy(1)) {
1717 Type *Ty = II->getType();
1719 return SelectInst::Create(X, ConstantInt::get(Ty, SignBit),
1721 }
1722
1723 if (Instruction *crossLogicOpFold =
1724 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(IIOperand, Builder))
1725 return crossLogicOpFold;
1726
1727 break;
1728 }
1729 case Intrinsic::bswap: {
1730 Value *IIOperand = II->getArgOperand(0);
1731
1732 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
1733 // inverse-shift-of-bswap:
1734 // bswap (shl X, Y) --> lshr (bswap X), Y
1735 // bswap (lshr X, Y) --> shl (bswap X), Y
1736 Value *X, *Y;
1737 if (match(IIOperand, m_OneUse(m_LogicalShift(m_Value(X), m_Value(Y))))) {
1738 // The transform allows undef vector elements, so try a constant match
1739 // first. If knownbits can handle that case, that clause could be removed.
1740 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
1741 const APInt *C;
1742 if ((match(Y, m_APIntAllowUndef(C)) && (*C & 7) == 0) ||
1744 Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1745 BinaryOperator::BinaryOps InverseShift =
1746 cast<BinaryOperator>(IIOperand)->getOpcode() == Instruction::Shl
1747 ? Instruction::LShr
1748 : Instruction::Shl;
1749 return BinaryOperator::Create(InverseShift, NewSwap, Y);
1750 }
1751 }
1752
1753 KnownBits Known = computeKnownBits(IIOperand, 0, II);
1754 uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1755 uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1756 unsigned BW = Known.getBitWidth();
1757
1758 // bswap(x) -> shift(x) if x has exactly one "active byte"
1759 if (BW - LZ - TZ == 8) {
1760 assert(LZ != TZ && "active byte cannot be in the middle");
1761 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
1762 return BinaryOperator::CreateNUWShl(
1763 IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1764 // -> lshr(x) if the "active byte" is in the high part of x
1765 return BinaryOperator::CreateExactLShr(
1766 IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1767 }
1768
1769 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1770 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1771 unsigned C = X->getType()->getScalarSizeInBits() - BW;
1772 Value *CV = ConstantInt::get(X->getType(), C);
1773 Value *V = Builder.CreateLShr(X, CV);
1774 return new TruncInst(V, IIOperand->getType());
1775 }
1776
1777 if (Instruction *crossLogicOpFold =
1778 foldBitOrderCrossLogicOp<Intrinsic::bswap>(IIOperand, Builder)) {
1779 return crossLogicOpFold;
1780 }
1781
1782 break;
1783 }
1784 case Intrinsic::masked_load:
1785 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1786 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1787 break;
1788 case Intrinsic::masked_store:
1789 return simplifyMaskedStore(*II);
1790 case Intrinsic::masked_gather:
1791 return simplifyMaskedGather(*II);
1792 case Intrinsic::masked_scatter:
1793 return simplifyMaskedScatter(*II);
1794 case Intrinsic::launder_invariant_group:
1795 case Intrinsic::strip_invariant_group:
1796 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1797 return replaceInstUsesWith(*II, SkippedBarrier);
1798 break;
1799 case Intrinsic::powi:
1800 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1801 // 0 and 1 are handled in instsimplify
1802 // powi(x, -1) -> 1/x
1803 if (Power->isMinusOne())
1805 II->getArgOperand(0), II);
1806 // powi(x, 2) -> x*x
1807 if (Power->equalsInt(2))
1809 II->getArgOperand(0), II);
1810
1811 if (!Power->getValue()[0]) {
1812 Value *X;
1813 // If power is even:
1814 // powi(-x, p) -> powi(x, p)
1815 // powi(fabs(x), p) -> powi(x, p)
1816 // powi(copysign(x, y), p) -> powi(x, p)
1817 if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1818 match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1819 match(II->getArgOperand(0),
1820 m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1821 return replaceOperand(*II, 0, X);
1822 }
1823 }
1824 break;
1825
1826 case Intrinsic::cttz:
1827 case Intrinsic::ctlz:
1828 if (auto *I = foldCttzCtlz(*II, *this))
1829 return I;
1830 break;
1831
1832 case Intrinsic::ctpop:
1833 if (auto *I = foldCtpop(*II, *this))
1834 return I;
1835 break;
1836
1837 case Intrinsic::fshl:
1838 case Intrinsic::fshr: {
1839 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1840 Type *Ty = II->getType();
1841 unsigned BitWidth = Ty->getScalarSizeInBits();
1842 Constant *ShAmtC;
1843 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC))) {
1844 // Canonicalize a shift amount constant operand to modulo the bit-width.
1845 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1846 Constant *ModuloC =
1847 ConstantFoldBinaryOpOperands(Instruction::URem, ShAmtC, WidthC, DL);
1848 if (!ModuloC)
1849 return nullptr;
1850 if (ModuloC != ShAmtC)
1851 return replaceOperand(*II, 2, ModuloC);
1852
1855 "Shift amount expected to be modulo bitwidth");
1856
1857 // Canonicalize funnel shift right by constant to funnel shift left. This
1858 // is not entirely arbitrary. For historical reasons, the backend may
1859 // recognize rotate left patterns but miss rotate right patterns.
1860 if (IID == Intrinsic::fshr) {
1861 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1862 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1863 Module *Mod = II->getModule();
1864 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1865 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1866 }
1867 assert(IID == Intrinsic::fshl &&
1868 "All funnel shifts by simple constants should go left");
1869
1870 // fshl(X, 0, C) --> shl X, C
1871 // fshl(X, undef, C) --> shl X, C
1872 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1873 return BinaryOperator::CreateShl(Op0, ShAmtC);
1874
1875 // fshl(0, X, C) --> lshr X, (BW-C)
1876 // fshl(undef, X, C) --> lshr X, (BW-C)
1877 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1878 return BinaryOperator::CreateLShr(Op1,
1879 ConstantExpr::getSub(WidthC, ShAmtC));
1880
1881 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1882 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1883 Module *Mod = II->getModule();
1884 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1885 return CallInst::Create(Bswap, { Op0 });
1886 }
1887 if (Instruction *BitOp =
1888 matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ true,
1889 /*MatchBitReversals*/ true))
1890 return BitOp;
1891 }
1892
1893 // Left or right might be masked.
1895 return &CI;
1896
1897 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1898 // so only the low bits of the shift amount are demanded if the bitwidth is
1899 // a power-of-2.
1900 if (!isPowerOf2_32(BitWidth))
1901 break;
1903 KnownBits Op2Known(BitWidth);
1904 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1905 return &CI;
1906 break;
1907 }
1908 case Intrinsic::uadd_with_overflow:
1909 case Intrinsic::sadd_with_overflow: {
1910 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1911 return I;
1912
1913 // Given 2 constant operands whose sum does not overflow:
1914 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
1915 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
1916 Value *X;
1917 const APInt *C0, *C1;
1918 Value *Arg0 = II->getArgOperand(0);
1919 Value *Arg1 = II->getArgOperand(1);
1920 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
1921 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
1922 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
1923 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
1924 bool Overflow;
1925 APInt NewC =
1926 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
1927 if (!Overflow)
1928 return replaceInstUsesWith(
1930 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
1931 }
1932 break;
1933 }
1934
1935 case Intrinsic::umul_with_overflow:
1936 case Intrinsic::smul_with_overflow:
1937 case Intrinsic::usub_with_overflow:
1938 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1939 return I;
1940 break;
1941
1942 case Intrinsic::ssub_with_overflow: {
1943 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
1944 return I;
1945
1946 Constant *C;
1947 Value *Arg0 = II->getArgOperand(0);
1948 Value *Arg1 = II->getArgOperand(1);
1949 // Given a constant C that is not the minimum signed value
1950 // for an integer of a given bit width:
1951 //
1952 // ssubo X, C -> saddo X, -C
1953 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
1954 Value *NegVal = ConstantExpr::getNeg(C);
1955 // Build a saddo call that is equivalent to the discovered
1956 // ssubo call.
1957 return replaceInstUsesWith(
1958 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
1959 Arg0, NegVal));
1960 }
1961
1962 break;
1963 }
1964
1965 case Intrinsic::uadd_sat:
1966 case Intrinsic::sadd_sat:
1967 case Intrinsic::usub_sat:
1968 case Intrinsic::ssub_sat: {
1969 SaturatingInst *SI = cast<SaturatingInst>(II);
1970 Type *Ty = SI->getType();
1971 Value *Arg0 = SI->getLHS();
1972 Value *Arg1 = SI->getRHS();
1973
1974 // Make use of known overflow information.
1975 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
1976 Arg0, Arg1, SI);
1977 switch (OR) {
1979 break;
1981 if (SI->isSigned())
1982 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
1983 else
1984 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
1986 unsigned BitWidth = Ty->getScalarSizeInBits();
1987 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
1988 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
1989 }
1991 unsigned BitWidth = Ty->getScalarSizeInBits();
1992 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
1993 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
1994 }
1995 }
1996
1997 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
1998 Constant *C;
1999 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2000 C->isNotMinSignedValue()) {
2001 Value *NegVal = ConstantExpr::getNeg(C);
2002 return replaceInstUsesWith(
2004 Intrinsic::sadd_sat, Arg0, NegVal));
2005 }
2006
2007 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2008 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2009 // if Val and Val2 have the same sign
2010 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2011 Value *X;
2012 const APInt *Val, *Val2;
2013 APInt NewVal;
2014 bool IsUnsigned =
2015 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2016 if (Other->getIntrinsicID() == IID &&
2017 match(Arg1, m_APInt(Val)) &&
2018 match(Other->getArgOperand(0), m_Value(X)) &&
2019 match(Other->getArgOperand(1), m_APInt(Val2))) {
2020 if (IsUnsigned)
2021 NewVal = Val->uadd_sat(*Val2);
2022 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2023 bool Overflow;
2024 NewVal = Val->sadd_ov(*Val2, Overflow);
2025 if (Overflow) {
2026 // Both adds together may add more than SignedMaxValue
2027 // without saturating the final result.
2028 break;
2029 }
2030 } else {
2031 // Cannot fold saturated addition with different signs.
2032 break;
2033 }
2034
2035 return replaceInstUsesWith(
2037 IID, X, ConstantInt::get(II->getType(), NewVal)));
2038 }
2039 }
2040 break;
2041 }
2042
2043 case Intrinsic::minnum:
2044 case Intrinsic::maxnum:
2045 case Intrinsic::minimum:
2046 case Intrinsic::maximum: {
2047 Value *Arg0 = II->getArgOperand(0);
2048 Value *Arg1 = II->getArgOperand(1);
2049 Value *X, *Y;
2050 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2051 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2052 // If both operands are negated, invert the call and negate the result:
2053 // min(-X, -Y) --> -(max(X, Y))
2054 // max(-X, -Y) --> -(min(X, Y))
2055 Intrinsic::ID NewIID;
2056 switch (IID) {
2057 case Intrinsic::maxnum:
2058 NewIID = Intrinsic::minnum;
2059 break;
2060 case Intrinsic::minnum:
2061 NewIID = Intrinsic::maxnum;
2062 break;
2063 case Intrinsic::maximum:
2064 NewIID = Intrinsic::minimum;
2065 break;
2066 case Intrinsic::minimum:
2067 NewIID = Intrinsic::maximum;
2068 break;
2069 default:
2070 llvm_unreachable("unexpected intrinsic ID");
2071 }
2072 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2073 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
2074 FNeg->copyIRFlags(II);
2075 return FNeg;
2076 }
2077
2078 // m(m(X, C2), C1) -> m(X, C)
2079 const APFloat *C1, *C2;
2080 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2081 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2082 ((match(M->getArgOperand(0), m_Value(X)) &&
2083 match(M->getArgOperand(1), m_APFloat(C2))) ||
2084 (match(M->getArgOperand(1), m_Value(X)) &&
2085 match(M->getArgOperand(0), m_APFloat(C2))))) {
2086 APFloat Res(0.0);
2087 switch (IID) {
2088 case Intrinsic::maxnum:
2089 Res = maxnum(*C1, *C2);
2090 break;
2091 case Intrinsic::minnum:
2092 Res = minnum(*C1, *C2);
2093 break;
2094 case Intrinsic::maximum:
2095 Res = maximum(*C1, *C2);
2096 break;
2097 case Intrinsic::minimum:
2098 Res = minimum(*C1, *C2);
2099 break;
2100 default:
2101 llvm_unreachable("unexpected intrinsic ID");
2102 }
2104 IID, X, ConstantFP::get(Arg0->getType(), Res), II);
2105 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
2106 // was a simplification (so Arg0 and its original flags could
2107 // propagate?)
2108 NewCall->andIRFlags(M);
2109 return replaceInstUsesWith(*II, NewCall);
2110 }
2111 }
2112
2113 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
2114 if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
2115 match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
2116 X->getType() == Y->getType()) {
2117 Value *NewCall =
2118 Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
2119 return new FPExtInst(NewCall, II->getType());
2120 }
2121
2122 // max X, -X --> fabs X
2123 // min X, -X --> -(fabs X)
2124 // TODO: Remove one-use limitation? That is obviously better for max.
2125 // It would be an extra instruction for min (fnabs), but that is
2126 // still likely better for analysis and codegen.
2127 if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
2128 (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
2129 Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2130 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
2131 R = Builder.CreateFNegFMF(R, II);
2132 return replaceInstUsesWith(*II, R);
2133 }
2134
2135 break;
2136 }
2137 case Intrinsic::matrix_multiply: {
2138 // Optimize negation in matrix multiplication.
2139
2140 // -A * -B -> A * B
2141 Value *A, *B;
2142 if (match(II->getArgOperand(0), m_FNeg(m_Value(A))) &&
2143 match(II->getArgOperand(1), m_FNeg(m_Value(B)))) {
2144 replaceOperand(*II, 0, A);
2145 replaceOperand(*II, 1, B);
2146 return II;
2147 }
2148
2149 Value *Op0 = II->getOperand(0);
2150 Value *Op1 = II->getOperand(1);
2151 Value *OpNotNeg, *NegatedOp;
2152 unsigned NegatedOpArg, OtherOpArg;
2153 if (match(Op0, m_FNeg(m_Value(OpNotNeg)))) {
2154 NegatedOp = Op0;
2155 NegatedOpArg = 0;
2156 OtherOpArg = 1;
2157 } else if (match(Op1, m_FNeg(m_Value(OpNotNeg)))) {
2158 NegatedOp = Op1;
2159 NegatedOpArg = 1;
2160 OtherOpArg = 0;
2161 } else
2162 // Multiplication doesn't have a negated operand.
2163 break;
2164
2165 // Only optimize if the negated operand has only one use.
2166 if (!NegatedOp->hasOneUse())
2167 break;
2168
2169 Value *OtherOp = II->getOperand(OtherOpArg);
2170 VectorType *RetTy = cast<VectorType>(II->getType());
2171 VectorType *NegatedOpTy = cast<VectorType>(NegatedOp->getType());
2172 VectorType *OtherOpTy = cast<VectorType>(OtherOp->getType());
2173 ElementCount NegatedCount = NegatedOpTy->getElementCount();
2174 ElementCount OtherCount = OtherOpTy->getElementCount();
2175 ElementCount RetCount = RetTy->getElementCount();
2176 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
2177 if (ElementCount::isKnownGT(NegatedCount, OtherCount) &&
2178 ElementCount::isKnownLT(OtherCount, RetCount)) {
2179 Value *InverseOtherOp = Builder.CreateFNeg(OtherOp);
2180 replaceOperand(*II, NegatedOpArg, OpNotNeg);
2181 replaceOperand(*II, OtherOpArg, InverseOtherOp);
2182 return II;
2183 }
2184 // (-A) * B -> -(A * B), if it is cheaper to negate the result
2185 if (ElementCount::isKnownGT(NegatedCount, RetCount)) {
2186 SmallVector<Value *, 5> NewArgs(II->args());
2187 NewArgs[NegatedOpArg] = OpNotNeg;
2188 Instruction *NewMul =
2189 Builder.CreateIntrinsic(II->getType(), IID, NewArgs, II);
2190 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(NewMul, II));
2191 }
2192 break;
2193 }
2194 case Intrinsic::fmuladd: {
2195 // Canonicalize fast fmuladd to the separate fmul + fadd.
2196 if (II->isFast()) {
2200 II->getArgOperand(1));
2202 Add->takeName(II);
2203 return replaceInstUsesWith(*II, Add);
2204 }
2205
2206 // Try to simplify the underlying FMul.
2207 if (Value *V = simplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2208 II->getFastMathFlags(),
2209 SQ.getWithInstruction(II))) {
2210 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2211 FAdd->copyFastMathFlags(II);
2212 return FAdd;
2213 }
2214
2215 [[fallthrough]];
2216 }
2217 case Intrinsic::fma: {
2218 // fma fneg(x), fneg(y), z -> fma x, y, z
2219 Value *Src0 = II->getArgOperand(0);
2220 Value *Src1 = II->getArgOperand(1);
2221 Value *X, *Y;
2222 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2223 replaceOperand(*II, 0, X);
2224 replaceOperand(*II, 1, Y);
2225 return II;
2226 }
2227
2228 // fma fabs(x), fabs(x), z -> fma x, x, z
2229 if (match(Src0, m_FAbs(m_Value(X))) &&
2230 match(Src1, m_FAbs(m_Specific(X)))) {
2231 replaceOperand(*II, 0, X);
2232 replaceOperand(*II, 1, X);
2233 return II;
2234 }
2235
2236 // Try to simplify the underlying FMul. We can only apply simplifications
2237 // that do not require rounding.
2238 if (Value *V = simplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
2239 II->getFastMathFlags(),
2240 SQ.getWithInstruction(II))) {
2241 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2242 FAdd->copyFastMathFlags(II);
2243 return FAdd;
2244 }
2245
2246 // fma x, y, 0 -> fmul x, y
2247 // This is always valid for -0.0, but requires nsz for +0.0 as
2248 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
2249 if (match(II->getArgOperand(2), m_NegZeroFP()) ||
2250 (match(II->getArgOperand(2), m_PosZeroFP()) &&
2252 return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
2253
2254 break;
2255 }
2256 case Intrinsic::copysign: {
2257 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
2258 if (SignBitMustBeZero(Sign, DL, &TLI)) {
2259 // If we know that the sign argument is positive, reduce to FABS:
2260 // copysign Mag, +Sign --> fabs Mag
2261 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2262 return replaceInstUsesWith(*II, Fabs);
2263 }
2264 // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
2265 const APFloat *C;
2266 if (match(Sign, m_APFloat(C)) && C->isNegative()) {
2267 // If we know that the sign argument is negative, reduce to FNABS:
2268 // copysign Mag, -Sign --> fneg (fabs Mag)
2269 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2270 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
2271 }
2272
2273 // Propagate sign argument through nested calls:
2274 // copysign Mag, (copysign ?, X) --> copysign Mag, X
2275 Value *X;
2276 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
2277 return replaceOperand(*II, 1, X);
2278
2279 // Peek through changes of magnitude's sign-bit. This call rewrites those:
2280 // copysign (fabs X), Sign --> copysign X, Sign
2281 // copysign (fneg X), Sign --> copysign X, Sign
2282 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
2283 return replaceOperand(*II, 0, X);
2284
2285 break;
2286 }
2287 case Intrinsic::fabs: {
2288 Value *Cond, *TVal, *FVal;
2289 if (match(II->getArgOperand(0),
2290 m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
2291 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
2292 if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
2293 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
2294 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
2295 return SelectInst::Create(Cond, AbsT, AbsF);
2296 }
2297 // fabs (select Cond, -FVal, FVal) --> fabs FVal
2298 if (match(TVal, m_FNeg(m_Specific(FVal))))
2299 return replaceOperand(*II, 0, FVal);
2300 // fabs (select Cond, TVal, -TVal) --> fabs TVal
2301 if (match(FVal, m_FNeg(m_Specific(TVal))))
2302 return replaceOperand(*II, 0, TVal);
2303 }
2304
2305 Value *Magnitude, *Sign;
2306 if (match(II->getArgOperand(0),
2307 m_CopySign(m_Value(Magnitude), m_Value(Sign)))) {
2308 // fabs (copysign x, y) -> (fabs x)
2309 CallInst *AbsSign =
2310 Builder.CreateCall(II->getCalledFunction(), {Magnitude});
2311 AbsSign->copyFastMathFlags(II);
2312 return replaceInstUsesWith(*II, AbsSign);
2313 }
2314
2315 [[fallthrough]];
2316 }
2317 case Intrinsic::ceil:
2318 case Intrinsic::floor:
2319 case Intrinsic::round:
2320 case Intrinsic::roundeven:
2321 case Intrinsic::nearbyint:
2322 case Intrinsic::rint:
2323 case Intrinsic::trunc: {
2324 Value *ExtSrc;
2325 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2326 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2327 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2328 return new FPExtInst(NarrowII, II->getType());
2329 }
2330 break;
2331 }
2332 case Intrinsic::cos:
2333 case Intrinsic::amdgcn_cos: {
2334 Value *X;
2335 Value *Src = II->getArgOperand(0);
2336 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
2337 // cos(-x) -> cos(x)
2338 // cos(fabs(x)) -> cos(x)
2339 return replaceOperand(*II, 0, X);
2340 }
2341 break;
2342 }
2343 case Intrinsic::sin: {
2344 Value *X;
2345 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2346 // sin(-x) --> -sin(x)
2347 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
2348 Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
2349 FNeg->copyFastMathFlags(II);
2350 return FNeg;
2351 }
2352 break;
2353 }
2354 case Intrinsic::ptrauth_auth:
2355 case Intrinsic::ptrauth_resign: {
2356 // (sign|resign) + (auth|resign) can be folded by omitting the middle
2357 // sign+auth component if the key and discriminator match.
2358 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
2359 Value *Key = II->getArgOperand(1);
2360 Value *Disc = II->getArgOperand(2);
2361
2362 // AuthKey will be the key we need to end up authenticating against in
2363 // whatever we replace this sequence with.
2364 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
2365 if (auto CI = dyn_cast<CallBase>(II->getArgOperand(0))) {
2366 BasePtr = CI->getArgOperand(0);
2367 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
2368 if (CI->getArgOperand(1) != Key || CI->getArgOperand(2) != Disc)
2369 break;
2370 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
2371 if (CI->getArgOperand(3) != Key || CI->getArgOperand(4) != Disc)
2372 break;
2373 AuthKey = CI->getArgOperand(1);
2374 AuthDisc = CI->getArgOperand(2);
2375 } else
2376 break;
2377 } else
2378 break;
2379
2380 unsigned NewIntrin;
2381 if (AuthKey && NeedSign) {
2382 // resign(0,1) + resign(1,2) = resign(0, 2)
2383 NewIntrin = Intrinsic::ptrauth_resign;
2384 } else if (AuthKey) {
2385 // resign(0,1) + auth(1) = auth(0)
2386 NewIntrin = Intrinsic::ptrauth_auth;
2387 } else if (NeedSign) {
2388 // sign(0) + resign(0, 1) = sign(1)
2389 NewIntrin = Intrinsic::ptrauth_sign;
2390 } else {
2391 // sign(0) + auth(0) = nop
2392 replaceInstUsesWith(*II, BasePtr);
2394 return nullptr;
2395 }
2396
2397 SmallVector<Value *, 4> CallArgs;
2398 CallArgs.push_back(BasePtr);
2399 if (AuthKey) {
2400 CallArgs.push_back(AuthKey);
2401 CallArgs.push_back(AuthDisc);
2402 }
2403
2404 if (NeedSign) {
2405 CallArgs.push_back(II->getArgOperand(3));
2406 CallArgs.push_back(II->getArgOperand(4));
2407 }
2408
2409 Function *NewFn = Intrinsic::getDeclaration(II->getModule(), NewIntrin);
2410 return CallInst::Create(NewFn, CallArgs);
2411 }
2412 case Intrinsic::arm_neon_vtbl1:
2413 case Intrinsic::aarch64_neon_tbl1:
2414 if (Value *V = simplifyNeonTbl1(*II, Builder))
2415 return replaceInstUsesWith(*II, V);
2416 break;
2417
2418 case Intrinsic::arm_neon_vmulls:
2419 case Intrinsic::arm_neon_vmullu:
2420 case Intrinsic::aarch64_neon_smull:
2421 case Intrinsic::aarch64_neon_umull: {
2422 Value *Arg0 = II->getArgOperand(0);
2423 Value *Arg1 = II->getArgOperand(1);
2424
2425 // Handle mul by zero first:
2426 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2428 }
2429
2430 // Check for constant LHS & RHS - in this case we just simplify.
2431 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
2432 IID == Intrinsic::aarch64_neon_umull);
2433 VectorType *NewVT = cast<VectorType>(II->getType());
2434 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2435 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2436 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2437 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2438
2439 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
2440 }
2441
2442 // Couldn't simplify - canonicalize constant to the RHS.
2443 std::swap(Arg0, Arg1);
2444 }
2445
2446 // Handle mul by one:
2447 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2448 if (ConstantInt *Splat =
2449 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2450 if (Splat->isOne())
2451 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2452 /*isSigned=*/!Zext);
2453
2454 break;
2455 }
2456 case Intrinsic::arm_neon_aesd:
2457 case Intrinsic::arm_neon_aese:
2458 case Intrinsic::aarch64_crypto_aesd:
2459 case Intrinsic::aarch64_crypto_aese: {
2460 Value *DataArg = II->getArgOperand(0);
2461 Value *KeyArg = II->getArgOperand(1);
2462
2463 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
2464 Value *Data, *Key;
2465 if (match(KeyArg, m_ZeroInt()) &&
2466 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
2467 replaceOperand(*II, 0, Data);
2468 replaceOperand(*II, 1, Key);
2469 return II;
2470 }
2471 break;
2472 }
2473 case Intrinsic::hexagon_V6_vandvrt:
2474 case Intrinsic::hexagon_V6_vandvrt_128B: {
2475 // Simplify Q -> V -> Q conversion.
2476 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2477 Intrinsic::ID ID0 = Op0->getIntrinsicID();
2478 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
2479 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
2480 break;
2481 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
2482 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
2483 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
2484 // Check if every byte has common bits in Bytes and Mask.
2485 uint64_t C = Bytes1 & Mask1;
2486 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
2487 return replaceInstUsesWith(*II, Op0->getArgOperand(0));
2488 }
2489 break;
2490 }
2491 case Intrinsic::stackrestore: {
2492 enum class ClassifyResult {
2493 None,
2494 Alloca,
2495 StackRestore,
2496 CallWithSideEffects,
2497 };
2498 auto Classify = [](const Instruction *I) {
2499 if (isa<AllocaInst>(I))
2500 return ClassifyResult::Alloca;
2501
2502 if (auto *CI = dyn_cast<CallInst>(I)) {
2503 if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
2504 if (II->getIntrinsicID() == Intrinsic::stackrestore)
2505 return ClassifyResult::StackRestore;
2506
2507 if (II->mayHaveSideEffects())
2508 return ClassifyResult::CallWithSideEffects;
2509 } else {
2510 // Consider all non-intrinsic calls to be side effects
2511 return ClassifyResult::CallWithSideEffects;
2512 }
2513 }
2514
2515 return ClassifyResult::None;
2516 };
2517
2518 // If the stacksave and the stackrestore are in the same BB, and there is
2519 // no intervening call, alloca, or stackrestore of a different stacksave,
2520 // remove the restore. This can happen when variable allocas are DCE'd.
2521 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2522 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
2523 SS->getParent() == II->getParent()) {
2524 BasicBlock::iterator BI(SS);
2525 bool CannotRemove = false;
2526 for (++BI; &*BI != II; ++BI) {
2527 switch (Classify(&*BI)) {
2528 case ClassifyResult::None:
2529 // So far so good, look at next instructions.
2530 break;
2531
2532 case ClassifyResult::StackRestore:
2533 // If we found an intervening stackrestore for a different
2534 // stacksave, we can't remove the stackrestore. Otherwise, continue.
2535 if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
2536 CannotRemove = true;
2537 break;
2538
2539 case ClassifyResult::Alloca:
2540 case ClassifyResult::CallWithSideEffects:
2541 // If we found an alloca, a non-intrinsic call, or an intrinsic
2542 // call with side effects, we can't remove the stackrestore.
2543 CannotRemove = true;
2544 break;
2545 }
2546 if (CannotRemove)
2547 break;
2548 }
2549
2550 if (!CannotRemove)
2551 return eraseInstFromFunction(CI);
2552 }
2553 }
2554
2555 // Scan down this block to see if there is another stack restore in the
2556 // same block without an intervening call/alloca.
2557 BasicBlock::iterator BI(II);
2558 Instruction *TI = II->getParent()->getTerminator();
2559 bool CannotRemove = false;
2560 for (++BI; &*BI != TI; ++BI) {
2561 switch (Classify(&*BI)) {
2562 case ClassifyResult::None:
2563 // So far so good, look at next instructions.
2564 break;
2565
2566 case ClassifyResult::StackRestore:
2567 // If there is a stackrestore below this one, remove this one.
2568 return eraseInstFromFunction(CI);
2569
2570 case ClassifyResult::Alloca:
2571 case ClassifyResult::CallWithSideEffects:
2572 // If we found an alloca, a non-intrinsic call, or an intrinsic call
2573 // with side effects (such as llvm.stacksave and llvm.read_register),
2574 // we can't remove the stack restore.
2575 CannotRemove = true;
2576 break;
2577 }
2578 if (CannotRemove)
2579 break;
2580 }
2581
2582 // If the stack restore is in a return, resume, or unwind block and if there
2583 // are no allocas or calls between the restore and the return, nuke the
2584 // restore.
2585 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
2586 return eraseInstFromFunction(CI);
2587 break;
2588 }
2589 case Intrinsic::lifetime_end:
2590 // Asan needs to poison memory to detect invalid access which is possible
2591 // even for empty lifetime range.
2592 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2593 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
2594 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2595 break;
2596
2597 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
2598 return I.getIntrinsicID() == Intrinsic::lifetime_start;
2599 }))
2600 return nullptr;
2601 break;
2602 case Intrinsic::assume: {
2603 Value *IIOperand = II->getArgOperand(0);
2605 II->getOperandBundlesAsDefs(OpBundles);
2606
2607 /// This will remove the boolean Condition from the assume given as
2608 /// argument and remove the assume if it becomes useless.
2609 /// always returns nullptr for use as a return values.
2610 auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
2611 assert(isa<AssumeInst>(Assume));
2612 if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
2613 return eraseInstFromFunction(CI);
2615 return nullptr;
2616 };
2617 // Remove an assume if it is followed by an identical assume.
2618 // TODO: Do we need this? Unless there are conflicting assumptions, the
2619 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
2621 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2622 return RemoveConditionFromAssume(Next);
2623
2624 // Canonicalize assume(a && b) -> assume(a); assume(b);
2625 // Note: New assumption intrinsics created here are registered by
2626 // the InstCombineIRInserter object.
2627 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
2628 Value *AssumeIntrinsic = II->getCalledOperand();
2629 Value *A, *B;
2630 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
2631 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
2632 II->getName());
2633 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
2634 return eraseInstFromFunction(*II);
2635 }
2636 // assume(!(a || b)) -> assume(!a); assume(!b);
2637 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
2638 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2639 Builder.CreateNot(A), OpBundles, II->getName());
2640 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2641 Builder.CreateNot(B), II->getName());
2642 return eraseInstFromFunction(*II);
2643 }
2644
2645 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2646 // (if assume is valid at the load)
2647 CmpInst::Predicate Pred;
2649 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2650 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2651 LHS->getType()->isPointerTy() &&
2653 MDNode *MD = MDNode::get(II->getContext(), std::nullopt);
2654 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2655 return RemoveConditionFromAssume(II);
2656
2657 // TODO: apply nonnull return attributes to calls and invokes
2658 // TODO: apply range metadata for range check patterns?
2659 }
2660
2661 // Separate storage assumptions apply to the underlying allocations, not any
2662 // particular pointer within them. When evaluating the hints for AA purposes
2663 // we getUnderlyingObject them; by precomputing the answers here we can
2664 // avoid having to do so repeatedly there.
2665 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2667 if (OBU.getTagName() == "separate_storage") {
2668 assert(OBU.Inputs.size() == 2);
2669 auto MaybeSimplifyHint = [&](const Use &U) {
2670 Value *Hint = U.get();
2671 // Not having a limit is safe because InstCombine removes unreachable
2672 // code.
2673 Value *UnderlyingObject = getUnderlyingObject(Hint, /*MaxLookup*/ 0);
2674 if (Hint != UnderlyingObject)
2675 replaceUse(const_cast<Use &>(U), UnderlyingObject);
2676 };
2677 MaybeSimplifyHint(OBU.Inputs[0]);
2678 MaybeSimplifyHint(OBU.Inputs[1]);
2679 }
2680 }
2681
2682 // Convert nonnull assume like:
2683 // %A = icmp ne i32* %PTR, null
2684 // call void @llvm.assume(i1 %A)
2685 // into
2686 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
2688 match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
2689 Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
2690 if (auto *Replacement = buildAssumeFromKnowledge(
2691 {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2692
2693 Replacement->insertBefore(Next);
2694 AC.registerAssumption(Replacement);
2695 return RemoveConditionFromAssume(II);
2696 }
2697 }
2698
2699 // Convert alignment assume like:
2700 // %B = ptrtoint i32* %A to i64
2701 // %C = and i64 %B, Constant
2702 // %D = icmp eq i64 %C, 0
2703 // call void @llvm.assume(i1 %D)
2704 // into
2705 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
2706 uint64_t AlignMask;
2708 match(IIOperand,
2709 m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2710 m_Zero())) &&
2711 Pred == CmpInst::ICMP_EQ) {
2712 if (isPowerOf2_64(AlignMask + 1)) {
2713 uint64_t Offset = 0;
2715 if (match(A, m_PtrToInt(m_Value(A)))) {
2716 /// Note: this doesn't preserve the offset information but merges
2717 /// offset and alignment.
2718 /// TODO: we can generate a GEP instead of merging the alignment with
2719 /// the offset.
2720 RetainedKnowledge RK{Attribute::Alignment,
2721 (unsigned)MinAlign(Offset, AlignMask + 1), A};
2722 if (auto *Replacement =
2723 buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2724
2725 Replacement->insertAfter(II);
2726 AC.registerAssumption(Replacement);
2727 }
2728 return RemoveConditionFromAssume(II);
2729 }
2730 }
2731 }
2732
2733 /// Canonicalize Knowledge in operand bundles.
2735 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2736 auto &BOI = II->bundle_op_info_begin()[Idx];
2738 llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2739 if (BOI.End - BOI.Begin > 2)
2740 continue; // Prevent reducing knowledge in an align with offset since
2741 // extracting a RetainedKnowledge from them looses offset
2742 // information
2743 RetainedKnowledge CanonRK =
2744 llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2746 &getDominatorTree());
2747 if (CanonRK == RK)
2748 continue;
2749 if (!CanonRK) {
2750 if (BOI.End - BOI.Begin > 0) {
2751 Worklist.pushValue(II->op_begin()[BOI.Begin]);
2752 Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2753 }
2754 continue;
2755 }
2756 assert(RK.AttrKind == CanonRK.AttrKind);
2757 if (BOI.End - BOI.Begin > 0)
2758 II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2759 if (BOI.End - BOI.Begin > 1)
2760 II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2761 Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2762 if (RK.WasOn)
2764 return II;
2765 }
2766 }
2767
2768 // If there is a dominating assume with the same condition as this one,
2769 // then this one is redundant, and should be removed.
2770 KnownBits Known(1);
2771 computeKnownBits(IIOperand, Known, 0, II);
2772 if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2773 return eraseInstFromFunction(*II);
2774
2775 // Update the cache of affected values for this assumption (we might be
2776 // here because we just simplified the condition).
2777 AC.updateAffectedValues(cast<AssumeInst>(II));
2778 break;
2779 }
2780 case Intrinsic::experimental_guard: {
2781 // Is this guard followed by another guard? We scan forward over a small
2782 // fixed window of instructions to handle common cases with conditions
2783 // computed between guards.
2784 Instruction *NextInst = II->getNextNonDebugInstruction();
2785 for (unsigned i = 0; i < GuardWideningWindow; i++) {
2786 // Note: Using context-free form to avoid compile time blow up
2787 if (!isSafeToSpeculativelyExecute(NextInst))
2788 break;
2789 NextInst = NextInst->getNextNonDebugInstruction();
2790 }
2791 Value *NextCond = nullptr;
2792 if (match(NextInst,
2793 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
2794 Value *CurrCond = II->getArgOperand(0);
2795
2796 // Remove a guard that it is immediately preceded by an identical guard.
2797 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
2798 if (CurrCond != NextCond) {
2800 while (MoveI != NextInst) {
2801 auto *Temp = MoveI;
2802 MoveI = MoveI->getNextNonDebugInstruction();
2803 Temp->moveBefore(II);
2804 }
2805 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
2806 }
2807 eraseInstFromFunction(*NextInst);
2808 return II;
2809 }
2810 break;
2811 }
2812 case Intrinsic::vector_insert: {
2813 Value *Vec = II->getArgOperand(0);
2814 Value *SubVec = II->getArgOperand(1);
2815 Value *Idx = II->getArgOperand(2);
2816 auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
2817 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2818 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
2819
2820 // Only canonicalize if the destination vector, Vec, and SubVec are all
2821 // fixed vectors.
2822 if (DstTy && VecTy && SubVecTy) {
2823 unsigned DstNumElts = DstTy->getNumElements();
2824 unsigned VecNumElts = VecTy->getNumElements();
2825 unsigned SubVecNumElts = SubVecTy->getNumElements();
2826 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2827
2828 // An insert that entirely overwrites Vec with SubVec is a nop.
2829 if (VecNumElts == SubVecNumElts)
2830 return replaceInstUsesWith(CI, SubVec);
2831
2832 // Widen SubVec into a vector of the same width as Vec, since
2833 // shufflevector requires the two input vectors to be the same width.
2834 // Elements beyond the bounds of SubVec within the widened vector are
2835 // undefined.
2836 SmallVector<int, 8> WidenMask;
2837 unsigned i;
2838 for (i = 0; i != SubVecNumElts; ++i)
2839 WidenMask.push_back(i);
2840 for (; i != VecNumElts; ++i)
2841 WidenMask.push_back(PoisonMaskElem);
2842
2843 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
2844
2846 for (unsigned i = 0; i != IdxN; ++i)
2847 Mask.push_back(i);
2848 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
2849 Mask.push_back(i);
2850 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
2851 Mask.push_back(i);
2852
2853 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
2854 return replaceInstUsesWith(CI, Shuffle);
2855 }
2856 break;
2857 }
2858 case Intrinsic::vector_extract: {
2859 Value *Vec = II->getArgOperand(0);
2860 Value *Idx = II->getArgOperand(1);
2861
2862 Type *ReturnType = II->getType();
2863 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
2864 // ExtractIdx)
2865 unsigned ExtractIdx = cast<ConstantInt>(Idx)->getZExtValue();
2866 Value *InsertTuple, *InsertIdx, *InsertValue;
2867 if (match(Vec, m_Intrinsic<Intrinsic::vector_insert>(m_Value(InsertTuple),
2868 m_Value(InsertValue),
2869 m_Value(InsertIdx))) &&
2870 InsertValue->getType() == ReturnType) {
2871 unsigned Index = cast<ConstantInt>(InsertIdx)->getZExtValue();
2872 // Case where we get the same index right after setting it.
2873 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
2874 // InsertValue
2875 if (ExtractIdx == Index)
2876 return replaceInstUsesWith(CI, InsertValue);
2877 // If we are getting a different index than what was set in the
2878 // insert.vector intrinsic. We can just set the input tuple to the one up
2879 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
2880 // InsertIndex), ExtractIndex)
2881 // --> extract.vector(InsertTuple, ExtractIndex)
2882 else
2883 return replaceOperand(CI, 0, InsertTuple);
2884 }
2885
2886 auto *DstTy = dyn_cast<FixedVectorType>(ReturnType);
2887 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
2888
2889 // Only canonicalize if the the destination vector and Vec are fixed
2890 // vectors.
2891 if (DstTy && VecTy) {
2892 unsigned DstNumElts = DstTy->getNumElements();
2893 unsigned VecNumElts = VecTy->getNumElements();
2894 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
2895
2896 // Extracting the entirety of Vec is a nop.
2897 if (VecNumElts == DstNumElts) {
2898 replaceInstUsesWith(CI, Vec);
2899 return eraseInstFromFunction(CI);
2900 }
2901
2903 for (unsigned i = 0; i != DstNumElts; ++i)
2904 Mask.push_back(IdxN + i);
2905
2906 Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
2907 return replaceInstUsesWith(CI, Shuffle);
2908 }
2909 break;
2910 }
2911 case Intrinsic::experimental_vector_reverse: {
2912 Value *BO0, *BO1, *X, *Y;
2913 Value *Vec = II->getArgOperand(0);
2914 if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
2915 auto *OldBinOp = cast<BinaryOperator>(Vec);
2916 if (match(BO0, m_VecReverse(m_Value(X)))) {
2917 // rev(binop rev(X), rev(Y)) --> binop X, Y
2918 if (match(BO1, m_VecReverse(m_Value(Y))))
2919 return replaceInstUsesWith(CI,
2921 OldBinOp->getOpcode(), X, Y, OldBinOp,
2922 OldBinOp->getName(), II));
2923 // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
2924 if (isSplatValue(BO1))
2925 return replaceInstUsesWith(CI,
2927 OldBinOp->getOpcode(), X, BO1,
2928 OldBinOp, OldBinOp->getName(), II));
2929 }
2930 // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
2931 if (match(BO1, m_VecReverse(m_Value(Y))) && isSplatValue(BO0))
2933 OldBinOp->getOpcode(), BO0, Y,
2934 OldBinOp, OldBinOp->getName(), II));
2935 }
2936 // rev(unop rev(X)) --> unop X
2937 if (match(Vec, m_OneUse(m_UnOp(m_VecReverse(m_Value(X)))))) {
2938 auto *OldUnOp = cast<UnaryOperator>(Vec);
2940 OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
2941 return replaceInstUsesWith(CI, NewUnOp);
2942 }
2943 break;
2944 }
2945 case Intrinsic::vector_reduce_or:
2946 case Intrinsic::vector_reduce_and: {
2947 // Canonicalize logical or/and reductions:
2948 // Or reduction for i1 is represented as:
2949 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2950 // %res = cmp ne iReduxWidth %val, 0
2951 // And reduction for i1 is represented as:
2952 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
2953 // %res = cmp eq iReduxWidth %val, 11111
2954 Value *Arg = II->getArgOperand(0);
2955 Value *Vect;
2956 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2957 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2958 if (FTy->getElementType() == Builder.getInt1Ty()) {
2960 Vect, Builder.getIntNTy(FTy->getNumElements()));
2961 if (IID == Intrinsic::vector_reduce_and) {
2962 Res = Builder.CreateICmpEQ(
2964 } else {
2965 assert(IID == Intrinsic::vector_reduce_or &&
2966 "Expected or reduction.");
2967 Res = Builder.CreateIsNotNull(Res);
2968 }
2969 if (Arg != Vect)
2970 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
2971 II->getType());
2972 return replaceInstUsesWith(CI, Res);
2973 }
2974 }
2975 [[fallthrough]];
2976 }
2977 case Intrinsic::vector_reduce_add: {
2978 if (IID == Intrinsic::vector_reduce_add) {
2979 // Convert vector_reduce_add(ZExt(<n x i1>)) to
2980 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2981 // Convert vector_reduce_add(SExt(<n x i1>)) to
2982 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
2983 // Convert vector_reduce_add(<n x i1>) to
2984 // Trunc(ctpop(bitcast <n x i1> to in)).
2985 Value *Arg = II->getArgOperand(0);
2986 Value *Vect;
2987 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
2988 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
2989 if (FTy->getElementType() == Builder.getInt1Ty()) {
2991 Vect, Builder.getIntNTy(FTy->getNumElements()));
2992 Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
2993 if (Res->getType() != II->getType())
2994 Res = Builder.CreateZExtOrTrunc(Res, II->getType());
2995 if (Arg != Vect &&
2996 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
2997 Res = Builder.CreateNeg(Res);
2998 return replaceInstUsesWith(CI, Res);
2999 }
3000 }
3001 }
3002 [[fallthrough]];
3003 }
3004 case Intrinsic::vector_reduce_xor: {
3005 if (IID == Intrinsic::vector_reduce_xor) {
3006 // Exclusive disjunction reduction over the vector with
3007 // (potentially-extended) i1 element type is actually a
3008 // (potentially-extended) arithmetic `add` reduction over the original
3009 // non-extended value:
3010 // vector_reduce_xor(?ext(<n x i1>))
3011 // -->
3012 // ?ext(vector_reduce_add(<n x i1>))
3013 Value *Arg = II->getArgOperand(0);
3014 Value *Vect;
3015 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3016 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3017 if (FTy->getElementType() == Builder.getInt1Ty()) {
3018 Value *Res = Builder.CreateAddReduce(Vect);
3019 if (Arg != Vect)
3020 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3021 II->getType());
3022 return replaceInstUsesWith(CI, Res);
3023 }
3024 }
3025 }
3026 [[fallthrough]];
3027 }
3028 case Intrinsic::vector_reduce_mul: {
3029 if (IID == Intrinsic::vector_reduce_mul) {
3030 // Multiplicative reduction over the vector with (potentially-extended)
3031 // i1 element type is actually a (potentially zero-extended)
3032 // logical `and` reduction over the original non-extended value:
3033 // vector_reduce_mul(?ext(<n x i1>))
3034 // -->
3035 // zext(vector_reduce_and(<n x i1>))
3036 Value *Arg = II->getArgOperand(0);
3037 Value *Vect;
3038 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3039 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3040 if (FTy->getElementType() == Builder.getInt1Ty()) {
3041 Value *Res = Builder.CreateAndReduce(Vect);
3042 if (Res->getType() != II->getType())
3043 Res = Builder.CreateZExt(Res, II->getType());
3044 return replaceInstUsesWith(CI, Res);
3045 }
3046 }
3047 }
3048 [[fallthrough]];
3049 }
3050 case Intrinsic::vector_reduce_umin:
3051 case Intrinsic::vector_reduce_umax: {
3052 if (IID == Intrinsic::vector_reduce_umin ||
3053 IID == Intrinsic::vector_reduce_umax) {
3054 // UMin/UMax reduction over the vector with (potentially-extended)
3055 // i1 element type is actually a (potentially-extended)
3056 // logical `and`/`or` reduction over the original non-extended value:
3057 // vector_reduce_u{min,max}(?ext(<n x i1>))
3058 // -->
3059 // ?ext(vector_reduce_{and,or}(<n x i1>))
3060 Value *Arg = II->getArgOperand(0);
3061 Value *Vect;
3062 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3063 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3064 if (FTy->getElementType() == Builder.getInt1Ty()) {
3065 Value *Res = IID == Intrinsic::vector_reduce_umin
3066 ? Builder.CreateAndReduce(Vect)
3067 : Builder.CreateOrReduce(Vect);
3068 if (Arg != Vect)
3069 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3070 II->getType());
3071 return replaceInstUsesWith(CI, Res);
3072 }
3073 }
3074 }
3075 [[fallthrough]];
3076 }
3077 case Intrinsic::vector_reduce_smin:
3078 case Intrinsic::vector_reduce_smax: {
3079 if (IID == Intrinsic::vector_reduce_smin ||
3080 IID == Intrinsic::vector_reduce_smax) {
3081 // SMin/SMax reduction over the vector with (potentially-extended)
3082 // i1 element type is actually a (potentially-extended)
3083 // logical `and`/`or` reduction over the original non-extended value:
3084 // vector_reduce_s{min,max}(<n x i1>)
3085 // -->
3086 // vector_reduce_{or,and}(<n x i1>)
3087 // and
3088 // vector_reduce_s{min,max}(sext(<n x i1>))
3089 // -->
3090 // sext(vector_reduce_{or,and}(<n x i1>))
3091 // and
3092 // vector_reduce_s{min,max}(zext(<n x i1>))
3093 // -->
3094 // zext(vector_reduce_{and,or}(<n x i1>))
3095 Value *Arg = II->getArgOperand(0);
3096 Value *Vect;
3097 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3098 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3099 if (FTy->getElementType() == Builder.getInt1Ty()) {
3100 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
3101 if (Arg != Vect)
3102 ExtOpc = cast<CastInst>(Arg)->getOpcode();
3103 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
3104 (ExtOpc == Instruction::CastOps::ZExt))
3105 ? Builder.CreateAndReduce(Vect)
3106 : Builder.CreateOrReduce(Vect);
3107 if (Arg != Vect)
3108 Res = Builder.CreateCast(ExtOpc, Res, II->getType());
3109 return replaceInstUsesWith(CI, Res);
3110 }
3111 }
3112 }
3113 [[fallthrough]];
3114 }
3115 case Intrinsic::vector_reduce_fmax:
3116 case Intrinsic::vector_reduce_fmin:
3117 case Intrinsic::vector_reduce_fadd:
3118 case Intrinsic::vector_reduce_fmul: {
3119 bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
3120 IID != Intrinsic::vector_reduce_fmul) ||
3121 II->hasAllowReassoc();
3122 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
3123 IID == Intrinsic::vector_reduce_fmul)
3124 ? 1
3125 : 0;
3126 Value *Arg = II->getArgOperand(ArgIdx);
3127 Value *V;
3128 ArrayRef<int> Mask;
3129 if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
3130 !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
3131 !cast<ShuffleVectorInst>(Arg)->isSingleSource())
3132 break;
3133 int Sz = Mask.size();
3134 SmallBitVector UsedIndices(Sz);
3135 for (int Idx : Mask) {
3136 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
3137 break;
3138 UsedIndices.set(Idx);
3139 }
3140 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
3141 // other changes.
3142 if (UsedIndices.all()) {
3143 replaceUse(II->getOperandUse(ArgIdx), V);
3144 return nullptr;
3145 }
3146 break;
3147 }
3148 case Intrinsic::is_fpclass: {
3149 if (Instruction *I = foldIntrinsicIsFPClass(*II))
3150 return I;
3151 break;
3152 }
3153 default: {
3154 // Handle target specific intrinsics
3155 std::optional<Instruction *> V = targetInstCombineIntrinsic(*II);
3156 if (V)
3157 return *V;
3158 break;
3159 }
3160 }
3161
3162 // Try to fold intrinsic into select operands. This is legal if:
3163 // * The intrinsic is speculatable.
3164 // * The select condition is not a vector, or the intrinsic does not
3165 // perform cross-lane operations.
3166 switch (IID) {
3167 case Intrinsic::ctlz:
3168 case Intrinsic::cttz:
3169 case Intrinsic::ctpop:
3170 case Intrinsic::umin:
3171 case Intrinsic::umax:
3172 case Intrinsic::smin:
3173 case Intrinsic::smax:
3174 case Intrinsic::usub_sat:
3175 case Intrinsic::uadd_sat:
3176 case Intrinsic::ssub_sat:
3177 case Intrinsic::sadd_sat:
3178 for (Value *Op : II->args())
3179 if (auto *Sel = dyn_cast<SelectInst>(Op))
3180 if (Instruction *R = FoldOpIntoSelect(*II, Sel))
3181 return R;
3182 [[fallthrough]];
3183 default:
3184 break;
3185 }
3186
3188 return Shuf;
3189
3190 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
3191 // context, so it is handled in visitCallBase and we should trigger it.
3192 return visitCallBase(*II);
3193}
3194
3195// Fence instruction simplification
3197 auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
3198 // This check is solely here to handle arbitrary target-dependent syncscopes.
3199 // TODO: Can remove if does not matter in practice.
3200 if (NFI && FI.isIdenticalTo(NFI))
3201 return eraseInstFromFunction(FI);
3202
3203 // Returns true if FI1 is identical or stronger fence than FI2.
3204 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
3205 auto FI1SyncScope = FI1->getSyncScopeID();
3206 // Consider same scope, where scope is global or single-thread.
3207 if (FI1SyncScope != FI2->getSyncScopeID() ||
3208 (FI1SyncScope != SyncScope::System &&
3209 FI1SyncScope != SyncScope::SingleThread))
3210 return false;
3211
3212 return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
3213 };
3214 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
3215 return eraseInstFromFunction(FI);
3216
3217 if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
3218 if (isIdenticalOrStrongerFence(PFI, &FI))
3219 return eraseInstFromFunction(FI);
3220 return nullptr;
3221}
3222
3223// InvokeInst simplification
3225 return visitCallBase(II);
3226}
3227
3228// CallBrInst simplification
3230 return visitCallBase(CBI);
3231}
3232
3233Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
3234 if (!CI->getCalledFunction()) return nullptr;
3235
3236 // Skip optimizing notail and musttail calls so
3237 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
3238 // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
3239 if (CI->isMustTailCall() || CI->isNoTailCall())
3240 return nullptr;
3241
3242 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
3243 replaceInstUsesWith(*From, With);
3244 };
3245 auto InstCombineErase = [this](Instruction *I) {
3247 };
3248 LibCallSimplifier Simplifier(DL, &TLI, &AC, ORE, BFI, PSI, InstCombineRAUW,
3249 InstCombineErase);
3250 if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
3251 ++NumSimplified;
3252 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
3253 }
3254
3255 return nullptr;
3256}
3257
3259 // Strip off at most one level of pointer casts, looking for an alloca. This
3260 // is good enough in practice and simpler than handling any number of casts.
3261 Value *Underlying = TrampMem->stripPointerCasts();
3262 if (Underlying != TrampMem &&
3263 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
3264 return nullptr;
3265 if (!isa<AllocaInst>(Underlying))
3266 return nullptr;
3267
3268 IntrinsicInst *InitTrampoline = nullptr;
3269 for (User *U : TrampMem->users()) {
3270 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3271 if (!II)
3272 return nullptr;
3273 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3274 if (InitTrampoline)
3275 // More than one init_trampoline writes to this value. Give up.
3276 return nullptr;
3277 InitTrampoline = II;
3278 continue;
3279 }
3280 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3281 // Allow any number of calls to adjust.trampoline.
3282 continue;
3283 return nullptr;
3284 }
3285
3286 // No call to init.trampoline found.
3287 if (!InitTrampoline)
3288 return nullptr;
3289
3290 // Check that the alloca is being used in the expected way.
3291 if (InitTrampoline->getOperand(0) != TrampMem)
3292 return nullptr;
3293
3294 return InitTrampoline;
3295}
3296
3298 Value *TrampMem) {
3299 // Visit all the previous instructions in the basic block, and try to find a
3300 // init.trampoline which has a direct path to the adjust.trampoline.
3301 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3302 E = AdjustTramp->getParent()->begin();
3303 I != E;) {
3304 Instruction *Inst = &*--I;
3305 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3306 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3307 II->getOperand(0) == TrampMem)
3308 return II;
3309 if (Inst->mayWriteToMemory())
3310 return nullptr;
3311 }
3312 return nullptr;
3313}
3314
3315// Given a call to llvm.adjust.trampoline, find and return the corresponding
3316// call to llvm.init.trampoline if the call to the trampoline can be optimized
3317// to a direct call to a function. Otherwise return NULL.
3319 Callee = Callee->stripPointerCasts();
3320 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3321 if (!AdjustTramp ||
3322 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
3323 return nullptr;
3324
3325 Value *TrampMem = AdjustTramp->getOperand(0);
3326
3328 return IT;
3329 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
3330 return IT;
3331 return nullptr;
3332}
3333
3334bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
3335 const TargetLibraryInfo *TLI) {
3336 // Note: We only handle cases which can't be driven from generic attributes
3337 // here. So, for example, nonnull and noalias (which are common properties
3338 // of some allocation functions) are expected to be handled via annotation
3339 // of the respective allocator declaration with generic attributes.
3340 bool Changed = false;
3341
3342 if (!Call.getType()->isPointerTy())
3343 return Changed;
3344
3345 std::optional<APInt> Size = getAllocSize(&Call, TLI);
3346 if (Size && *Size != 0) {
3347 // TODO: We really should just emit deref_or_null here and then
3348 // let the generic inference code combine that with nonnull.
3349 if (Call.hasRetAttr(Attribute::NonNull)) {
3350 Changed = !Call.hasRetAttr(Attribute::Dereferenceable);
3352 Call.getContext(), Size->getLimitedValue()));
3353 } else {
3354 Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull);
3356 Call.getContext(), Size->getLimitedValue()));
3357 }
3358 }
3359
3360 // Add alignment attribute if alignment is a power of two constant.
3361 Value *Alignment = getAllocAlignment(&Call, TLI);
3362 if (!Alignment)
3363 return Changed;
3364
3365 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
3366 if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
3367 uint64_t AlignmentVal = AlignOpC->getZExtValue();
3368 if (llvm::isPowerOf2_64(AlignmentVal)) {
3369 Align ExistingAlign = Call.getRetAlign().valueOrOne();
3370 Align NewAlign = Align(AlignmentVal);
3371 if (NewAlign > ExistingAlign) {
3372 Call.addRetAttr(
3373 Attribute::getWithAlignment(Call.getContext(), NewAlign));
3374 Changed = true;
3375 }
3376 }
3377 }
3378 return Changed;
3379}
3380
3381/// Improvements for call, callbr and invoke instructions.
3382Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
3383 bool Changed = annotateAnyAllocSite(Call, &TLI);
3384
3385 // Mark any parameters that are known to be non-null with the nonnull
3386 // attribute. This is helpful for inlining calls to functions with null
3387 // checks on their arguments.
3389 unsigned ArgNo = 0;
3390
3391 for (Value *V : Call.args()) {
3392 if (V->getType()->isPointerTy() &&
3393 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
3394 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
3395 ArgNos.push_back(ArgNo);
3396 ArgNo++;
3397 }
3398
3399 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
3400
3401 if (!ArgNos.empty()) {
3402 AttributeList AS = Call.getAttributes();
3403 LLVMContext &Ctx = Call.getContext();
3404 AS = AS.addParamAttribute(Ctx, ArgNos,
3405 Attribute::get(Ctx, Attribute::NonNull));
3406 Call.setAttributes(AS);
3407 Changed = true;
3408 }
3409
3410 // If the callee is a pointer to a function, attempt to move any casts to the
3411 // arguments of the call/callbr/invoke.
3412 Value *Callee = Call.getCalledOperand();
3413 Function *CalleeF = dyn_cast<Function>(Callee);
3414 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
3415 transformConstExprCastCall(Call))
3416 return nullptr;
3417
3418 if (CalleeF) {
3419 // Remove the convergent attr on calls when the callee is not convergent.
3420 if (Call.isConvergent() && !CalleeF->isConvergent() &&
3421 !CalleeF->isIntrinsic()) {
3422 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
3423 << "\n");
3424 Call.setNotConvergent();
3425 return &Call;
3426 }
3427
3428 // If the call and callee calling conventions don't match, and neither one
3429 // of the calling conventions is compatible with C calling convention
3430 // this call must be unreachable, as the call is undefined.
3431 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
3432 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
3434 !(Call.getCallingConv() == llvm::CallingConv::C &&
3436 // Only do this for calls to a function with a body. A prototype may
3437 // not actually end up matching the implementation's calling conv for a
3438 // variety of reasons (e.g. it may be written in assembly).
3439 !CalleeF->isDeclaration()) {
3440 Instruction *OldCall = &Call;
3442 // If OldCall does not return void then replaceInstUsesWith poison.
3443 // This allows ValueHandlers and custom metadata to adjust itself.
3444 if (!OldCall->getType()->isVoidTy())
3445 replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
3446 if (isa<CallInst>(OldCall))
3447 return eraseInstFromFunction(*OldCall);
3448
3449 // We cannot remove an invoke or a callbr, because it would change thexi
3450 // CFG, just change the callee to a null pointer.
3451 cast<CallBase>(OldCall)->setCalledFunction(
3452 CalleeF->getFunctionType(),
3453 Constant::getNullValue(CalleeF->getType()));
3454 return nullptr;
3455 }
3456 }
3457
3458 // Calling a null function pointer is undefined if a null address isn't
3459 // dereferenceable.
3460 if ((isa<ConstantPointerNull>(Callee) &&
3461 !NullPointerIsDefined(Call.getFunction())) ||
3462 isa<UndefValue>(Callee)) {
3463 // If Call does not return void then replaceInstUsesWith poison.
3464 // This allows ValueHandlers and custom metadata to adjust itself.
3465 if (!Call.getType()->isVoidTy())
3466 replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
3467
3468 if (Call.isTerminator()) {
3469 // Can't remove an invoke or callbr because we cannot change the CFG.
3470 return nullptr;
3471 }
3472
3473 // This instruction is not reachable, just remove it.
3475 return eraseInstFromFunction(Call);
3476 }
3477
3479 return transformCallThroughTrampoline(Call, *II);
3480
3481 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
3482 InlineAsm *IA = cast<InlineAsm>(Callee);
3483 if (!IA->canThrow()) {
3484 // Normal inline asm calls cannot throw - mark them
3485 // 'nounwind'.
3486 Call.setDoesNotThrow();
3487 Changed = true;
3488 }
3489 }
3490
3491 // Try to optimize the call if possible, we require DataLayout for most of
3492 // this. None of these calls are seen as possibly dead so go ahead and
3493 // delete the instruction now.
3494 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
3495 Instruction *I = tryOptimizeCall(CI);
3496 // If we changed something return the result, etc. Otherwise let
3497 // the fallthrough check.
3498 if (I) return eraseInstFromFunction(*I);
3499 }
3500
3501 if (!Call.use_empty() && !Call.isMustTailCall())
3502 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
3503 Type *CallTy = Call.getType();
3504 Type *RetArgTy = ReturnedArg->getType();
3505 if (RetArgTy->canLosslesslyBitCastTo(CallTy))
3506 return replaceInstUsesWith(
3507 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
3508 }
3509
3510 // Drop unnecessary kcfi operand bundles from calls that were converted
3511 // into direct calls.
3512 auto Bundle = Call.getOperandBundle(LLVMContext::OB_kcfi);
3513 if (Bundle && !Call.isIndirectCall()) {
3514 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
3515 if (CalleeF) {
3516 ConstantInt *FunctionType = nullptr;
3517 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
3518
3519 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
3520 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
3521
3522 if (FunctionType &&
3523 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
3524 dbgs() << Call.getModule()->getName()
3525 << ": warning: kcfi: " << Call.getCaller()->getName()
3526 << ": call to " << CalleeF->getName()
3527 << " using a mismatching function pointer type\n";
3528 }
3529 });
3530
3532 }
3533
3534 if (isRemovableAlloc(&Call, &TLI))
3535 return visitAllocSite(Call);
3536
3537 // Handle intrinsics which can be used in both call and invoke context.
3538 switch (Call.getIntrinsicID()) {
3539 case Intrinsic::experimental_gc_statepoint: {
3540 GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
3541 SmallPtrSet<Value *, 32> LiveGcValues;
3542 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
3543 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
3544
3545 // Remove the relocation if unused.
3546 if (GCR.use_empty()) {
3548 continue;
3549 }
3550
3551 Value *DerivedPtr = GCR.getDerivedPtr();
3552 Value *BasePtr = GCR.getBasePtr();
3553
3554 // Undef is undef, even after relocation.
3555 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
3558 continue;
3559 }
3560
3561 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
3562 // The relocation of null will be null for most any collector.
3563 // TODO: provide a hook for this in GCStrategy. There might be some
3564 // weird collector this property does not hold for.
3565 if (isa<ConstantPointerNull>(DerivedPtr)) {
3566 // Use null-pointer of gc_relocate's type to replace it.
3569 continue;
3570 }
3571
3572 // isKnownNonNull -> nonnull attribute
3573 if (!GCR.hasRetAttr(Attribute::NonNull) &&
3574 isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
3575 GCR.addRetAttr(Attribute::NonNull);
3576 // We discovered new fact, re-check users.
3578 }
3579 }
3580
3581 // If we have two copies of the same pointer in the statepoint argument
3582 // list, canonicalize to one. This may let us common gc.relocates.
3583 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
3584 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
3585 auto *OpIntTy = GCR.getOperand(2)->getType();
3586 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
3587 }
3588
3589 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3590 // Canonicalize on the type from the uses to the defs
3591
3592 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3593 LiveGcValues.insert(BasePtr);
3594 LiveGcValues.insert(DerivedPtr);
3595 }
3596 std::optional<OperandBundleUse> Bundle =
3598 unsigned NumOfGCLives = LiveGcValues.size();
3599 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
3600 break;
3601 // We can reduce the size of gc live bundle.
3603 std::vector<Value *> NewLiveGc;
3604 for (Value *V : Bundle->Inputs) {
3605 if (Val2Idx.count(V))
3606 continue;
3607 if (LiveGcValues.count(V)) {
3608 Val2Idx[V] = NewLiveGc.size();
3609 NewLiveGc.push_back(V);
3610 } else
3611 Val2Idx[V] = NumOfGCLives;
3612 }
3613 // Update all gc.relocates
3614 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
3615 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
3616 Value *BasePtr = GCR.getBasePtr();
3617 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
3618 "Missed live gc for base pointer");
3619 auto *OpIntTy1 = GCR.getOperand(1)->getType();
3620 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
3621 Value *DerivedPtr = GCR.getDerivedPtr();
3622 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
3623 "Missed live gc for derived pointer");
3624 auto *OpIntTy2 = GCR.getOperand(2)->getType();
3625 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
3626 }
3627 // Create new statepoint instruction.
3628 OperandBundleDef NewBundle("gc-live", NewLiveGc);
3629 return CallBase::Create(&Call, NewBundle);
3630 }
3631 default: { break; }
3632 }
3633
3634 return Changed ? &Call : nullptr;
3635}
3636
3637/// If the callee is a constexpr cast of a function, attempt to move the cast to
3638/// the arguments of the call/invoke.
3639/// CallBrInst is not supported.
3640bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
3641 auto *Callee =
3642 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3643 if (!Callee)
3644 return false;
3645
3646 assert(!isa<CallBrInst>(Call) &&
3647 "CallBr's don't have a single point after a def to insert at");
3648
3649 // If this is a call to a thunk function, don't remove the cast. Thunks are
3650 // used to transparently forward all incoming parameters and outgoing return
3651 // values, so it's important to leave the cast in place.
3652 if (Callee->hasFnAttribute("thunk"))
3653 return false;
3654
3655 // If this is a musttail call, the callee's prototype must match the caller's
3656 // prototype with the exception of pointee types. The code below doesn't
3657 // implement that, so we can't do this transform.
3658 // TODO: Do the transform if it only requires adding pointer casts.
3659 if (Call.isMustTailCall())
3660 return false;
3661
3663 const AttributeList &CallerPAL = Call.getAttributes();
3664
3665 // Okay, this is a cast from a function to a different type. Unless doing so
3666 // would cause a type conversion of one of our arguments, change this call to
3667 // be a direct call with arguments casted to the appropriate types.
3669 Type *OldRetTy = Caller->getType();
3670 Type *NewRetTy = FT->getReturnType();
3671
3672 // Check to see if we are changing the return type...
3673 if (OldRetTy != NewRetTy) {
3674
3675 if (NewRetTy->isStructTy())
3676 return false; // TODO: Handle multiple return values.
3677
3678 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3679 if (Callee->isDeclaration())
3680 return false; // Cannot transform this return value.
3681
3682 if (!Caller->use_empty() &&
3683 // void -> non-void is handled specially
3684 !NewRetTy->isVoidTy())
3685 return false; // Cannot transform this return value.
3686 }
3687
3688 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3689 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3690 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3691 return false; // Attribute not compatible with transformed value.
3692 }
3693
3694 // If the callbase is an invoke instruction, and the return value is
3695 // used by a PHI node in a successor, we cannot change the return type of
3696 // the call because there is no place to put the cast instruction (without
3697 // breaking the critical edge). Bail out in this case.
3698 if (!Caller->use_empty()) {
3699 BasicBlock *PhisNotSupportedBlock = nullptr;
3700 if (auto *II = dyn_cast<InvokeInst>(Caller))
3701 PhisNotSupportedBlock = II->getNormalDest();
3702 if (PhisNotSupportedBlock)
3703 for (User *U : Caller->users())
3704 if (PHINode *PN = dyn_cast<PHINode>(U))
3705 if (PN->getParent() == PhisNotSupportedBlock)
3706 return false;
3707 }
3708 }
3709
3710 unsigned NumActualArgs = Call.arg_size();
3711 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3712
3713 // Prevent us turning:
3714 // declare void @takes_i32_inalloca(i32* inalloca)
3715 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3716 //
3717 // into:
3718 // call void @takes_i32_inalloca(i32* null)
3719 //
3720 // Similarly, avoid folding away bitcasts of byval calls.
3721 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3722 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))
3723 return false;
3724
3725 auto AI = Call.arg_begin();
3726 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3727 Type *ParamTy = FT->getParamType(i);
3728 Type *ActTy = (*AI)->getType();
3729
3730 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3731 return false; // Cannot transform this parameter value.
3732
3733 // Check if there are any incompatible attributes we cannot drop safely.
3734 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3737 return false; // Attribute not compatible with transformed value.
3738
3739 if (Call.isInAllocaArgument(i) ||
3740 CallerPAL.hasParamAttr(i, Attribute::Preallocated))
3741 return false; // Cannot transform to and from inalloca/preallocated.
3742
3743 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3744 return false;
3745
3746 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=
3747 Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))
3748 return false; // Cannot transform to or from byval.
3749 }
3750
3751 if (Callee->isDeclaration()) {
3752 // Do not delete arguments unless we have a function body.
3753 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3754 return false;
3755
3756 // If the callee is just a declaration, don't change the varargsness of the
3757 // call. We don't want to introduce a varargs call where one doesn't
3758 // already exist.
3759 if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
3760 return false;
3761
3762 // If both the callee and the cast type are varargs, we still have to make
3763 // sure the number of fixed parameters are the same or we have the same
3764 // ABI issues as if we introduce a varargs call.
3765 if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
3766 FT->getNumParams() != Call.getFunctionType()->getNumParams())
3767 return false;
3768 }
3769
3770 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3771 !CallerPAL.isEmpty()) {
3772 // In this case we have more arguments than the new function type, but we
3773 // won't be dropping them. Check that these extra arguments have attributes
3774 // that are compatible with being a vararg call argument.
3775 unsigned SRetIdx;
3776 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3777 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3778 return false;
3779 }
3780
3781 // Okay, we decided that this is a safe thing to do: go ahead and start
3782 // inserting cast instructions as necessary.
3785 Args.reserve(NumActualArgs);
3786 ArgAttrs.reserve(NumActualArgs);
3787
3788 // Get any return attributes.
3789 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3790
3791 // If the return value is not being used, the type may not be compatible
3792 // with the existing attributes. Wipe out any problematic attributes.
3793 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
3794
3795 LLVMContext &Ctx = Call.getContext();
3796 AI = Call.arg_begin();
3797 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3798 Type *ParamTy = FT->getParamType(i);
3799
3800 Value *NewArg = *AI;
3801 if ((*AI)->getType() != ParamTy)
3802 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
3803 Args.push_back(NewArg);
3804
3805 // Add any parameter attributes except the ones incompatible with the new
3806 // type. Note that we made sure all incompatible ones are safe to drop.
3809 ArgAttrs.push_back(
3810 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));
3811 }
3812
3813 // If the function takes more arguments than the call was taking, add them
3814 // now.
3815 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
3816 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3817 ArgAttrs.push_back(AttributeSet());
3818 }
3819
3820 // If we are removing arguments to the function, emit an obnoxious warning.
3821 if (FT->getNumParams() < NumActualArgs) {
3822 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3823 if (FT->isVarArg()) {
3824 // Add all of the arguments in their promoted form to the arg list.
3825 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3826 Type *PTy = getPromotedType((*AI)->getType());
3827 Value *NewArg = *AI;
3828 if (PTy != (*AI)->getType()) {
3829 // Must promote to pass through va_arg area!
3830 Instruction::CastOps opcode =
3831 CastInst::getCastOpcode(*AI, false, PTy, false);
3832 NewArg = Builder.CreateCast(opcode, *AI, PTy);
3833 }
3834 Args.push_back(NewArg);
3835
3836 // Add any parameter attributes.
3837 ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
3838 }
3839 }
3840 }
3841
3842 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
3843
3844 if (NewRetTy->isVoidTy())
3845 Caller->setName(""); // Void type should not have a name.
3846
3847 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
3848 "missing argument attributes");
3849 AttributeList NewCallerPAL = AttributeList::get(
3850 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
3851
3853 Call.getOperandBundlesAsDefs(OpBundles);
3854
3855 CallBase *NewCall;
3856 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3857 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
3858 II->getUnwindDest(), Args, OpBundles);
3859 } else {
3860 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
3861 cast<CallInst>(NewCall)->setTailCallKind(
3862 cast<CallInst>(Caller)->getTailCallKind());
3863 }
3864 NewCall->takeName(Caller);
3865 NewCall->setCallingConv(Call.getCallingConv());
3866 NewCall->setAttributes(NewCallerPAL);
3867
3868 // Preserve prof metadata if any.
3869 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
3870
3871 // Insert a cast of the return type as necessary.
3872 Instruction *NC = NewCall;
3873 Value *NV = NC;
3874 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3875 if (!NV->getType()->isVoidTy()) {
3877 NC->setDebugLoc(Caller->getDebugLoc());
3878
3879 Instruction *InsertPt = NewCall->getInsertionPointAfterDef();
3880 assert(InsertPt && "No place to insert cast");
3881 InsertNewInstBefore(NC, *InsertPt);
3883 } else {
3884 NV = PoisonValue::get(Caller->getType());
3885 }
3886 }
3887
3888 if (!Caller->use_empty())
3889 replaceInstUsesWith(*Caller, NV);
3890 else if (Caller->hasValueHandle()) {
3891 if (OldRetTy == NV->getType())
3893 else
3894 // We cannot call ValueIsRAUWd with a different type, and the
3895 // actual tracked value will disappear.
3897 }
3898
3899 eraseInstFromFunction(*Caller);
3900 return true;
3901}
3902
3903/// Turn a call to a function created by init_trampoline / adjust_trampoline
3904/// intrinsic pair into a direct call to the underlying function.
3906InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
3907 IntrinsicInst &Tramp) {
3908 Value *Callee = Call.getCalledOperand();
3909 Type *CalleeTy = Callee->getType();
3910 FunctionType *FTy = Call.getFunctionType();
3911 AttributeList Attrs = Call.getAttributes();
3912
3913 // If the call already has the 'nest' attribute somewhere then give up -
3914 // otherwise 'nest' would occur twice after splicing in the chain.
3915 if (Attrs.hasAttrSomewhere(Attribute::Nest))
3916 return nullptr;
3917
3918 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
3919 FunctionType *NestFTy = NestF->getFunctionType();
3920
3921 AttributeList NestAttrs = NestF->getAttributes();
3922 if (!NestAttrs.isEmpty()) {
3923 unsigned NestArgNo = 0;
3924 Type *NestTy = nullptr;
3925 AttributeSet NestAttr;
3926
3927 // Look for a parameter marked with the 'nest' attribute.
3928 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3929 E = NestFTy->param_end();
3930 I != E; ++NestArgNo, ++I) {
3931 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
3932 if (AS.hasAttribute(Attribute::Nest)) {
3933 // Record the parameter type and any other attributes.
3934 NestTy = *I;
3935 NestAttr = AS;
3936 break;
3937 }
3938 }
3939
3940 if (NestTy) {
3941 std::vector<Value*> NewArgs;
3942 std::vector<AttributeSet> NewArgAttrs;
3943 NewArgs.reserve(Call.arg_size() + 1);
3944 NewArgAttrs.reserve(Call.arg_size());
3945
3946 // Insert the nest argument into the call argument list, which may
3947 // mean appending it. Likewise for attributes.
3948
3949 {
3950 unsigned ArgNo = 0;
3951 auto I = Call.arg_begin(), E = Call.arg_end();
3952 do {
3953 if (ArgNo == NestArgNo) {
3954 // Add the chain argument and attributes.
3955 Value *NestVal = Tramp.getArgOperand(2);
3956 if (NestVal->getType() != NestTy)
3957 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
3958 NewArgs.push_back(NestVal);
3959 NewArgAttrs.push_back(NestAttr);
3960 }
3961
3962 if (I == E)
3963 break;
3964
3965 // Add the original argument and attributes.
3966 NewArgs.push_back(*I);
3967 NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
3968
3969 ++ArgNo;
3970 ++I;
3971 } while (true);
3972 }
3973
3974 // The trampoline may have been bitcast to a bogus type (FTy).
3975 // Handle this by synthesizing a new function type, equal to FTy
3976 // with the chain parameter inserted.
3977
3978 std::vector<Type*> NewTypes;
3979 NewTypes.reserve(FTy->getNumParams()+1);
3980
3981 // Insert the chain's type into the list of parameter types, which may
3982 // mean appending it.
3983 {
3984 unsigned ArgNo = 0;
3985 FunctionType::param_iterator I = FTy->param_begin(),
3986 E = FTy->param_end();
3987
3988 do {
3989 if (ArgNo == NestArgNo)
3990 // Add the chain's type.
3991 NewTypes.push_back(NestTy);
3992
3993 if (I == E)
3994 break;
3995
3996 // Add the original type.
3997 NewTypes.push_back(*I);
3998
3999 ++ArgNo;
4000 ++I;
4001 } while (true);
4002 }
4003
4004 // Replace the trampoline call with a direct call. Let the generic
4005 // code sort out any function type mismatches.
4006 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
4007 FTy->isVarArg());
4008 Constant *NewCallee =
4009 NestF->getType() == PointerType::getUnqual(NewFTy) ?
4010 NestF : ConstantExpr::getBitCast(NestF,
4011 PointerType::getUnqual(NewFTy));
4012 AttributeList NewPAL =
4013 AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
4014 Attrs.getRetAttrs(), NewArgAttrs);
4015
4017 Call.getOperandBundlesAsDefs(OpBundles);
4018
4019 Instruction *NewCaller;
4020 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4021 NewCaller = InvokeInst::Create(NewFTy, NewCallee,
4022 II->getNormalDest(), II->getUnwindDest(),
4023 NewArgs, OpBundles);
4024 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4025 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4026 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4027 NewCaller =
4028 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4029 CBI->getIndirectDests(), NewArgs, OpBundles);
4030 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4031 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4032 } else {
4033 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
4034 cast<CallInst>(NewCaller)->setTailCallKind(
4035 cast<CallInst>(Call).getTailCallKind());
4036 cast<CallInst>(NewCaller)->setCallingConv(
4037 cast<CallInst>(Call).getCallingConv());
4038 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4039 }
4040 NewCaller->setDebugLoc(Call.getDebugLoc());
4041
4042 return NewCaller;
4043 }
4044 }
4045
4046 // Replace the trampoline call with a direct call. Since there is no 'nest'
4047 // parameter, there is no need to adjust the argument list. Let the generic
4048 // code sort out any function type mismatches.
4049 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4050 Call.setCalledFunction(FTy, NewCallee);
4051 return &Call;
4052}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
unsigned Intr
amdgpu Simplify well known AMD library false FunctionCallee Callee
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
assume Assume Builder
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
SmallVector< MachineOperand, 4 > Cond
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static SDValue foldBitOrderCrossLogicOp(SDNode *N, SelectionDAG &DAG)
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
static Type * getPromotedType(Type *Ty)
Return the specified type promoted as it would be to pass though a va_arg area.
static Instruction * createOverflowTuple(IntrinsicInst *II, Value *Result, Constant *Overflow)
Creates a result tuple for an overflow intrinsic II with a given Result and a constant Overflow value...
static IntrinsicInst * findInitTrampolineFromAlloca(Value *TrampMem)
static bool removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC, std::function< bool(const IntrinsicInst &)> IsStart)
static bool inputDenormalIsDAZ(const Function &F, const Type *Ty)
static Instruction * reassociateMinMaxWithConstantInOperand(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If this min/max has a matching min/max operand with a constant, try to push the constant operand into...
static Instruction * moveAddAfterMinMax(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0.
static Instruction * simplifyInvariantGroupIntrinsic(IntrinsicInst &II, InstCombinerImpl &IC)
This function transforms launder.invariant.group and strip.invariant.group like: launder(launder(x)) ...
static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, unsigned NumOperands)
static cl::opt< unsigned > GuardWideningWindow("instcombine-guard-widening-window", cl::init(3), cl::desc("How wide an instruction window to bypass looking for " "another guard"))
static bool hasUndefSource(AnyMemTransferInst *MI)
Recognize a memcpy/memmove from a trivially otherwise unused alloca.
static Instruction * foldShuffledIntrinsicOperands(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If all arguments of the intrinsic are unary shuffles with the same mask, try to shuffle after the int...
static Instruction * factorizeMinMaxTree(IntrinsicInst *II)
Reduce a sequence of min/max intrinsics with a common operand.
static Value * simplifyNeonTbl1(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Convert a table lookup to shufflevector if the mask is constant.
static Instruction * foldClampRangeOfTwo(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If we have a clamp pattern like max (min X, 42), 41 – where the output can only be one of two possibl...
static IntrinsicInst * findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, Value *TrampMem)
static Value * reassociateMinMaxWithConstants(IntrinsicInst *II, IRBuilderBase &Builder)
If this min/max has a constant operand and an operand that is a matching min/max with a constant oper...
static Instruction * foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC)
static Instruction * foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC)
static IntrinsicInst * findInitTrampoline(Value *Callee)
static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask, const Function &F, Type *Ty)
static std::optional< bool > getKnownSign(Value *Op, Instruction *CxtI, const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT)
static CallInst * canonicalizeConstantArg0ToArg1(CallInst &Call)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Metadata * LowAndHigh[]
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
@ Struct
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static bool inputDenormalIsIEEE(const Function &F, const Type *Ty)
Return true if it's possible to assume IEEE treatment of input denormals in F for Val.
Value * RHS
Value * LHS
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
Class for arbitrary precision integers.
Definition: APInt.h:75
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:214
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:209
APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1946
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:366
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1443
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1093
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1926
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1933
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:199
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2027
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:317
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:289
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1939
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition: APSInt.h:311
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition: APSInt.h:303
This class represents any memset intrinsic.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void updateAffectedValues(AssumeInst *CI)
Update the cache of values being affected by this assumption (i.e.
bool overlaps(const AttributeMask &AM) const
Return true if the builder has any attribute that's in the specified builder.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
bool isEmpty() const
Return true if there are no attributes.
Definition: Attributes.h:954
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:770
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:576
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition: Attributes.cpp:778
AttributeSet removeAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attributes from this set.
Definition: Attributes.cpp:763
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:711
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:91
static Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:177
static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:183
static Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:167
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:323
InstListType::reverse_iterator reverse_iterator
Definition: BasicBlock.h:89
reverse_iterator rend()
Definition: BasicBlock.h:330
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
Value * getRHS() const
bool isSigned() const
Whether the intrinsic is signed or unsigned.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getLHS() const
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:271
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static BinaryOperator * CreateNSW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition: InstrTypes.h:282
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Instruction *CopyO, const Twine &Name="", Instruction *InsertBefore=nullptr)
Definition: InstrTypes.h:248
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:266
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition: InstrTypes.h:301
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1190
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1475
bundle_op_iterator bundle_op_info_begin()
Return the start of the list of BundleOpInfo instances associated with this OperandBundleUser.
Definition: InstrTypes.h:2216
void setDoesNotThrow()
Definition: InstrTypes.h:1928
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Definition: InstrTypes.h:2024
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Definition: InstrTypes.h:2055
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1412
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
Definition: InstrTypes.h:1883
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
Definition: InstrTypes.h:1616
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
Definition: InstrTypes.h:1968
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1471
static CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, Instruction *InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
static CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, Instruction *InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
Value * getCalledOperand() const
Definition: InstrTypes.h:1405
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1494
bool doesNotThrow() const
Determine if the call cannot unwind.
Definition: InstrTypes.h:1927
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Definition: InstrTypes.h:1532
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1357
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1362
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1270
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1348
unsigned arg_size() const
Definition: InstrTypes.h:1355
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Definition: InstrTypes.h:1973
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1451
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
void setTailCallKind(TailCallKind TCK)
bool isMustTailCall() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1058
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:711
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:714
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:740
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:717
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:715
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:716
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:734
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:738
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:719
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:736
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:718
@ ICMP_EQ
equal
Definition: InstrTypes.h:732
@ ICMP_NE
not equal
Definition: InstrTypes.h:733
Predicate getUnorderedPredicate() const
Definition: InstrTypes.h:847
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1579
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:419
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2600
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2103
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2460
static Constant * getIntegerCast(Constant *C, Type *Ty, bool IsSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:2051
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2089
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2607
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2213
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2075
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2581
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:927
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1027