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