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