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