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