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