LLVM 24.0.0git
SimplifyLibCalls.cpp
Go to the documentation of this file.
1//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 library calls simplifier. It does not implement
10// any pass, but can be used by other passes to do simplifications.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APSInt.h"
20#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
44
45#include <cmath>
46
47using namespace llvm;
48using namespace PatternMatch;
49
50#define DEBUG_TYPE "simplify-lib-calls"
51
52static cl::opt<bool>
53 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
54 cl::init(false),
55 cl::desc("Enable unsafe double to float "
56 "shrinking for math lib calls"));
57
58// Enable conversion of operator new calls with a MemProf hot or cold hint
59// to an operator new call that takes a hot/cold hint. Off by default since
60// not all allocators currently support this extension.
61static cl::opt<bool>
62 OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false),
63 cl::desc("Enable hot/cold operator new library calls"));
70 "optimize-existing-hot-cold-new", cl::Hidden,
72 "Enable optimization of existing hot/cold operator new library calls"),
76 "Do not optimize existing hot/cold operator new library calls"),
78 "Only optimize existing hot/cold operator new library calls "
79 "if determined to be cold"),
82 "Always optimize existing hot/cold operator new library calls"),
85 "Always optimize existing hot/cold operator new library calls")),
88 "optimize-nobuiltin-hot-cold-new-new", cl::Hidden, cl::init(false),
89 cl::desc("Enable transformation of nobuiltin operator new library calls"));
91 "min-existing-hot-cold-new-hint", cl::Hidden, cl::init(false),
92 cl::desc("Take the minimum of compiler hint and existing hint when "
93 "optimizing existing hot/cold operator new library calls"));
94
95namespace llvm {
97} // namespace llvm
98
99namespace {
100
101// Specialized parser to ensure the hint is an 8 bit value (we can't specify
102// uint8_t to opt<> as that is interpreted to mean that we are passing a char
103// option with a specific set of values.
104struct HotColdHintParser : public cl::parser<unsigned> {
105 HotColdHintParser(cl::Option &O) : cl::parser<unsigned>(O) {}
106
107 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
108 if (Arg.getAsInteger(0, Value))
109 return O.error("'" + Arg + "' value invalid for uint argument!");
110
111 if (Value > 255)
112 return O.error("'" + Arg + "' value must be in the range [0, 255]!");
113
114 return false;
115 }
116};
117
118} // end anonymous namespace
119
120// Hot/cold operator new takes an 8 bit hotness hint, where 0 is the coldest
121// and 255 is the hottest. Default to 1 value away from the coldest and hottest
122// hints, so that the compiler hinted allocations are slightly less strong than
123// manually inserted hints at the two extremes.
125 "cold-new-hint-value", cl::Hidden, cl::init(1),
126 cl::desc("Value to pass to hot/cold operator new for cold allocation"));
128 NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128),
129 cl::desc("Value to pass to hot/cold operator new for "
130 "notcold (warm) allocation"));
132 "hot-new-hint-value", cl::Hidden, cl::init(254),
133 cl::desc("Value to pass to hot/cold operator new for hot allocation"));
135 "ambiguous-new-hint-value", cl::Hidden, cl::init(222),
136 cl::desc(
137 "Value to pass to hot/cold operator new for ambiguous allocation"));
138
139//===----------------------------------------------------------------------===//
140// Helper Functions
141//===----------------------------------------------------------------------===//
142
143static bool ignoreCallingConv(LibFunc Func) {
144 return Func == LibFunc_abs || Func == LibFunc_labs ||
145 Func == LibFunc_llabs || Func == LibFunc_strlen;
146}
147
148/// Return true if it is only used in equality comparisons with With.
150 for (User *U : V->users()) {
151 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
152 if (IC->isEquality() && IC->getOperand(1) == With)
153 continue;
154 // Unknown instruction.
155 return false;
156 }
157 return true;
158}
159
161 return any_of(CI->operands(), [](const Use &OI) {
162 return OI->getType()->isFloatingPointTy();
163 });
164}
165
166static bool callHasFP128Argument(const CallInst *CI) {
167 return any_of(CI->operands(), [](const Use &OI) {
168 return OI->getType()->isFP128Ty();
169 });
170}
171
172// Convert the entire string Str representing an integer in Base, up to
173// the terminating nul if present, to a constant according to the rules
174// of strtoul[l] or, when AsSigned is set, of strtol[l]. On success
175// return the result, otherwise null.
176// The function assumes the string is encoded in ASCII and carefully
177// avoids converting sequences (including "") that the corresponding
178// library call might fail and set errno for.
179static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
180 uint64_t Base, bool AsSigned, IRBuilderBase &B) {
181 if (Base < 2 || Base > 36)
182 if (Base != 0)
183 // Fail for an invalid base (required by POSIX).
184 return nullptr;
185
186 // Current offset into the original string to reflect in EndPtr.
187 size_t Offset = 0;
188 // Strip leading whitespace.
189 for ( ; Offset != Str.size(); ++Offset)
190 if (!isSpace((unsigned char)Str[Offset])) {
191 Str = Str.substr(Offset);
192 break;
193 }
194
195 if (Str.empty())
196 // Fail for empty subject sequences (POSIX allows but doesn't require
197 // strtol[l]/strtoul[l] to fail with EINVAL).
198 return nullptr;
199
200 // Strip but remember the sign.
201 bool Negate = Str[0] == '-';
202 if (Str[0] == '-' || Str[0] == '+') {
203 Str = Str.drop_front();
204 if (Str.empty())
205 // Fail for a sign with nothing after it.
206 return nullptr;
207 ++Offset;
208 }
209
210 // Set Max to the absolute value of the minimum (for signed), or
211 // to the maximum (for unsigned) value representable in the type.
212 Type *RetTy = CI->getType();
213 unsigned NBits = RetTy->getPrimitiveSizeInBits();
214 uint64_t Max = AsSigned && Negate ? 1 : 0;
215 Max += AsSigned ? maxIntN(NBits) : maxUIntN(NBits);
216
217 // Autodetect Base if it's zero and consume the "0x" prefix.
218 if (Str.size() > 1) {
219 if (Str[0] == '0') {
220 if (toUpper((unsigned char)Str[1]) == 'X') {
221 if (Str.size() == 2 || (Base && Base != 16))
222 // Fail if Base doesn't allow the "0x" prefix or for the prefix
223 // alone that implementations like BSD set errno to EINVAL for.
224 return nullptr;
225
226 Str = Str.drop_front(2);
227 Offset += 2;
228 Base = 16;
229 }
230 else if (Base == 0)
231 Base = 8;
232 } else if (Base == 0)
233 Base = 10;
234 }
235 else if (Base == 0)
236 Base = 10;
237
238 // Convert the rest of the subject sequence, not including the sign,
239 // to its uint64_t representation (this assumes the source character
240 // set is ASCII).
241 uint64_t Result = 0;
242 for (unsigned i = 0; i != Str.size(); ++i) {
243 unsigned char DigVal = Str[i];
244 if (isDigit(DigVal))
245 DigVal = DigVal - '0';
246 else {
247 DigVal = toUpper(DigVal);
248 if (isAlpha(DigVal))
249 DigVal = DigVal - 'A' + 10;
250 else
251 return nullptr;
252 }
253
254 if (DigVal >= Base)
255 // Fail if the digit is not valid in the Base.
256 return nullptr;
257
258 // Add the digit and fail if the result is not representable in
259 // the (unsigned form of the) destination type.
260 bool VFlow;
261 Result = SaturatingMultiplyAdd(Result, Base, (uint64_t)DigVal, &VFlow);
262 if (VFlow || Result > Max)
263 return nullptr;
264 }
265
266 if (EndPtr) {
267 // Store the pointer to the end.
268 Value *Off = B.getInt64(Offset + Str.size());
269 Value *StrBeg = CI->getArgOperand(0);
270 Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr");
271 B.CreateStore(StrEnd, EndPtr);
272 }
273
274 if (Negate) {
275 // Unsigned negation doesn't overflow.
276 Result = -Result;
277 // For unsigned numbers, discard sign bits.
278 if (!AsSigned)
279 Result &= maxUIntN(NBits);
280 }
281
282 return ConstantInt::get(RetTy, Result, AsSigned);
283}
284
286 for (User *U : V->users()) {
287 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
288 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
289 if (C->isNullValue())
290 continue;
291 // Unknown instruction.
292 return false;
293 }
294 return true;
295}
296
297static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
298 const SimplifyQuery &SQ) {
300 return false;
301
302 if (!isDereferenceablePointer(Str, APInt(64, Len), SQ))
303 return false;
304
305 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
306 return false;
307
308 return true;
309}
310
312 ArrayRef<unsigned> ArgNos,
313 uint64_t DereferenceableBytes) {
314 const Function *F = CI->getCaller();
315 if (!F)
316 return;
317 for (unsigned ArgNo : ArgNos) {
318 uint64_t DerefBytes = DereferenceableBytes;
319 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
320 if (!llvm::NullPointerIsDefined(F, AS) ||
321 CI->paramHasAttr(ArgNo, Attribute::NonNull))
322 DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo),
323 DereferenceableBytes);
324
325 if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) {
326 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
327 if (!llvm::NullPointerIsDefined(F, AS) ||
328 CI->paramHasAttr(ArgNo, Attribute::NonNull))
329 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
331 CI->getContext(), DerefBytes));
332 }
333 }
334}
335
337 ArrayRef<unsigned> ArgNos,
338 uint64_t CharSize = 1) {
339 Function *F = CI->getCaller();
340 if (!F)
341 return;
342
343 for (unsigned ArgNo : ArgNos) {
344 if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef))
345 CI->addParamAttr(ArgNo, Attribute::NoUndef);
346
347 if (!CI->paramHasAttr(ArgNo, Attribute::NonNull)) {
348 unsigned AS =
351 continue;
352 CI->addParamAttr(ArgNo, Attribute::NonNull);
353 }
354
355 annotateDereferenceableBytes(CI, ArgNo, CharSize);
356 }
357}
358
360 Value *Size, const DataLayout &DL) {
363 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
364 } else if (isKnownNonZero(Size, DL)) {
366 uint64_t X, Y;
367 uint64_t DerefMin = 1;
369 DerefMin = std::min(X, Y);
370 annotateDereferenceableBytes(CI, ArgNos, DerefMin);
371 }
372 }
373}
374
375// Copy CallInst "flags" like musttail, notail, and tail. Return New param for
376// easier chaining. Calls to emit* and B.createCall should probably be wrapped
377// in this function when New is created to replace Old. Callers should take
378// care to check Old.isMustTailCall() if they aren't replacing Old directly
379// with New.
380static Value *copyFlags(const CallInst &Old, Value *New) {
381 assert(!Old.isMustTailCall() && "do not copy musttail call flags");
382 assert(!Old.isNoTailCall() && "do not copy notail call flags");
383 if (auto *NewCI = dyn_cast_or_null<CallInst>(New))
384 NewCI->setTailCallKind(Old.getTailCallKind());
385 return New;
386}
387
388static Value *mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old) {
389 NewCI->setAttributes(AttributeList::get(
390 NewCI->getContext(), {NewCI->getAttributes(), Old.getAttributes()}));
391 if (NewCI->getType()->isVoidTy()) {
392 for (unsigned I = 0; I < NewCI->arg_size(); ++I)
393 NewCI->removeParamAttr(I, Attribute::Returned);
394 }
395 NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(
396 NewCI->getType(), NewCI->getRetAttributes()));
397 for (unsigned I = 0; I < NewCI->arg_size(); ++I)
398 NewCI->removeParamAttrs(
399 I, AttributeFuncs::typeIncompatible(NewCI->getArgOperand(I)->getType(),
400 NewCI->getParamAttributes(I)));
401
402 return copyFlags(Old, NewCI);
403}
404
405// Helper to avoid truncating the length if size_t is 32-bits.
407 return Len >= Str.size() ? Str : Str.substr(0, Len);
408}
409
410//===----------------------------------------------------------------------===//
411// String and Memory Library Call Optimizations
412//===----------------------------------------------------------------------===//
413
414Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) {
415 // Extract some information from the instruction
416 Value *Dst = CI->getArgOperand(0);
417 Value *Src = CI->getArgOperand(1);
419
420 // See if we can get the length of the input string.
422 if (Len)
424 else
425 return nullptr;
426 --Len; // Unbias length.
427
428 // Handle the simple, do-nothing case: strcat(x, "") -> x
429 if (Len == 0)
430 return Dst;
431
432 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B));
433}
434
435Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
436 IRBuilderBase &B) {
437 // We need to find the end of the destination string. That's where the
438 // memory is to be moved to. We just generate a call to strlen.
439 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
440 if (!DstLen)
441 return nullptr;
442
443 // Now that we have the destination's length, we must index into the
444 // destination's pointer to get the actual memcpy destination (end of
445 // the string .. we're concatenating).
446 Value *CpyDst = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
447
448 // We have enough information to now generate the memcpy call to do the
449 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
450 B.CreateMemCpy(CpyDst, Align(1), Src, Align(1),
451 TLI->getAsSizeT(Len + 1, *B.getModule()));
452 return Dst;
453}
454
455Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) {
456 // Extract some information from the instruction.
457 Value *Dst = CI->getArgOperand(0);
458 Value *Src = CI->getArgOperand(1);
459 Value *Size = CI->getArgOperand(2);
462 if (isKnownNonZero(Size, DL))
464
465 // We don't do anything if length is not constant.
466 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
467 if (LengthArg) {
468 Len = LengthArg->getZExtValue();
469 // strncat(x, c, 0) -> x
470 if (!Len)
471 return Dst;
472 } else {
473 return nullptr;
474 }
475
476 // See if we can get the length of the input string.
477 uint64_t SrcLen = GetStringLength(Src);
478 if (SrcLen) {
479 annotateDereferenceableBytes(CI, 1, SrcLen);
480 --SrcLen; // Unbias length.
481 } else {
482 return nullptr;
483 }
484
485 // strncat(x, "", c) -> x
486 if (SrcLen == 0)
487 return Dst;
488
489 // We don't optimize this case.
490 if (Len < SrcLen)
491 return nullptr;
492
493 // strncat(x, s, c) -> strcat(x, s)
494 // s is constant so the strcat can be optimized further.
495 return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B));
496}
497
498// Helper to transform memchr(S, C, N) == S to N && *S == C and, when
499// NBytes is null, strchr(S, C) to *S == C. A precondition of the function
500// is that either S is dereferenceable or the value of N is nonzero.
502 IRBuilderBase &B, const DataLayout &DL)
503{
504 Value *Src = CI->getArgOperand(0);
505 Value *CharVal = CI->getArgOperand(1);
506
507 // Fold memchr(A, C, N) == A to N && *A == C.
508 Type *CharTy = B.getInt8Ty();
509 Value *Char0 = B.CreateLoad(CharTy, Src);
510 CharVal = B.CreateTrunc(CharVal, CharTy);
511 Value *Cmp = B.CreateICmpEQ(Char0, CharVal, "char0cmp");
512
513 if (NBytes) {
514 Value *Zero = ConstantInt::get(NBytes->getType(), 0);
515 Value *And = B.CreateICmpNE(NBytes, Zero);
516 Cmp = B.CreateLogicalAnd(And, Cmp);
517 // The and above is based on the byte count and the query, neither of which
518 // we know without value profiling, so mark the profile as unknown.
519 if (auto *SI = dyn_cast<SelectInst>(Cmp))
521 }
522
523 Value *NullPtr = Constant::getNullValue(CI->getType());
524 return B.CreateSelect(Cmp, Src, NullPtr);
525}
526
527Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) {
528 Value *SrcStr = CI->getArgOperand(0);
529 Value *CharVal = CI->getArgOperand(1);
531
532 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
533 return memChrToCharCompare(CI, nullptr, B, DL);
534
535 // If the second operand is non-constant, see if we can compute the length
536 // of the input string and turn this into memchr.
537 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
538 if (!CharC) {
539 uint64_t Len = GetStringLength(SrcStr);
540 if (Len)
542 else
543 return nullptr;
544
546 FunctionType *FT = Callee->getFunctionType();
547 unsigned IntBits = TLI->getIntSize();
548 if (!FT->getParamType(1)->isIntegerTy(IntBits)) // memchr needs 'int'.
549 return nullptr;
550
551 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
552 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
553 return copyFlags(*CI,
554 emitMemChr(SrcStr, CharVal, // include nul.
555 ConstantInt::get(SizeTTy, Len), B,
556 DL, TLI));
557 }
558
559 if (CharC->isZero()) {
560 Value *NullPtr = Constant::getNullValue(CI->getType());
561 if (isOnlyUsedInEqualityComparison(CI, NullPtr))
562 // Pre-empt the transformation to strlen below and fold
563 // strchr(A, '\0') == null to false.
564 return B.CreateIntToPtr(B.getTrue(), CI->getType());
565 }
566
567 // Otherwise, the character is a constant, see if the first argument is
568 // a string literal. If so, we can constant fold.
569 StringRef Str;
570 if (!getConstantStringInfo(SrcStr, Str)) {
571 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
572 if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI))
573 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr");
574 return nullptr;
575 }
576
577 // Compute the offset, make sure to handle the case when we're searching for
578 // zero (a weird way to spell strlen).
579 size_t I = (0xFF & CharC->getSExtValue()) == 0
580 ? Str.size()
581 : Str.find(CharC->getSExtValue());
582 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
583 return Constant::getNullValue(CI->getType());
584
585 // strchr(s+n,c) -> gep(s+n+i,c)
586 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
587}
588
589Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) {
590 Value *SrcStr = CI->getArgOperand(0);
591 Value *CharVal = CI->getArgOperand(1);
592 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
594
595 StringRef Str;
596 if (!getConstantStringInfo(SrcStr, Str)) {
597 // strrchr(s, 0) -> strchr(s, 0)
598 if (CharC && CharC->isZero())
599 return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI));
600 return nullptr;
601 }
602
603 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
604 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
605
606 // Try to expand strrchr to the memrchr nonstandard extension if it's
607 // available, or simply fail otherwise.
608 uint64_t NBytes = Str.size() + 1; // Include the terminating nul.
609 Value *Size = ConstantInt::get(SizeTTy, NBytes);
610 return copyFlags(*CI, emitMemRChr(SrcStr, CharVal, Size, B, DL, TLI));
611}
612
613Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
614 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
615 if (Str1P == Str2P) // strcmp(x,x) -> 0
616 return ConstantInt::get(CI->getType(), 0);
617
618 StringRef Str1, Str2;
619 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
620 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
621
622 // strcmp(x, y) -> cnst (if both x and y are constant strings)
623 if (HasStr1 && HasStr2)
624 return ConstantInt::getSigned(CI->getType(),
625 std::clamp(Str1.compare(Str2), -1, 1));
626
627 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
628 return B.CreateNeg(B.CreateZExt(
629 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
630
631 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
632 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
633 CI->getType());
634
635 // strcmp(P, "x") -> memcmp(P, "x", 2)
636 uint64_t Len1 = GetStringLength(Str1P);
637 if (Len1)
638 annotateDereferenceableBytes(CI, 0, Len1);
639 uint64_t Len2 = GetStringLength(Str2P);
640 if (Len2)
641 annotateDereferenceableBytes(CI, 1, Len2);
642
643 if (Len1 && Len2) {
644 return copyFlags(
645 *CI, emitMemCmp(Str1P, Str2P,
646 TLI->getAsSizeT(std::min(Len1, Len2), *CI->getModule()),
647 B, DL, TLI));
648 }
649
650 // strcmp to memcmp
651 SimplifyQuery SQ(DL, TLI, DT, AC, CI);
652 if (!HasStr1 && HasStr2) {
653 if (canTransformToMemCmp(CI, Str1P, Len2, SQ))
654 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
655 TLI->getAsSizeT(Len2, *CI->getModule()),
656 B, DL, TLI));
657 } else if (HasStr1 && !HasStr2) {
658 if (canTransformToMemCmp(CI, Str2P, Len1, SQ))
659 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
660 TLI->getAsSizeT(Len1, *CI->getModule()),
661 B, DL, TLI));
662 }
663
665 return nullptr;
666}
667
668// Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
669// arrays LHS and RHS and nonconstant Size.
671 Value *Size, bool StrNCmp,
672 IRBuilderBase &B, const DataLayout &DL);
673
674Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
675 Value *Str1P = CI->getArgOperand(0);
676 Value *Str2P = CI->getArgOperand(1);
677 Value *Size = CI->getArgOperand(2);
678 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
679 return ConstantInt::get(CI->getType(), 0);
680
681 if (isKnownNonZero(Size, DL))
683 // Get the length argument if it is constant.
685 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
686 Length = LengthArg->getZExtValue();
687 else
688 return optimizeMemCmpVarSize(CI, Str1P, Str2P, Size, true, B, DL);
689
690 if (Length == 0) // strncmp(x,y,0) -> 0
691 return ConstantInt::get(CI->getType(), 0);
692
693 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
694 return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI));
695
696 StringRef Str1, Str2;
697 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
698 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
699
700 // strncmp(x, y) -> cnst (if both x and y are constant strings)
701 if (HasStr1 && HasStr2) {
702 // Avoid truncating the 64-bit Length to 32 bits in ILP32.
703 StringRef SubStr1 = substr(Str1, Length);
704 StringRef SubStr2 = substr(Str2, Length);
705 return ConstantInt::getSigned(CI->getType(),
706 std::clamp(SubStr1.compare(SubStr2), -1, 1));
707 }
708
709 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
710 return B.CreateNeg(B.CreateZExt(
711 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
712
713 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
714 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
715 CI->getType());
716
717 uint64_t Len1 = GetStringLength(Str1P);
718 if (Len1)
719 annotateDereferenceableBytes(CI, 0, Len1);
720 uint64_t Len2 = GetStringLength(Str2P);
721 if (Len2)
722 annotateDereferenceableBytes(CI, 1, Len2);
723
724 // strncmp to memcmp
725 if (!HasStr1 && HasStr2) {
726 Len2 = std::min(Len2, Length);
727 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
728 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
729 TLI->getAsSizeT(Len2, *CI->getModule()),
730 B, DL, TLI));
731 } else if (HasStr1 && !HasStr2) {
732 Len1 = std::min(Len1, Length);
733 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
734 return copyFlags(*CI, emitMemCmp(Str1P, Str2P,
735 TLI->getAsSizeT(Len1, *CI->getModule()),
736 B, DL, TLI));
737 }
738
739 return nullptr;
740}
741
742Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) {
743 Value *Src = CI->getArgOperand(0);
744 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
745 uint64_t SrcLen = GetStringLength(Src);
746 if (SrcLen && Size) {
747 annotateDereferenceableBytes(CI, 0, SrcLen);
748 if (SrcLen <= Size->getZExtValue() + 1)
749 return copyFlags(*CI, emitStrDup(Src, B, TLI));
750 }
751
752 return nullptr;
753}
754
755Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) {
756 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
757 if (Dst == Src) // strcpy(x,x) -> x
758 return Src;
759
761 // See if we can get the length of the input string.
763 if (Len)
765 else
766 return nullptr;
767
768 // We have enough information to now generate the memcpy call to do the
769 // copy for us. Make a memcpy to copy the nul byte with align = 1.
770 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
771 TLI->getAsSizeT(Len, *CI->getModule()));
772 mergeAttributesAndFlags(NewCI, *CI);
773 return Dst;
774}
775
776Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) {
777 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
778
779 // stpcpy(d,s) -> strcpy(d,s) if the result is not used.
780 if (CI->use_empty())
781 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
782
783 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
784 Value *StrLen = emitStrLen(Src, B, DL, TLI);
785 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
786 }
787
788 // See if we can get the length of the input string.
790 if (Len)
792 else
793 return nullptr;
794
795 Value *LenV = TLI->getAsSizeT(Len, *CI->getModule());
796 Value *DstEnd = B.CreateInBoundsGEP(
797 B.getInt8Ty(), Dst, TLI->getAsSizeT(Len - 1, *CI->getModule()));
798
799 // We have enough information to now generate the memcpy call to do the
800 // copy for us. Make a memcpy to copy the nul byte with align = 1.
801 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV);
802 mergeAttributesAndFlags(NewCI, *CI);
803 return DstEnd;
804}
805
806// Optimize a call to size_t strlcpy(char*, const char*, size_t).
807
808Value *LibCallSimplifier::optimizeStrLCpy(CallInst *CI, IRBuilderBase &B) {
809 Value *Size = CI->getArgOperand(2);
810 if (isKnownNonZero(Size, DL))
811 // Like snprintf, the function stores into the destination only when
812 // the size argument is nonzero.
814 // The function reads the source argument regardless of Size (it returns
815 // its length).
817
818 uint64_t NBytes;
819 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size))
820 NBytes = SizeC->getZExtValue();
821 else
822 return nullptr;
823
824 Value *Dst = CI->getArgOperand(0);
825 Value *Src = CI->getArgOperand(1);
826 if (NBytes <= 1) {
827 if (NBytes == 1)
828 // For a call to strlcpy(D, S, 1) first store a nul in *D.
829 B.CreateStore(B.getInt8(0), Dst);
830
831 // Transform strlcpy(D, S, 0) to a call to strlen(S).
832 return copyFlags(*CI, emitStrLen(Src, B, DL, TLI));
833 }
834
835 // Try to determine the length of the source, substituting its size
836 // when it's not nul-terminated (as it's required to be) to avoid
837 // reading past its end.
838 StringRef Str;
839 if (!getConstantStringInfo(Src, Str, /*TrimAtNul=*/false))
840 return nullptr;
841
842 uint64_t SrcLen = Str.find('\0');
843 // Set if the terminating nul should be copied by the call to memcpy
844 // below.
845 bool NulTerm = SrcLen < NBytes;
846
847 if (NulTerm)
848 // Overwrite NBytes with the number of bytes to copy, including
849 // the terminating nul.
850 NBytes = SrcLen + 1;
851 else {
852 // Set the length of the source for the function to return to its
853 // size, and cap NBytes at the same.
854 SrcLen = std::min(SrcLen, uint64_t(Str.size()));
855 NBytes = std::min(NBytes - 1, SrcLen);
856 }
857
858 if (SrcLen == 0) {
859 // Transform strlcpy(D, "", N) to (*D = '\0, 0).
860 B.CreateStore(B.getInt8(0), Dst);
861 return ConstantInt::get(CI->getType(), 0);
862 }
863
864 // Transform strlcpy(D, S, N) to memcpy(D, S, N') where N' is the lower
865 // bound on strlen(S) + 1 and N, optionally followed by a nul store to
866 // D[N' - 1] if necessary.
867 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
868 TLI->getAsSizeT(NBytes, *CI->getModule()));
869 mergeAttributesAndFlags(NewCI, *CI);
870
871 if (!NulTerm) {
872 Value *EndOff = ConstantInt::get(CI->getType(), NBytes);
873 Value *EndPtr = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, EndOff);
874 B.CreateStore(B.getInt8(0), EndPtr);
875 }
876
877 // Like snprintf, strlcpy returns the number of nonzero bytes that would
878 // have been copied if the bound had been sufficiently big (which in this
879 // case is strlen(Src)).
880 return ConstantInt::get(CI->getType(), SrcLen);
881}
882
883// Optimize a call CI to either stpncpy when RetEnd is true, or to strncpy
884// otherwise.
885Value *LibCallSimplifier::optimizeStringNCpy(CallInst *CI, bool RetEnd,
886 IRBuilderBase &B) {
887 Value *Dst = CI->getArgOperand(0);
888 Value *Src = CI->getArgOperand(1);
889 Value *Size = CI->getArgOperand(2);
890
891 if (isKnownNonZero(Size, DL)) {
892 // Both st{p,r}ncpy(D, S, N) access the source and destination arrays
893 // only when N is nonzero.
896 }
897
898 // If the "bound" argument is known set N to it. Otherwise set it to
899 // UINT64_MAX and handle it later.
901 if (ConstantInt *SizeC = dyn_cast<ConstantInt>(Size))
902 N = SizeC->getZExtValue();
903
904 if (N == 0)
905 // Fold st{p,r}ncpy(D, S, 0) to D.
906 return Dst;
907
908 if (N == 1) {
909 Type *CharTy = B.getInt8Ty();
910 Value *CharVal = B.CreateLoad(CharTy, Src, "stxncpy.char0");
911 B.CreateStore(CharVal, Dst);
912 if (!RetEnd)
913 // Transform strncpy(D, S, 1) to return (*D = *S), D.
914 return Dst;
915
916 // Transform stpncpy(D, S, 1) to return (*D = *S) ? D + 1 : D.
917 Value *ZeroChar = ConstantInt::get(CharTy, 0);
918 Value *Cmp = B.CreateICmpEQ(CharVal, ZeroChar, "stpncpy.char0cmp");
919
920 Value *Off1 = B.getInt32(1);
921 Value *EndPtr = B.CreateInBoundsGEP(CharTy, Dst, Off1, "stpncpy.end");
922 return B.CreateSelect(Cmp, Dst, EndPtr, "stpncpy.sel");
923 }
924
925 // If the length of the input string is known set SrcLen to it.
926 uint64_t SrcLen = GetStringLength(Src);
927 if (SrcLen)
928 annotateDereferenceableBytes(CI, 1, SrcLen);
929 else
930 return nullptr;
931
932 --SrcLen; // Unbias length.
933
934 if (SrcLen == 0) {
935 // Transform st{p,r}ncpy(D, "", N) to memset(D, '\0', N) for any N.
936 Align MemSetAlign =
937 CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne();
938 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign);
939 AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0));
940 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
941 CI->getContext(), 0, ArgAttrs));
942 copyFlags(*CI, NewCI);
943 return Dst;
944 }
945
946 if (N > SrcLen + 1) {
947 if (N > 128)
948 // Bail if N is large or unknown.
949 return nullptr;
950
951 // st{p,r}ncpy(D, "a", N) -> memcpy(D, "a\0\0\0", N) for N <= 128.
952 StringRef Str;
953 if (!getConstantStringInfo(Src, Str))
954 return nullptr;
955 std::string SrcStr = Str.str();
956 // Create a bigger, nul-padded array with the same length, SrcLen,
957 // as the original string.
958 SrcStr.resize(N, '\0');
959 Src = B.CreateGlobalString(SrcStr, "str", /*AddressSpace=*/0,
960 /*M=*/nullptr, /*AddNull=*/false);
961 }
962
963 // st{p,r}ncpy(D, S, N) -> memcpy(align 1 D, align 1 S, N) when both
964 // S and N are constant.
965 CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
966 TLI->getAsSizeT(N, *CI->getModule()));
967 mergeAttributesAndFlags(NewCI, *CI);
968 if (!RetEnd)
969 return Dst;
970
971 // stpncpy(D, S, N) returns the address of the first null in D if it writes
972 // one, otherwise D + N.
973 Value *Off = B.getInt64(std::min(SrcLen, N));
974 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, Off, "endptr");
975}
976
977Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B,
978 unsigned CharSize,
979 Value *Bound) {
980 Value *Src = CI->getArgOperand(0);
981 Type *CharTy = B.getIntNTy(CharSize);
982
984 (!Bound || isKnownNonZero(Bound, DL))) {
985 // Fold strlen:
986 // strlen(x) != 0 --> *x != 0
987 // strlen(x) == 0 --> *x == 0
988 // and likewise strnlen with constant N > 0:
989 // strnlen(x, N) != 0 --> *x != 0
990 // strnlen(x, N) == 0 --> *x == 0
991 return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"),
992 CI->getType());
993 }
994
995 if (Bound) {
996 if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) {
997 if (BoundCst->isZero())
998 // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise.
999 return ConstantInt::get(CI->getType(), 0);
1000
1001 if (BoundCst->isOne()) {
1002 // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s.
1003 Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0");
1004 Value *ZeroChar = ConstantInt::get(CharTy, 0);
1005 Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp");
1006 return B.CreateZExt(Cmp, CI->getType());
1007 }
1008 }
1009 }
1010
1011 if (uint64_t Len = GetStringLength(Src, CharSize)) {
1012 Value *LenC = ConstantInt::get(CI->getType(), Len - 1);
1013 // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2
1014 // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound.
1015 if (Bound)
1016 return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound);
1017 return LenC;
1018 }
1019
1020 if (Bound)
1021 // Punt for strnlen for now.
1022 return nullptr;
1023
1024 // If s is a constant pointer pointing to a string literal, we can fold
1025 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
1026 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
1027 // We only try to simplify strlen when the pointer s points to an array
1028 // of CharSize elements. Otherwise, we would need to scale the offset x before
1029 // doing the subtraction. This will make the optimization more complex, and
1030 // it's not very useful because calling strlen for a pointer of other types is
1031 // very uncommon.
1032 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
1033 unsigned BW = DL.getIndexTypeSizeInBits(GEP->getType());
1034 SmallMapVector<Value *, APInt, 4> VarOffsets;
1035 APInt ConstOffset(BW, 0);
1036 assert(CharSize % 8 == 0 && "Expected a multiple of 8 sized CharSize");
1037 // Check the gep is a single variable offset.
1038 if (!GEP->collectOffset(DL, BW, VarOffsets, ConstOffset) ||
1039 VarOffsets.size() != 1 || ConstOffset != 0 ||
1040 VarOffsets.begin()->second != CharSize / 8)
1041 return nullptr;
1042
1043 ConstantDataArraySlice Slice;
1044 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
1045 uint64_t NullTermIdx;
1046 if (Slice.Array == nullptr) {
1047 NullTermIdx = 0;
1048 } else {
1049 NullTermIdx = ~((uint64_t)0);
1050 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
1051 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
1052 NullTermIdx = I;
1053 break;
1054 }
1055 }
1056 // If the string does not have '\0', leave it to strlen to compute
1057 // its length.
1058 if (NullTermIdx == ~((uint64_t)0))
1059 return nullptr;
1060 }
1061
1062 Value *Offset = VarOffsets.begin()->first;
1063 KnownBits Known = computeKnownBits(Offset, DL, nullptr, CI, nullptr);
1064
1065 // If Offset is not provably in the range [0, NullTermIdx], we can still
1066 // optimize if we can prove that the program has undefined behavior when
1067 // Offset is outside that range. That is the case when GEP->getOperand(0)
1068 // is a pointer to an object whose memory extent is NullTermIdx+1.
1069 if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) ||
1070 (isa<GlobalVariable>(GEP->getOperand(0)) &&
1071 NullTermIdx == Slice.Length - 1)) {
1072 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
1073 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
1074 Offset);
1075 }
1076 }
1077 }
1078
1079 // strlen(x?"foo":"bars") --> x ? 3 : 4
1080 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
1081 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
1082 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
1083 if (LenTrue && LenFalse) {
1084 ORE.emit([&]() {
1085 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
1086 << "folded strlen(select) to select of constants";
1087 });
1088 return B.CreateSelect(SI->getCondition(),
1089 ConstantInt::get(CI->getType(), LenTrue - 1),
1090 ConstantInt::get(CI->getType(), LenFalse - 1), "",
1091 ProfcheckDisableMetadataFixes ? nullptr : SI);
1092 }
1093 }
1094
1095 return nullptr;
1096}
1097
1098Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) {
1099 if (Value *V = optimizeStringLength(CI, B, 8))
1100 return V;
1102 return nullptr;
1103}
1104
1105Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) {
1106 Value *Bound = CI->getArgOperand(1);
1107 if (Value *V = optimizeStringLength(CI, B, 8, Bound))
1108 return V;
1109
1110 if (isKnownNonZero(Bound, DL))
1112 return nullptr;
1113}
1114
1115Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) {
1116 Module &M = *CI->getModule();
1117 unsigned WCharSize = M.getWCharSize();
1118 // We cannot perform this optimization without wchar_size metadata.
1119 if (WCharSize == 0)
1120 return nullptr;
1121
1122 if (Value *V = optimizeStringLength(CI, B, WCharSize * 8))
1123 return V;
1124 // At least the terminating wide character is read.
1125 annotateNonNullNoUndefBasedOnAccess(CI, 0, WCharSize);
1126 return nullptr;
1127}
1128
1129Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) {
1130 StringRef S1, S2;
1131 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1132 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1133
1134 // strpbrk(s, "") -> nullptr
1135 // strpbrk("", s) -> nullptr
1136 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
1137 return Constant::getNullValue(CI->getType());
1138
1139 // Constant folding.
1140 if (HasS1 && HasS2) {
1141 size_t I = S1.find_first_of(S2);
1142 if (I == StringRef::npos) // No match.
1143 return Constant::getNullValue(CI->getType());
1144
1145 return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0),
1146 B.getInt64(I), "strpbrk");
1147 }
1148
1149 // strpbrk(s, "a") -> strchr(s, 'a')
1150 if (HasS2 && S2.size() == 1)
1151 return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI));
1152
1153 return nullptr;
1154}
1155
1156Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) {
1157 Value *EndPtr = CI->getArgOperand(1);
1158 if (isa<ConstantPointerNull>(EndPtr)) {
1159 // With a null EndPtr, this function won't capture the main argument.
1160 // It would be readonly too, except that it still may write to errno.
1163 }
1164
1165 return nullptr;
1166}
1167
1168Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) {
1169 StringRef S1, S2;
1170 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1171 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1172
1173 // strspn(s, "") -> 0
1174 // strspn("", s) -> 0
1175 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
1176 return Constant::getNullValue(CI->getType());
1177
1178 // Constant folding.
1179 if (HasS1 && HasS2) {
1180 size_t Pos = S1.find_first_not_of(S2);
1181 if (Pos == StringRef::npos)
1182 Pos = S1.size();
1183 return ConstantInt::get(CI->getType(), Pos);
1184 }
1185
1186 return nullptr;
1187}
1188
1189Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) {
1190 StringRef S1, S2;
1191 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
1192 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
1193
1194 // strcspn("", s) -> 0
1195 if (HasS1 && S1.empty())
1196 return Constant::getNullValue(CI->getType());
1197
1198 // Constant folding.
1199 if (HasS1 && HasS2) {
1200 size_t Pos = S1.find_first_of(S2);
1201 if (Pos == StringRef::npos)
1202 Pos = S1.size();
1203 return ConstantInt::get(CI->getType(), Pos);
1204 }
1205
1206 // strcspn(s, "") -> strlen(s)
1207 if (HasS2 && S2.empty())
1208 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI));
1209
1210 return nullptr;
1211}
1212
1213Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) {
1214 // fold strstr(x, x) -> x.
1215 if (CI->getArgOperand(0) == CI->getArgOperand(1))
1216 return CI->getArgOperand(0);
1217
1218 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
1220 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
1221 if (!StrLen)
1222 return nullptr;
1223 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
1224 StrLen, B, DL, TLI);
1225 if (!StrNCmp)
1226 return nullptr;
1227 for (User *U : llvm::make_early_inc_range(CI->users())) {
1228 ICmpInst *Old = cast<ICmpInst>(U);
1229 Value *Cmp =
1230 B.CreateICmp(Old->getPredicate(), StrNCmp,
1231 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
1232 replaceAllUsesWith(Old, Cmp);
1233 }
1234 return CI;
1235 }
1236
1237 // See if either input string is a constant string.
1238 StringRef SearchStr, ToFindStr;
1239 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
1240 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
1241
1242 // fold strstr(x, "") -> x.
1243 if (HasStr2 && ToFindStr.empty())
1244 return CI->getArgOperand(0);
1245
1246 // If both strings are known, constant fold it.
1247 if (HasStr1 && HasStr2) {
1248 size_t Offset = SearchStr.find(ToFindStr);
1249
1250 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
1251 return Constant::getNullValue(CI->getType());
1252
1253 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
1254 return B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), CI->getArgOperand(0),
1255 Offset, "strstr");
1256 }
1257
1258 // fold strstr(x, "y") -> strchr(x, 'y').
1259 if (HasStr2 && ToFindStr.size() == 1) {
1260 return emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
1261 }
1262
1264 return nullptr;
1265}
1266
1267Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) {
1268 Value *SrcStr = CI->getArgOperand(0);
1269 Value *Size = CI->getArgOperand(2);
1271 Value *CharVal = CI->getArgOperand(1);
1272 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1273 Value *NullPtr = Constant::getNullValue(CI->getType());
1274
1275 if (LenC) {
1276 if (LenC->isZero())
1277 // Fold memrchr(x, y, 0) --> null.
1278 return NullPtr;
1279
1280 if (LenC->isOne()) {
1281 // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y,
1282 // constant or otherwise.
1283 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0");
1284 // Slice off the character's high end bits.
1285 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1286 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp");
1287 return B.CreateSelectWithUnknownProfile(Cmp, SrcStr, NullPtr, DEBUG_TYPE,
1288 "memrchr.sel");
1289 }
1290 }
1291
1292 StringRef Str;
1293 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false))
1294 return nullptr;
1295
1296 if (Str.size() == 0)
1297 // If the array is empty fold memrchr(A, C, N) to null for any value
1298 // of C and N on the basis that the only valid value of N is zero
1299 // (otherwise the call is undefined).
1300 return NullPtr;
1301
1302 uint64_t EndOff = UINT64_MAX;
1303 if (LenC) {
1304 EndOff = LenC->getZExtValue();
1305 if (Str.size() < EndOff)
1306 // Punt out-of-bounds accesses to sanitizers and/or libc.
1307 return nullptr;
1308 }
1309
1310 if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) {
1311 // Fold memrchr(S, C, N) for a constant C.
1312 size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff);
1313 if (Pos == StringRef::npos)
1314 // When the character is not in the source array fold the result
1315 // to null regardless of Size.
1316 return NullPtr;
1317
1318 if (LenC)
1319 // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos.
1320 return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos));
1321
1322 if (Str.find(Str[Pos]) == Pos) {
1323 // When there is just a single occurrence of C in S, i.e., the one
1324 // in Str[Pos], fold
1325 // memrchr(s, c, N) --> N <= Pos ? null : s + Pos
1326 // for nonconstant N.
1327 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1328 "memrchr.cmp");
1329 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr,
1330 B.getInt64(Pos), "memrchr.ptr_plus");
1331 return B.CreateSelectWithUnknownProfile(Cmp, NullPtr, SrcPlus, DEBUG_TYPE,
1332 "memrchr.sel");
1333 }
1334 }
1335
1336 // Truncate the string to search at most EndOff characters.
1337 Str = Str.substr(0, EndOff);
1338 if (Str.find_first_not_of(Str[0]) != StringRef::npos)
1339 return nullptr;
1340
1341 // If the source array consists of all equal characters, then for any
1342 // C and N (whether in bounds or not), fold memrchr(S, C, N) to
1343 // N != 0 && *S == C ? S + N - 1 : null
1344 Type *SizeTy = Size->getType();
1345 Type *Int8Ty = B.getInt8Ty();
1346 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1347 // Slice off the sought character's high end bits.
1348 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1349 Value *CEqS0 =
1350 B.CreateICmpEQ(ConstantInt::get(Int8Ty, (unsigned char)Str[0]), CharVal);
1351 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0);
1352 if (auto *AndSI = dyn_cast<SelectInst>(And))
1354 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1));
1355 Value *SrcPlus =
1356 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus");
1357 return B.CreateSelectWithUnknownProfile(And, SrcPlus, NullPtr, DEBUG_TYPE,
1358 "memrchr.sel");
1359}
1360
1361Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) {
1362 Value *SrcStr = CI->getArgOperand(0);
1363 Value *Size = CI->getArgOperand(2);
1364
1365 if (isKnownNonZero(Size, DL)) {
1367 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1368 return memChrToCharCompare(CI, Size, B, DL);
1369 }
1370
1371 Value *CharVal = CI->getArgOperand(1);
1372 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
1373 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1374 Value *NullPtr = Constant::getNullValue(CI->getType());
1375
1376 // memchr(x, y, 0) -> null
1377 if (LenC) {
1378 if (LenC->isZero())
1379 return NullPtr;
1380
1381 if (LenC->isOne()) {
1382 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y,
1383 // constant or otherwise.
1384 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0");
1385 // Slice off the character's high end bits.
1386 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1387 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp");
1388 // The condition depends on the value of the string being equal to the
1389 // query, neither of which we know without value profiling, so mark the
1390 // profile unknown.
1391 return B.CreateSelectWithUnknownProfile(Cmp, SrcStr, NullPtr, DEBUG_TYPE,
1392 "memchr.sel");
1393 }
1394 }
1395
1396 StringRef Str;
1397 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false))
1398 return nullptr;
1399
1400 if (CharC) {
1401 size_t Pos = Str.find(CharC->getZExtValue());
1402 if (Pos == StringRef::npos)
1403 // When the character is not in the source array fold the result
1404 // to null regardless of Size.
1405 return NullPtr;
1406
1407 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos
1408 // When the constant Size is less than or equal to the character
1409 // position also fold the result to null.
1410 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1411 "memchr.cmp");
1412 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos),
1413 "memchr.ptr");
1414 // The condition is dependent upon the value of n, which we cannot infer
1415 // without value profiling, so mark the profile unknown.
1416 return B.CreateSelectWithUnknownProfile(Cmp, NullPtr, SrcPlus, DEBUG_TYPE);
1417 }
1418
1419 if (Str.size() == 0)
1420 // If the array is empty fold memchr(A, C, N) to null for any value
1421 // of C and N on the basis that the only valid value of N is zero
1422 // (otherwise the call is undefined).
1423 return NullPtr;
1424
1425 if (LenC)
1426 Str = substr(Str, LenC->getZExtValue());
1427
1428 size_t Pos = Str.find_first_not_of(Str[0]);
1429 if (Pos == StringRef::npos
1430 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) {
1431 // If the source array consists of at most two consecutive sequences
1432 // of the same characters, then for any C and N (whether in bounds or
1433 // not), fold memchr(S, C, N) to
1434 // N != 0 && *S == C ? S : null
1435 // or for the two sequences to:
1436 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null)
1437 // ^Sel2 ^Sel1 are denoted above.
1438 // The latter makes it also possible to fold strchr() calls with strings
1439 // of the same characters.
1440 Type *SizeTy = Size->getType();
1441 Type *Int8Ty = B.getInt8Ty();
1442
1443 // Slice off the sought character's high end bits.
1444 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1445
1446 Value *Sel1 = NullPtr;
1447 if (Pos != StringRef::npos) {
1448 // Handle two consecutive sequences of the same characters.
1449 Value *PosVal = ConstantInt::get(SizeTy, Pos);
1450 Value *StrPos = ConstantInt::get(Int8Ty, (unsigned char)Str[Pos]);
1451 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos);
1452 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal);
1453 Value *And = B.CreateAnd(CEqSPos, NGtPos);
1454 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal);
1455 // The condition depends on the value of the query and size, neither of
1456 // which we know without value profiling, so mark the profile unknown.
1457 Sel1 = B.CreateSelectWithUnknownProfile(And, SrcPlus, NullPtr, DEBUG_TYPE,
1458 "memchr.sel1");
1459 }
1460
1461 Value *Str0 = ConstantInt::get(Int8Ty, (unsigned char)Str[0]);
1462 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal);
1463 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1464 Value *And = B.CreateAnd(NNeZ, CEqS0);
1465 // The condition depends on the value of the query and size, neither of
1466 // which we know without value profiling, so mark the profile unknown.
1467 return B.CreateSelectWithUnknownProfile(And, SrcStr, Sel1, DEBUG_TYPE,
1468 "memchr.sel2");
1469 }
1470
1471 if (!LenC) {
1472 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1473 // S is dereferenceable so it's safe to load from it and fold
1474 // memchr(S, C, N) == S to N && *S == C for any C and N.
1475 // TODO: This is safe even for nonconstant S.
1476 return memChrToCharCompare(CI, Size, B, DL);
1477
1478 // From now on we need a constant length and constant array.
1479 return nullptr;
1480 }
1481
1482 bool OptForSize = llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
1484
1485 // If the char is variable but the input str and length are not we can turn
1486 // this memchr call into a simple bit field test. Of course this only works
1487 // when the return value is only checked against null.
1488 //
1489 // It would be really nice to reuse switch lowering here but we can't change
1490 // the CFG at this point.
1491 //
1492 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
1493 // != 0
1494 // after bounds check.
1495 if (OptForSize || Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI))
1496 return nullptr;
1497
1498 unsigned char Max =
1499 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
1500 reinterpret_cast<const unsigned char *>(Str.end()));
1501
1502 // Make sure the bit field we're about to create fits in a register on the
1503 // target.
1504 // FIXME: On a 64 bit architecture this prevents us from using the
1505 // interesting range of alpha ascii chars. We could do better by emitting
1506 // two bitfields or shifting the range by 64 if no lower chars are used.
1507 if (!DL.fitsInLegalInteger(Max + 1)) {
1508 // Build chain of ORs
1509 // Transform:
1510 // memchr("abcd", C, 4) != nullptr
1511 // to:
1512 // (C == 'a' || C == 'b' || C == 'c' || C == 'd') != 0
1513 std::string SortedStr = Str.str();
1514 llvm::sort(SortedStr);
1515 // Compute the number of of non-contiguous ranges.
1516 unsigned NonContRanges = 1;
1517 for (size_t i = 1; i < SortedStr.size(); ++i) {
1518 if (SortedStr[i] > SortedStr[i - 1] + 1) {
1519 NonContRanges++;
1520 }
1521 }
1522
1523 // Restrict this optimization to profitable cases with one or two range
1524 // checks.
1525 if (NonContRanges > 2)
1526 return nullptr;
1527
1528 // Slice off the character's high end bits.
1529 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1530
1531 SmallVector<Value *> CharCompares;
1532 for (unsigned char C : SortedStr)
1533 CharCompares.push_back(B.CreateICmpEQ(CharVal, B.getInt8(C)));
1534
1535 return B.CreateIntToPtr(B.CreateOr(CharCompares), CI->getType());
1536 }
1537
1538 // For the bit field use a power-of-2 type with at least 8 bits to avoid
1539 // creating unnecessary illegal types.
1540 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
1541
1542 // Now build the bit field.
1543 APInt Bitfield(Width, 0);
1544 for (char C : Str)
1545 Bitfield.setBit((unsigned char)C);
1546 Value *BitfieldC = B.getInt(Bitfield);
1547
1548 // Adjust width of "C" to the bitfield width, then mask off the high bits.
1549 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType());
1550 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
1551
1552 // First check that the bit field access is within bounds.
1553 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
1554 "memchr.bounds");
1555
1556 // Create code that checks if the given bit is set in the field.
1557 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
1558 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
1559
1560 // Finally merge both checks and cast to pointer type. The inttoptr
1561 // implicitly zexts the i1 to intptr type.
1562 Value *Memchr = B.CreateLogicalAnd(Bounds, Bits, "memchr");
1563 // We construct an and between the value of the memory and the bytes to search
1564 // for. We cannot infer how often this would be true without value profiling
1565 // for the query, so mark the profile unknown.
1566 if (auto *SI = dyn_cast<SelectInst>(Memchr))
1568 return B.CreateIntToPtr(Memchr, CI->getType());
1569}
1570
1571// Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
1572// arrays LHS and RHS and nonconstant Size.
1574 Value *Size, bool StrNCmp,
1575 IRBuilderBase &B, const DataLayout &DL) {
1576 if (LHS == RHS) // memcmp(s,s,x) -> 0
1577 return Constant::getNullValue(CI->getType());
1578
1579 StringRef LStr, RStr;
1580 if (!getConstantStringInfo(LHS, LStr, /*TrimAtNul=*/false) ||
1581 !getConstantStringInfo(RHS, RStr, /*TrimAtNul=*/false))
1582 return nullptr;
1583
1584 // If the contents of both constant arrays are known, fold a call to
1585 // memcmp(A, B, N) to
1586 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0)
1587 // where Pos is the first mismatch between A and B, determined below.
1588
1589 uint64_t Pos = 0;
1590 Value *Zero = ConstantInt::get(CI->getType(), 0);
1591 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) {
1592 if (Pos == MinSize ||
1593 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) {
1594 // One array is a leading part of the other of equal or greater
1595 // size, or for strncmp, the arrays are equal strings.
1596 // Fold the result to zero. Size is assumed to be in bounds, since
1597 // otherwise the call would be undefined.
1598 return Zero;
1599 }
1600
1601 if (LStr[Pos] != RStr[Pos])
1602 break;
1603 }
1604
1605 // Normalize the result.
1606 typedef unsigned char UChar;
1607 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
1608 Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
1609 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
1610 Value *Res = ConstantInt::getSigned(CI->getType(), IRes);
1611 return B.CreateSelect(Cmp, Zero, Res);
1612}
1613
1614// Optimize a memcmp call CI with constant size Len.
1616 uint64_t Len, IRBuilderBase &B,
1617 const DataLayout &DL) {
1618 if (Len == 0) // memcmp(s1,s2,0) -> 0
1619 return Constant::getNullValue(CI->getType());
1620
1621 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1622 if (Len == 1) {
1623 Value *LHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), LHS, "lhsc"),
1624 CI->getType(), "lhsv");
1625 Value *RHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), RHS, "rhsc"),
1626 CI->getType(), "rhsv");
1627 return B.CreateSub(LHSV, RHSV, "chardiff");
1628 }
1629
1630 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
1631 // TODO: The case where both inputs are constants does not need to be limited
1632 // to legal integers or equality comparison. See block below this.
1633 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
1634 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1635 Align PrefAlignment = DL.getPrefTypeAlign(IntType);
1636
1637 // First, see if we can fold either argument to a constant.
1638 Value *LHSV = nullptr;
1639 if (auto *LHSC = dyn_cast<Constant>(LHS))
1640 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1641
1642 Value *RHSV = nullptr;
1643 if (auto *RHSC = dyn_cast<Constant>(RHS))
1644 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1645
1646 // Don't generate unaligned loads. If either source is constant data,
1647 // alignment doesn't matter for that source because there is no load.
1648 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1649 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1650 if (!LHSV)
1651 LHSV = B.CreateLoad(IntType, LHS, "lhsv");
1652 if (!RHSV)
1653 RHSV = B.CreateLoad(IntType, RHS, "rhsv");
1654 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
1655 }
1656 }
1657
1658 return nullptr;
1659}
1660
1661// Most simplifications for memcmp also apply to bcmp.
1662Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1663 IRBuilderBase &B) {
1664 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1665 Value *Size = CI->getArgOperand(2);
1666
1667 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1668
1669 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL))
1670 return Res;
1671
1672 // Handle constant Size.
1673 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1674 if (!LenC)
1675 return nullptr;
1676
1677 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL);
1678}
1679
1680Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
1681 Module *M = CI->getModule();
1682 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1683 return V;
1684
1685 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
1686 // bcmp can be more efficient than memcmp because it only has to know that
1687 // there is a difference, not how different one is to the other.
1688 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) &&
1690 Value *LHS = CI->getArgOperand(0);
1691 Value *RHS = CI->getArgOperand(1);
1692 Value *Size = CI->getArgOperand(2);
1693 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
1694 }
1695
1696 return nullptr;
1697}
1698
1699Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
1700 return optimizeMemCmpBCmpCommon(CI, B);
1701}
1702
1703Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
1704 Value *Size = CI->getArgOperand(2);
1705 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1706 if (isa<IntrinsicInst>(CI))
1707 return nullptr;
1708
1709 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
1710 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
1711 CI->getArgOperand(1), Align(1), Size);
1712 mergeAttributesAndFlags(NewCI, *CI);
1713 return CI->getArgOperand(0);
1714}
1715
1716Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
1717 Value *Dst = CI->getArgOperand(0);
1718 Value *Src = CI->getArgOperand(1);
1719 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1720 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
1721 StringRef SrcStr;
1722 if (CI->use_empty() && Dst == Src)
1723 return Dst;
1724 // memccpy(d, s, c, 0) -> nullptr
1725 if (N) {
1726 if (N->isNullValue())
1727 return Constant::getNullValue(CI->getType());
1728 if (!getConstantStringInfo(Src, SrcStr, /*TrimAtNul=*/false) ||
1729 // TODO: Handle zeroinitializer.
1730 !StopChar)
1731 return nullptr;
1732 } else {
1733 return nullptr;
1734 }
1735
1736 // Wrap arg 'c' of type int to char
1737 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
1738 if (Pos == StringRef::npos) {
1739 if (N->getZExtValue() <= SrcStr.size()) {
1740 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
1741 CI->getArgOperand(3)));
1742 return Constant::getNullValue(CI->getType());
1743 }
1744 return nullptr;
1745 }
1746
1747 Value *NewN =
1748 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
1749 // memccpy -> llvm.memcpy
1750 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
1751 return Pos + 1 <= N->getZExtValue()
1752 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
1754}
1755
1756Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
1757 Value *Dst = CI->getArgOperand(0);
1758 Value *N = CI->getArgOperand(2);
1759 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1760 CallInst *NewCI =
1761 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
1762 // Propagate attributes, but memcpy has no return value, so make sure that
1763 // any return attributes are compliant.
1764 // TODO: Attach return value attributes to the 1st operand to preserve them?
1765 mergeAttributesAndFlags(NewCI, *CI);
1766 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1767}
1768
1769Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
1770 Value *Size = CI->getArgOperand(2);
1771 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1772 if (isa<IntrinsicInst>(CI))
1773 return nullptr;
1774
1775 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1776 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
1777 CI->getArgOperand(1), Align(1), Size);
1778 mergeAttributesAndFlags(NewCI, *CI);
1779 return CI->getArgOperand(0);
1780}
1781
1782Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
1783 Value *Size = CI->getArgOperand(2);
1785 if (isa<IntrinsicInst>(CI))
1786 return nullptr;
1787
1788 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1789 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1790 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
1791 mergeAttributesAndFlags(NewCI, *CI);
1792 return CI->getArgOperand(0);
1793}
1794
1795Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
1797 Value *Malloc = emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1798 if (auto *MallocCI = dyn_cast_or_null<CallInst>(Malloc))
1799 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alloc_token))
1800 MallocCI->setMetadata(LLVMContext::MD_alloc_token, MD);
1801 return copyFlags(*CI, Malloc);
1802 }
1803
1804 return nullptr;
1805}
1806
1807// Optionally allow optimization of nobuiltin calls to operator new and its
1808// variants.
1809Value *LibCallSimplifier::maybeOptimizeNoBuiltinOperatorNew(CallInst *CI,
1810 IRBuilderBase &B) {
1811 if (!OptimizeHotColdNew)
1812 return nullptr;
1814 if (!Callee)
1815 return nullptr;
1816 LibFunc Func = TLI->getLibFunc(*Callee);
1817 if (Func == NotLibFunc)
1818 return nullptr;
1819 switch (Func) {
1820 case LibFunc_Znwm:
1821 case LibFunc_ZnwmRKSt9nothrow_t:
1822 case LibFunc_ZnwmSt11align_val_t:
1823 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1824 case LibFunc_Znam:
1825 case LibFunc_ZnamRKSt9nothrow_t:
1826 case LibFunc_ZnamSt11align_val_t:
1827 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
1828 case LibFunc_size_returning_new:
1829 case LibFunc_size_returning_new_aligned:
1830 // By default normal operator new calls (not already passing a hot_cold_t
1831 // parameter) are not mutated if the call is not marked builtin. Optionally
1832 // enable that in cases where it is known to be safe.
1834 return nullptr;
1835 break;
1836 case LibFunc_Znwm12__hot_cold_t:
1837 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1838 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1839 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1840 case LibFunc_Znam12__hot_cold_t:
1841 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1842 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1843 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1844 case LibFunc_size_returning_new_hot_cold:
1845 case LibFunc_size_returning_new_aligned_hot_cold:
1846 // If the nobuiltin call already passes a hot_cold_t parameter, allow update
1847 // of that parameter when enabled.
1849 return nullptr;
1850 break;
1851 default:
1852 return nullptr;
1853 }
1854 return optimizeNew(CI, B, Func);
1855}
1856
1857// When enabled, replace operator new() calls marked with a hot or cold memprof
1858// attribute with an operator new() call that takes a __hot_cold_t parameter.
1859// Currently this is supported by the open source version of tcmalloc, see:
1860// https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h
1861Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B,
1862 LibFunc &Func) {
1863 if (!OptimizeHotColdNew)
1864 return nullptr;
1865
1866 uint8_t HotCold;
1867 bool IsCold = false;
1868 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold") {
1869 HotCold = ColdNewHintValue;
1870 IsCold = true;
1871 } else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1872 "notcold")
1873 HotCold = NotColdNewHintValue;
1874 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot")
1875 HotCold = HotNewHintValue;
1876 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1877 "ambiguous")
1878 HotCold = AmbiguousNewHintValue;
1879 else
1880 return nullptr;
1881
1882 bool ShouldOptimizeExistingHotColdNew =
1885 IsCold);
1886
1887 Value *HotColdVal = B.getInt8(HotCold);
1888 auto getHotColdHintForExisting = [&](uint8_t HotCold) -> Value * {
1889 // If not taking the minimum, simply use the compiler hint value.
1891 return HotColdVal;
1892 Value *ExistingHint = CI->getArgOperand(CI->arg_size() - 1);
1893 if (ExistingHint->getType() != B.getInt8Ty())
1894 ExistingHint = B.CreateTruncOrBitCast(ExistingHint, B.getInt8Ty());
1895 // Emit a umin intrinsic to take the minimum of the existing hint and the
1896 // compiler hint. When the existing hint is a compile-time constant, the
1897 // IRBuilder folder will automatically constant-fold this into a constant.
1898 return B.CreateBinaryIntrinsic(Intrinsic::umin, ExistingHint, HotColdVal);
1899 };
1900
1901 // For calls that already pass a hot/cold hint, only update the hint if
1902 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint
1903 // if cold or hot, and leave as-is for default handling if "notcold" aka warm.
1904 // Note that in cases where we decide it is "notcold", it might be slightly
1905 // better to replace the hinted call with a non hinted call, to avoid the
1906 // extra parameter and the if condition check of the hint value in the
1907 // allocator. This can be considered in the future.
1908 Value *NewCall = nullptr;
1909 switch (Func) {
1910 case LibFunc_Znwm12__hot_cold_t:
1911 if (ShouldOptimizeExistingHotColdNew)
1912 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1913 LibFunc_Znwm12__hot_cold_t,
1914 getHotColdHintForExisting(HotCold));
1915 break;
1916 case LibFunc_Znwm:
1917 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1918 LibFunc_Znwm12__hot_cold_t, HotColdVal);
1919 break;
1920 case LibFunc_Znam12__hot_cold_t:
1921 if (ShouldOptimizeExistingHotColdNew)
1922 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1923 LibFunc_Znam12__hot_cold_t,
1924 getHotColdHintForExisting(HotCold));
1925 break;
1926 case LibFunc_Znam:
1927 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1928 LibFunc_Znam12__hot_cold_t, HotColdVal);
1929 break;
1930 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1931 if (ShouldOptimizeExistingHotColdNew)
1932 NewCall =
1934 TLI, LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t,
1935 getHotColdHintForExisting(HotCold));
1936 break;
1937 case LibFunc_ZnwmRKSt9nothrow_t:
1938 NewCall = emitHotColdNewNoThrow(
1939 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1940 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotColdVal);
1941 break;
1942 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1943 if (ShouldOptimizeExistingHotColdNew)
1944 NewCall =
1946 TLI, LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t,
1947 getHotColdHintForExisting(HotCold));
1948 break;
1949 case LibFunc_ZnamRKSt9nothrow_t:
1950 NewCall = emitHotColdNewNoThrow(
1951 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1952 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotColdVal);
1953 break;
1954 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1955 if (ShouldOptimizeExistingHotColdNew)
1956 NewCall =
1958 TLI, LibFunc_ZnwmSt11align_val_t12__hot_cold_t,
1959 getHotColdHintForExisting(HotCold));
1960 break;
1961 case LibFunc_ZnwmSt11align_val_t:
1962 NewCall = emitHotColdNewAligned(
1963 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1964 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotColdVal);
1965 break;
1966 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1967 if (ShouldOptimizeExistingHotColdNew)
1968 NewCall =
1970 TLI, LibFunc_ZnamSt11align_val_t12__hot_cold_t,
1971 getHotColdHintForExisting(HotCold));
1972 break;
1973 case LibFunc_ZnamSt11align_val_t:
1974 NewCall = emitHotColdNewAligned(
1975 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1976 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotColdVal);
1977 break;
1978 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1979 if (ShouldOptimizeExistingHotColdNew)
1981 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1982 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1983 getHotColdHintForExisting(HotCold));
1984 break;
1985 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1987 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1988 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1989 HotColdVal);
1990 break;
1991 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1992 if (ShouldOptimizeExistingHotColdNew)
1994 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1995 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1996 getHotColdHintForExisting(HotCold));
1997 break;
1998 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
2000 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
2001 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
2002 HotColdVal);
2003 break;
2004 case LibFunc_size_returning_new:
2005 NewCall = emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI,
2006 LibFunc_size_returning_new_hot_cold,
2007 HotColdVal, CI->getType());
2008 break;
2009 case LibFunc_size_returning_new_hot_cold:
2010 if (ShouldOptimizeExistingHotColdNew)
2012 CI->getArgOperand(0), B, TLI, LibFunc_size_returning_new_hot_cold,
2013 getHotColdHintForExisting(HotCold), CI->getType());
2014 break;
2015 case LibFunc_size_returning_new_aligned:
2017 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
2018 LibFunc_size_returning_new_aligned_hot_cold, HotColdVal, CI->getType());
2019 break;
2020 case LibFunc_size_returning_new_aligned_hot_cold:
2021 if (ShouldOptimizeExistingHotColdNew)
2023 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
2024 LibFunc_size_returning_new_aligned_hot_cold,
2025 getHotColdHintForExisting(HotCold), CI->getType());
2026 break;
2027 default:
2028 return nullptr;
2029 }
2030
2031 if (auto *NewCI = dyn_cast_or_null<Instruction>(NewCall))
2032 NewCI->copyMetadata(*CI);
2033
2034 return NewCall;
2035}
2036
2037//===----------------------------------------------------------------------===//
2038// Math Library Optimizations
2039//===----------------------------------------------------------------------===//
2040
2041/// Preserve the accuracy requirement of \p Old on the replacement \p New.
2042static void copyFPMath(const CallInst &Old, Value *New) {
2043 if (auto *NewI = dyn_cast<Instruction>(New))
2044 if (MDNode *MD = Old.getMetadata(LLVMContext::MD_fpmath))
2045 NewI->setMetadata(LLVMContext::MD_fpmath, MD);
2046}
2047
2048// Replace a libcall \p CI with a call to intrinsic \p IID
2050 Intrinsic::ID IID) {
2051 Value *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI);
2052 NewCall->takeName(CI);
2053 copyFPMath(*CI, NewCall);
2054 return copyFlags(*CI, NewCall);
2055}
2056
2058 Intrinsic::ID IID) {
2059 Value *NewCall = B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
2060 CI->getArgOperand(1), CI);
2061 NewCall->takeName(CI);
2062 copyFPMath(*CI, NewCall);
2063 return copyFlags(*CI, NewCall);
2064}
2065
2066/// Return a variant of Val with float type.
2067/// Currently this works in two cases: If Val is an FPExtension of a float
2068/// value to something bigger, simply return the operand.
2069/// If Val is a ConstantFP but can be converted to a float ConstantFP without
2070/// loss of precision do so.
2072 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
2073 Value *Op = Cast->getOperand(0);
2074 if (Op->getType()->isFloatTy())
2075 return Op;
2076 }
2077 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
2078 APFloat F = Const->getValueAPF();
2079 bool losesInfo;
2081 &losesInfo);
2082 if (!losesInfo)
2083 return ConstantFP::get(Const->getContext(), F);
2084 }
2085 return nullptr;
2086}
2087
2088/// Shrink double -> float functions.
2090 bool isBinary, const TargetLibraryInfo *TLI,
2091 bool isPrecise = false) {
2092 Function *CalleeFn = CI->getCalledFunction();
2093 if (!CI->getType()->isDoubleTy() || !CalleeFn)
2094 return nullptr;
2095
2096 // If not all the uses of the function are converted to float, then bail out.
2097 // This matters if the precision of the result is more important than the
2098 // precision of the arguments.
2099 if (isPrecise)
2100 for (User *U : CI->users()) {
2102 if (!Cast || !Cast->getType()->isFloatTy())
2103 return nullptr;
2104 }
2105
2106 // If this is something like 'g((double) float)', convert to 'gf(float)'.
2107 Value *V[2];
2109 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
2110 if (!V[0] || (isBinary && !V[1]))
2111 return nullptr;
2112
2113 // If call isn't an intrinsic, check that it isn't within a function with the
2114 // same name as the float version of this call, otherwise the result is an
2115 // infinite loop. For example, from MinGW-w64:
2116 //
2117 // float expf(float val) { return (float) exp((double) val); }
2118 StringRef CalleeName = CalleeFn->getName();
2119 bool IsIntrinsic = CalleeFn->isIntrinsic();
2120 if (!IsIntrinsic) {
2121 StringRef CallerName = CI->getFunction()->getName();
2122 if (CallerName.ends_with('f') &&
2123 CallerName.size() == (CalleeName.size() + 1) &&
2124 CallerName.starts_with(CalleeName))
2125 return nullptr;
2126 }
2127
2128 // Propagate the math semantics from the current function to the new function.
2130 B.setFastMathFlags(CI->getFastMathFlags());
2131
2132 // g((double) float) -> (double) gf(float)
2133 Value *R;
2134 if (IsIntrinsic) {
2135 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
2136 R = isBinary ? B.CreateIntrinsic(IID, B.getFloatTy(), V)
2137 : B.CreateIntrinsic(IID, B.getFloatTy(), V[0]);
2138 } else {
2139 AttributeList CallsiteAttrs = CI->getAttributes();
2140 R = isBinary
2141 ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B,
2142 CallsiteAttrs)
2143 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CallsiteAttrs);
2144 }
2145 return B.CreateFPExt(R, B.getDoubleTy());
2146}
2147
2148/// Shrink double -> float for unary functions.
2150 const TargetLibraryInfo *TLI,
2151 bool isPrecise = false) {
2152 return optimizeDoubleFP(CI, B, false, TLI, isPrecise);
2153}
2154
2155/// Shrink double -> float for binary functions.
2157 const TargetLibraryInfo *TLI,
2158 bool isPrecise = false) {
2159 return optimizeDoubleFP(CI, B, true, TLI, isPrecise);
2160}
2161
2162/// Shrink double -> float for llvm.sincos.
2164 auto *RetTy = dyn_cast<StructType>(CI->getType());
2165 if (!RetTy || RetTy->getNumElements() != 2 ||
2166 !RetTy->getElementType(0)->getScalarType()->isDoubleTy())
2167 return nullptr;
2168
2170 if (!X)
2171 if (auto *Ext = dyn_cast<FPExtInst>(CI->getArgOperand(0)))
2172 if (Ext->getOperand(0)->getType()->getScalarType()->isFloatTy())
2173 X = Ext->getOperand(0);
2174 if (!X)
2175 return nullptr;
2176
2177 for (User *U : CI->users()) {
2178 auto *EV = dyn_cast<ExtractValueInst>(U);
2179 if (!EV)
2180 return nullptr;
2181 for (User *EVU : EV->users()) {
2182 auto *Cast = dyn_cast<FPTruncInst>(EVU);
2183 if (!Cast || !Cast->getType()->getScalarType()->isFloatTy())
2184 return nullptr;
2185 }
2186 }
2187
2189 B.setFastMathFlags(CI->getFastMathFlags());
2190
2191 Value *NewCall = B.CreateIntrinsic(Intrinsic::sincos, X->getType(), X);
2192 cast<Instruction>(NewCall)->setMetadata(
2193 LLVMContext::MD_fpmath, CI->getMetadata(LLVMContext::MD_fpmath));
2194 Value *Res = PoisonValue::get(RetTy);
2195 for (unsigned I = 0; I != 2; ++I) {
2196 Value *Ext = B.CreateFPExt(B.CreateExtractValue(NewCall, I),
2197 RetTy->getElementType(I));
2198 Res = B.CreateInsertValue(Res, Ext, I);
2199 }
2200 return Res;
2201}
2202
2203// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
2204Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
2205 Value *Real, *Imag;
2206
2207 if (CI->arg_size() == 1) {
2208
2209 if (!CI->isFast())
2210 return nullptr;
2211
2212 Value *Op = CI->getArgOperand(0);
2213 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
2214
2215 Real = B.CreateExtractValue(Op, 0, "real");
2216 Imag = B.CreateExtractValue(Op, 1, "imag");
2217
2218 } else {
2219 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
2220
2221 Real = CI->getArgOperand(0);
2222 Imag = CI->getArgOperand(1);
2223
2224 // if real or imaginary part is zero, simplify to abs(cimag(z))
2225 // or abs(creal(z))
2226 Value *AbsOp = nullptr;
2227 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) {
2228 if (ConstReal->isZero())
2229 AbsOp = Imag;
2230
2231 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) {
2232 if (ConstImag->isZero())
2233 AbsOp = Real;
2234 }
2235
2236 if (AbsOp)
2237 return copyFlags(*CI, B.CreateFAbs(AbsOp, CI, "cabs"));
2238
2239 if (!CI->isFast())
2240 return nullptr;
2241 }
2242
2243 // Propagate fast-math flags from the existing call to new instructions.
2244 Value *RealReal = B.CreateFMulFMF(Real, Real, CI);
2245 Value *ImagImag = B.CreateFMulFMF(Imag, Imag, CI);
2246 return copyFlags(
2247 *CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt,
2248 B.CreateFAddFMF(RealReal, ImagImag, CI), CI,
2249 "cabs"));
2250}
2251
2252// Return a properly extended integer (DstWidth bits wide) if the operation is
2253// an itofp.
2254static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
2255 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
2256 Value *Op = cast<Instruction>(I2F)->getOperand(0);
2257 // Make sure that the exponent fits inside an "int" of size DstWidth,
2258 // thus avoiding any range issues that FP has not.
2259 unsigned BitWidth = Op->getType()->getScalarSizeInBits();
2260 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) {
2261 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth);
2262 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy)
2263 : B.CreateZExt(Op, IntTy);
2264 }
2265 }
2266
2267 return nullptr;
2268}
2269
2270/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
2271/// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
2272/// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
2273Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
2274 Module *M = Pow->getModule();
2275 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2276 Type *Ty = Pow->getType();
2277 bool Ignored;
2278
2279 // Evaluate special cases related to a nested function as the base.
2280
2281 // pow(exp(x), y) -> exp(x * y)
2282 // pow(exp2(x), y) -> exp2(x * y)
2283 // If exp{,2}() is used only once, it is better to fold two transcendental
2284 // math functions into one. If used again, exp{,2}() would still have to be
2285 // called with the original argument, then keep both original transcendental
2286 // functions. However, this transformation is only safe with fully relaxed
2287 // math semantics, since, besides rounding differences, it changes overflow
2288 // and underflow behavior quite dramatically. For example:
2289 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
2290 // Whereas:
2291 // exp(1000 * 0.001) = exp(1)
2292 // TODO: Loosen the requirement for fully relaxed math semantics.
2293 // TODO: Handle exp10() when more targets have it available.
2294 CallInst *BaseFn = dyn_cast<CallInst>(Base);
2295 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
2296 Function *CalleeFn = BaseFn->getCalledFunction();
2297 LibFunc LibFn =
2298 CalleeFn ? TLI->getLibFunc(CalleeFn->getName()) : NotLibFunc;
2299 if (isLibFuncEmittable(M, TLI, LibFn)) {
2300 StringRef ExpName;
2302 Value *ExpFn;
2303 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
2304
2305 switch (LibFn) {
2306 default:
2307 return nullptr;
2308 case LibFunc_expf:
2309 case LibFunc_exp:
2310 case LibFunc_expl:
2311 ExpName = TLI->getName(LibFunc_exp);
2312 ID = Intrinsic::exp;
2313 LibFnFloat = LibFunc_expf;
2314 LibFnDouble = LibFunc_exp;
2315 LibFnLongDouble = LibFunc_expl;
2316 break;
2317 case LibFunc_exp2f:
2318 case LibFunc_exp2:
2319 case LibFunc_exp2l:
2320 ExpName = TLI->getName(LibFunc_exp2);
2321 ID = Intrinsic::exp2;
2322 LibFnFloat = LibFunc_exp2f;
2323 LibFnDouble = LibFunc_exp2;
2324 LibFnLongDouble = LibFunc_exp2l;
2325 break;
2326 }
2327
2328 // Create new exp{,2}() with the product as its argument.
2329 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
2330 ExpFn = BaseFn->doesNotAccessMemory()
2331 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName)
2332 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
2333 LibFnLongDouble, B,
2334 BaseFn->getAttributes());
2335
2336 // Since the new exp{,2}() is different from the original one, dead code
2337 // elimination cannot be trusted to remove it, since it may have side
2338 // effects (e.g., errno). When the only consumer for the original
2339 // exp{,2}() is pow(), then it has to be explicitly erased.
2340 substituteInParent(BaseFn, ExpFn);
2341 return ExpFn;
2342 }
2343 }
2344
2345 // Evaluate special cases related to a constant base.
2346
2347 const APFloat *BaseF;
2348 if (!match(Base, m_APFloat(BaseF)))
2349 return nullptr;
2350
2351 AttributeList NoAttrs; // Attributes are only meaningful on the original call
2352
2353 const bool UseIntrinsic = Pow->doesNotAccessMemory();
2354
2355 // pow(2.0, itofp(x)) -> ldexp(1.0, x)
2356 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) &&
2357 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
2358 (UseIntrinsic ||
2359 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2360
2361 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can
2362 // just directly use the original integer type.
2363 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) {
2364 Constant *One = ConstantFP::get(Ty, 1.0);
2365
2366 if (UseIntrinsic) {
2367 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp,
2368 {Ty, ExpoI->getType()},
2369 {One, ExpoI}, Pow, "exp2"));
2370 }
2371
2373 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2374 LibFunc_ldexpl, B, NoAttrs));
2375 }
2376 }
2377
2378 // pow(2.0 ** n, x) -> exp2(n * x)
2379 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
2380 APFloat BaseR = APFloat(1.0);
2381 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
2382 BaseR = BaseR / *BaseF;
2383 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
2384 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
2385 APSInt NI(64, false);
2386 if ((IsInteger || IsReciprocal) &&
2387 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
2388 APFloat::opOK &&
2389 NI > 1 && NI.isPowerOf2()) {
2390 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
2391 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
2392 if (Pow->doesNotAccessMemory())
2393 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2394 nullptr, "exp2"));
2395 else
2396 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2397 LibFunc_exp2f,
2398 LibFunc_exp2l, B, NoAttrs));
2399 }
2400 }
2401
2402 // pow(10.0, x) -> exp10(x)
2403 if (BaseF->isExactlyValue(10.0) &&
2404 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) {
2405
2406 if (Pow->doesNotAccessMemory()) {
2407 return B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10", {},
2408 [Pow](CallInst *CI) { CI->copyIRFlags(Pow); });
2409 }
2410
2411 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
2412 LibFunc_exp10f, LibFunc_exp10l,
2413 B, NoAttrs));
2414 }
2415
2416 // pow(x, y) -> exp2(log2(x) * y)
2417 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
2418 !BaseF->isNegative()) {
2419 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
2420 // Luckily optimizePow has already handled the x == 1 case.
2421 assert(!match(Base, m_FPOne()) &&
2422 "pow(1.0, y) should have been simplified earlier!");
2423
2424 Value *Log = nullptr;
2425 if (Ty->isFloatTy())
2426 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
2427 else if (Ty->isDoubleTy())
2428 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
2429
2430 if (Log) {
2431 Value *FMul = B.CreateFMul(Log, Expo, "mul");
2432 if (Pow->doesNotAccessMemory())
2433 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2434 nullptr, "exp2"));
2435 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f,
2436 LibFunc_exp2l))
2437 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2438 LibFunc_exp2f,
2439 LibFunc_exp2l, B, NoAttrs));
2440 }
2441 }
2442
2443 return nullptr;
2444}
2445
2446static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
2447 Module *M, IRBuilderBase &B,
2448 const TargetLibraryInfo *TLI) {
2449 // If errno is never set, then use the intrinsic for sqrt().
2450 if (NoErrno)
2451 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt");
2452
2453 // Otherwise, use the libcall for sqrt().
2454 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
2455 LibFunc_sqrtl))
2456 // TODO: We also should check that the target can in fact lower the sqrt()
2457 // libcall. We currently have no way to ask this question, so we ask if
2458 // the target has a sqrt() libcall, which is not exactly the same.
2459 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
2460 LibFunc_sqrtl, B, Attrs);
2461
2462 return nullptr;
2463}
2464
2465/// Use square root in place of pow(x, +/-0.5).
2466Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
2467 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2468 Module *Mod = Pow->getModule();
2469 Type *Ty = Pow->getType();
2470
2471 const APFloat *ExpoF;
2472 if (!match(Expo, m_APFloat(ExpoF)) ||
2473 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
2474 return nullptr;
2475
2476 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
2477 // so that requires fast-math-flags (afn or reassoc).
2478 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
2479 return nullptr;
2480
2481 // If we have a pow() library call (accesses memory) and we can't guarantee
2482 // that the base is not an infinity, give up:
2483 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
2484 // errno), but sqrt(-Inf) is required by various standards to set errno.
2485 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
2487 Base, SimplifyQuery(DL, TLI, DT, AC, Pow, true, true, DC)))
2488 return nullptr;
2489
2490 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B,
2491 TLI);
2492 if (!Sqrt)
2493 return nullptr;
2494
2495 // Handle signed zero base by expanding to fabs(sqrt(x)).
2496 if (!Pow->hasNoSignedZeros())
2497 Sqrt = B.CreateFAbs(Sqrt, nullptr, "abs");
2498
2499 Sqrt = copyFlags(*Pow, Sqrt);
2500
2501 // Handle non finite base by expanding to
2502 // (x == -infinity ? +infinity : sqrt(x)).
2503 if (!Pow->hasNoInfs()) {
2504 Value *PosInf = ConstantFP::getInfinity(Ty),
2505 *NegInf = ConstantFP::getInfinity(Ty, true);
2506 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
2507 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
2508 // We assume that the case where x == -infinity is unlikely, so we assign
2509 // unlikely branch weights to that arm of the select.
2511 if (auto *SqrtSI = dyn_cast<SelectInst>(Sqrt))
2513 *SqrtSI,
2515 /*IsExpected=*/false);
2516 }
2517 }
2518
2519 // If the exponent is negative, then get the reciprocal.
2520 if (ExpoF->isNegative())
2521 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
2522
2523 return Sqrt;
2524}
2525
2527 IRBuilderBase &B) {
2528 Value *Args[] = {Base, Expo};
2529 Type *Types[] = {Base->getType(), Expo->getType()};
2530 return B.CreateIntrinsic(Intrinsic::powi, Types, Args);
2531}
2532
2533Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
2534 Value *Base = Pow->getArgOperand(0);
2535 Value *Expo = Pow->getArgOperand(1);
2536 Function *Callee = Pow->getCalledFunction();
2537 StringRef Name = Callee->getName();
2538 Type *Ty = Pow->getType();
2539 Module *M = Pow->getModule();
2540 bool AllowApprox = Pow->hasApproxFunc();
2541 bool Ignored;
2542
2543 // Propagate the math semantics from the call to any created instructions.
2544 IRBuilderBase::FastMathFlagGuard Guard(B);
2545 B.setFastMathFlags(Pow->getFastMathFlags());
2546 // Evaluate special cases related to the base.
2547
2548 // pow(1.0, x) -> 1.0
2549 if (match(Base, m_FPOne()))
2550 return Base;
2551
2552 if (Value *Exp = replacePowWithExp(Pow, B))
2553 return Exp;
2554
2555 // Evaluate special cases related to the exponent.
2556
2557 // pow(x, -1.0) -> 1.0 / x
2558 if (match(Expo, m_SpecificFP(-1.0)))
2559 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
2560
2561 // pow(x, +/-0.0) -> 1.0
2562 if (match(Expo, m_AnyZeroFP()))
2563 return ConstantFP::get(Ty, 1.0);
2564
2565 // pow(x, 1.0) -> x
2566 if (match(Expo, m_FPOne()))
2567 return Base;
2568
2569 // pow(x, 2.0) -> x * x
2570 if (match(Expo, m_SpecificFP(2.0)) && Pow->doesNotAccessMemory())
2571 return B.CreateFMul(Base, Base, "square");
2572
2573 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
2574 return Sqrt;
2575
2576 // If we can approximate pow:
2577 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction
2578 // pow(x, n) -> powi(x, n) if n is a constant signed integer value
2579 const APFloat *ExpoF;
2580 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
2581 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
2582 APFloat ExpoA(abs(*ExpoF));
2583 APFloat ExpoI(*ExpoF);
2584 Value *Sqrt = nullptr;
2585 if (!ExpoA.isInteger()) {
2586 APFloat Expo2 = ExpoA;
2587 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
2588 // is no floating point exception and the result is an integer, then
2589 // ExpoA == integer + 0.5
2590 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
2591 return nullptr;
2592
2593 if (!Expo2.isInteger())
2594 return nullptr;
2595
2596 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) !=
2598 return nullptr;
2599 if (!ExpoI.isInteger())
2600 return nullptr;
2601 ExpoF = &ExpoI;
2602
2603 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M,
2604 B, TLI);
2605 if (!Sqrt)
2606 return nullptr;
2607 }
2608
2609 // 0.5 fraction is now optionally handled.
2610 // Do pow -> powi for remaining integer exponent
2611 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
2612 if (ExpoF->isInteger() &&
2613 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
2614 APFloat::opOK) {
2615 Value *PowI = copyFlags(
2616 *Pow,
2618 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
2619 M, B));
2620
2621 if (PowI && Sqrt)
2622 return B.CreateFMul(PowI, Sqrt);
2623
2624 return PowI;
2625 }
2626 }
2627
2628 // powf(x, itofp(y)) -> powi(x, y)
2629 // The powi exponent must be a scalar integer, so a vector y is not usable.
2630 if (AllowApprox && !Expo->getType()->isVectorTy() &&
2631 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
2632 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
2633 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
2634 }
2635
2636 // Shrink pow() to powf() if the arguments are single precision,
2637 // unless the result is expected to be double precision.
2638 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
2639 hasFloatVersion(M, Name)) {
2640 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
2641 return Shrunk;
2642 }
2643
2644 return nullptr;
2645}
2646
2647Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
2648 Module *M = CI->getModule();
2650 StringRef Name = Callee->getName();
2651 Value *Ret = nullptr;
2652 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
2653 hasFloatVersion(M, Name))
2654 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2655
2656 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we
2657 // have the libcall, emit the libcall.
2658 //
2659 // TODO: In principle we should be able to just always use the intrinsic for
2660 // any doesNotAccessMemory callsite.
2661
2662 const bool UseIntrinsic = Callee->isIntrinsic();
2663 // Bail out for vectors because the code below only expects scalars.
2664 Type *Ty = CI->getType();
2665 if (!UseIntrinsic && Ty->isVectorTy())
2666 return Ret;
2667
2668 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize
2669 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize
2670 Value *Op = CI->getArgOperand(0);
2671 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
2672 (UseIntrinsic ||
2673 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2674 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) {
2675 Constant *One = ConstantFP::get(Ty, 1.0);
2676
2677 if (UseIntrinsic) {
2678 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp,
2679 {Ty, Exp->getType()},
2680 {One, Exp}, CI));
2681 }
2682
2683 IRBuilderBase::FastMathFlagGuard Guard(B);
2684 B.setFastMathFlags(CI->getFastMathFlags());
2685 return copyFlags(*CI, emitBinaryFloatFnCall(
2686 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2687 LibFunc_ldexpl, B, AttributeList()));
2688 }
2689 }
2690
2691 return Ret;
2692}
2693
2694Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B,
2695 Intrinsic::ID IID) {
2696 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
2697 // the intrinsics for improved optimization (for example, vectorization).
2698 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
2699 // From the C standard draft WG14/N1256:
2700 // "Ideally, fmax would be sensitive to the sign of zero, for example
2701 // fmax(-0.0, +0.0) would return +0; however, implementation in software
2702 // might be impractical."
2703 FastMathFlags FMF = CI->getFastMathFlags();
2704 FMF.setNoSignedZeros();
2705 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
2706 CI->getArgOperand(1), FMF));
2707}
2708
2709Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
2710 Function *LogFn = Log->getCalledFunction();
2711 StringRef LogNm = LogFn->getName();
2712 Intrinsic::ID LogID = LogFn->getIntrinsicID();
2713 Module *Mod = Log->getModule();
2714 Type *Ty = Log->getType();
2715
2716 if (UnsafeFPShrink && (LogFn->isIntrinsic() || hasFloatVersion(Mod, LogNm)))
2717 if (Value *Ret = optimizeUnaryDoubleFP(Log, B, TLI, true))
2718 return Ret;
2719
2720 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2721
2722 // This is only applicable to log(), log2(), log10().
2723 LogLb = TLI->getLibFunc(LogNm);
2724 if (LogLb != NotLibFunc) {
2725 switch (LogLb) {
2726 case LibFunc_logf:
2727 LogID = Intrinsic::log;
2728 ExpLb = LibFunc_expf;
2729 Exp2Lb = LibFunc_exp2f;
2730 Exp10Lb = LibFunc_exp10f;
2731 PowLb = LibFunc_powf;
2732 break;
2733 case LibFunc_log:
2734 LogID = Intrinsic::log;
2735 ExpLb = LibFunc_exp;
2736 Exp2Lb = LibFunc_exp2;
2737 Exp10Lb = LibFunc_exp10;
2738 PowLb = LibFunc_pow;
2739 break;
2740 case LibFunc_logl:
2741 LogID = Intrinsic::log;
2742 ExpLb = LibFunc_expl;
2743 Exp2Lb = LibFunc_exp2l;
2744 Exp10Lb = LibFunc_exp10l;
2745 PowLb = LibFunc_powl;
2746 break;
2747 case LibFunc_log2f:
2748 LogID = Intrinsic::log2;
2749 ExpLb = LibFunc_expf;
2750 Exp2Lb = LibFunc_exp2f;
2751 Exp10Lb = LibFunc_exp10f;
2752 PowLb = LibFunc_powf;
2753 break;
2754 case LibFunc_log2:
2755 LogID = Intrinsic::log2;
2756 ExpLb = LibFunc_exp;
2757 Exp2Lb = LibFunc_exp2;
2758 Exp10Lb = LibFunc_exp10;
2759 PowLb = LibFunc_pow;
2760 break;
2761 case LibFunc_log2l:
2762 LogID = Intrinsic::log2;
2763 ExpLb = LibFunc_expl;
2764 Exp2Lb = LibFunc_exp2l;
2765 Exp10Lb = LibFunc_exp10l;
2766 PowLb = LibFunc_powl;
2767 break;
2768 case LibFunc_log10f:
2769 LogID = Intrinsic::log10;
2770 ExpLb = LibFunc_expf;
2771 Exp2Lb = LibFunc_exp2f;
2772 Exp10Lb = LibFunc_exp10f;
2773 PowLb = LibFunc_powf;
2774 break;
2775 case LibFunc_log10:
2776 LogID = Intrinsic::log10;
2777 ExpLb = LibFunc_exp;
2778 Exp2Lb = LibFunc_exp2;
2779 Exp10Lb = LibFunc_exp10;
2780 PowLb = LibFunc_pow;
2781 break;
2782 case LibFunc_log10l:
2783 LogID = Intrinsic::log10;
2784 ExpLb = LibFunc_expl;
2785 Exp2Lb = LibFunc_exp2l;
2786 Exp10Lb = LibFunc_exp10l;
2787 PowLb = LibFunc_powl;
2788 break;
2789 default:
2790 return nullptr;
2791 }
2792
2793 // Convert libcall to intrinsic if the value is known > 0.
2794 bool IsKnownNoErrno = Log->hasNoNaNs() && Log->hasNoInfs();
2795 if (!IsKnownNoErrno) {
2796 SimplifyQuery SQ(DL, TLI, DT, AC, Log, true, true, DC);
2797 KnownFPClass Known = computeKnownFPClass(
2798 Log->getOperand(0),
2800 Function *F = Log->getParent()->getParent();
2801 const fltSemantics &FltSem = Ty->getScalarType()->getFltSemantics();
2802 IsKnownNoErrno =
2803 Known.cannotBeOrderedLessThanZero() &&
2804 Known.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
2805 }
2806 if (IsKnownNoErrno) {
2807 Value *NewLog = B.CreateUnaryIntrinsic(LogID, Log->getArgOperand(0), Log);
2808 if (auto *I = dyn_cast<Instruction>(NewLog)) {
2809 I->copyMetadata(*Log);
2810 return copyFlags(*Log, I);
2811 }
2812 return NewLog;
2813 }
2814 } else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2815 LogID == Intrinsic::log10) {
2816 if (Ty->getScalarType()->isFloatTy()) {
2817 ExpLb = LibFunc_expf;
2818 Exp2Lb = LibFunc_exp2f;
2819 Exp10Lb = LibFunc_exp10f;
2820 PowLb = LibFunc_powf;
2821 } else if (Ty->getScalarType()->isDoubleTy()) {
2822 ExpLb = LibFunc_exp;
2823 Exp2Lb = LibFunc_exp2;
2824 Exp10Lb = LibFunc_exp10;
2825 PowLb = LibFunc_pow;
2826 } else
2827 return nullptr;
2828 } else
2829 return nullptr;
2830
2831 // The earlier call must also be 'fast' in order to do these transforms.
2832 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2833 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2834 return nullptr;
2835
2836 IRBuilderBase::FastMathFlagGuard Guard(B);
2837 B.setFastMathFlags(FastMathFlags::getFast());
2838
2839 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2840 LibFunc ArgLb = TLI->getLibFunc(*Arg);
2841
2842 // log(pow(x,y)) -> y*log(x)
2843 AttributeList NoAttrs;
2844 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) {
2845 Value *LogX =
2846 Log->doesNotAccessMemory()
2847 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log")
2848 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs);
2849 Value *Y = Arg->getArgOperand(1);
2850 // Cast exponent to FP if integer.
2851 if (ArgID == Intrinsic::powi)
2852 Y = B.CreateSIToFP(Y, Ty, "cast");
2853 Value *MulY = B.CreateFMul(Y, LogX, "mul");
2854 // Since pow() may have side effects, e.g. errno,
2855 // dead code elimination may not be trusted to remove it.
2856 substituteInParent(Arg, MulY);
2857 return MulY;
2858 }
2859
2860 // log(exp{,2,10}(y)) -> y*log({e,2,10})
2861 // TODO: There is no exp10() intrinsic yet.
2862 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2863 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2864 Constant *Eul;
2865 if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2866 // FIXME: Add more precise value of e for long double.
2867 Eul = ConstantFP::get(Log->getType(), numbers::e);
2868 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2869 Eul = ConstantFP::get(Log->getType(), 2.0);
2870 else
2871 Eul = ConstantFP::get(Log->getType(), 10.0);
2872 Value *LogE = Log->doesNotAccessMemory()
2873 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log")
2874 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs);
2875 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2876 // Since exp() may have side effects, e.g. errno,
2877 // dead code elimination may not be trusted to remove it.
2878 substituteInParent(Arg, MulY);
2879 return MulY;
2880 }
2881
2882 return nullptr;
2883}
2884
2885// sqrt(exp(X)) -> exp(X * 0.5)
2886Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) {
2887 if (!CI->hasAllowReassoc())
2888 return nullptr;
2889
2890 Function *SqrtFn = CI->getCalledFunction();
2891 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0));
2892 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse())
2893 return nullptr;
2894 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2895 LibFunc ArgLb = TLI->getLibFunc(*Arg);
2896
2897 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb;
2898
2899 SqrtLb = TLI->getLibFunc(SqrtFn->getName());
2900 if (SqrtLb != NotLibFunc)
2901 switch (SqrtLb) {
2902 case LibFunc_sqrtf:
2903 ExpLb = LibFunc_expf;
2904 Exp2Lb = LibFunc_exp2f;
2905 Exp10Lb = LibFunc_exp10f;
2906 break;
2907 case LibFunc_sqrt:
2908 ExpLb = LibFunc_exp;
2909 Exp2Lb = LibFunc_exp2;
2910 Exp10Lb = LibFunc_exp10;
2911 break;
2912 case LibFunc_sqrtl:
2913 ExpLb = LibFunc_expl;
2914 Exp2Lb = LibFunc_exp2l;
2915 Exp10Lb = LibFunc_exp10l;
2916 break;
2917 default:
2918 return nullptr;
2919 }
2920 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) {
2921 if (CI->getType()->getScalarType()->isFloatTy()) {
2922 ExpLb = LibFunc_expf;
2923 Exp2Lb = LibFunc_exp2f;
2924 Exp10Lb = LibFunc_exp10f;
2925 } else if (CI->getType()->getScalarType()->isDoubleTy()) {
2926 ExpLb = LibFunc_exp;
2927 Exp2Lb = LibFunc_exp2;
2928 Exp10Lb = LibFunc_exp10;
2929 } else
2930 return nullptr;
2931 } else
2932 return nullptr;
2933
2934 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb &&
2935 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2)
2936 return nullptr;
2937
2938 IRBuilderBase::InsertPointGuard Guard(B);
2939 B.SetInsertPoint(Arg);
2940 auto *ExpOperand = Arg->getOperand(0);
2941 auto *FMul =
2942 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5),
2943 CI, "merged.sqrt");
2944
2945 Arg->setOperand(0, FMul);
2946 return Arg;
2947}
2948
2949Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2950 Module *M = CI->getModule();
2952 Value *Ret = nullptr;
2953 // TODO: Once we have a way (other than checking for the existince of the
2954 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2955 // condition below.
2956 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2957 (Callee->getName() == "sqrt" ||
2958 Callee->getIntrinsicID() == Intrinsic::sqrt))
2959 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2960
2961 if (Value *Opt = mergeSqrtToExp(CI, B))
2962 return Opt;
2963
2964 if (!CI->isFast())
2965 return Ret;
2966
2968 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2969 return Ret;
2970
2971 // We're looking for a repeated factor in a multiplication tree,
2972 // so we can do this fold: sqrt(x * x) -> fabs(x);
2973 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2974 Value *Op0 = I->getOperand(0);
2975 Value *Op1 = I->getOperand(1);
2976 Value *RepeatOp = nullptr;
2977 Value *OtherOp = nullptr;
2978 if (Op0 == Op1) {
2979 // Simple match: the operands of the multiply are identical.
2980 RepeatOp = Op0;
2981 } else {
2982 // Look for a more complicated pattern: one of the operands is itself
2983 // a multiply, so search for a common factor in that multiply.
2984 // Note: We don't bother looking any deeper than this first level or for
2985 // variations of this pattern because instcombine's visitFMUL and/or the
2986 // reassociation pass should give us this form.
2987 Value *MulOp;
2988 if (match(Op0, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2989 cast<Instruction>(Op0)->isFast()) {
2990 // Pattern: sqrt((x * x) * z)
2991 RepeatOp = MulOp;
2992 OtherOp = Op1;
2993 } else if (match(Op1, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2994 cast<Instruction>(Op1)->isFast()) {
2995 // Pattern: sqrt(z * (x * x))
2996 RepeatOp = MulOp;
2997 OtherOp = Op0;
2998 }
2999 }
3000 if (!RepeatOp)
3001 return Ret;
3002
3003 // Fast math flags for any created instructions should match the sqrt
3004 // and multiply.
3005
3006 // If we found a repeated factor, hoist it out of the square root and
3007 // replace it with the fabs of that factor.
3008 Value *FabsCall = B.CreateFAbs(RepeatOp, I, "fabs");
3009 if (OtherOp) {
3010 // If we found a non-repeated factor, we still need to get its square
3011 // root. We then multiply that by the value that was simplified out
3012 // of the square root calculation.
3013 Value *SqrtCall =
3014 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, I, "sqrt");
3015 return copyFlags(*CI, B.CreateFMulFMF(FabsCall, SqrtCall, I));
3016 }
3017 return copyFlags(*CI, FabsCall);
3018}
3019
3020Value *LibCallSimplifier::optimizeFMod(CallInst *CI, IRBuilderBase &B) {
3021
3022 // fmod(x,y) sets errno if y == 0 or x == +/-inf. frem does not set errno,
3023 // so the fold is valid only when we can prove fmod wouldn't either.
3024 bool IsNoErrno = CI->hasNoNaNs();
3025 if (!IsNoErrno) {
3026 SimplifyQuery SQ(DL, TLI, DT, AC, CI, true, true, DC);
3027 KnownFPClass Known0 = computeKnownFPClass(CI->getOperand(0), fcInf, SQ);
3028 if (Known0.isKnownNeverInfinity()) {
3029 KnownFPClass Known1 =
3031 Function *F = CI->getParent()->getParent();
3032 const fltSemantics &FltSem =
3034 IsNoErrno = Known1.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
3035 }
3036 }
3037
3038 if (IsNoErrno)
3039 return B.CreateFRemFMF(CI->getOperand(0), CI->getOperand(1), CI);
3040 return nullptr;
3041}
3042
3043Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI,
3044 IRBuilderBase &B) {
3045 Module *M = CI->getModule();
3047 Value *Ret = nullptr;
3048 StringRef Name = Callee->getName();
3049 if (UnsafeFPShrink &&
3050 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" ||
3051 Name == "asinh") &&
3052 hasFloatVersion(M, Name))
3053 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
3054
3055 Value *Op1 = CI->getArgOperand(0);
3056 auto *OpC = dyn_cast<CallInst>(Op1);
3057 if (!OpC)
3058 return Ret;
3059
3060 // Both calls must be 'fast' in order to remove them.
3061 if (!CI->isFast() || !OpC->isFast())
3062 return Ret;
3063
3064 // tan(atan(x)) -> x
3065 // atanh(tanh(x)) -> x
3066 // sinh(asinh(x)) -> x
3067 // asinh(sinh(x)) -> x
3068 // cosh(acosh(x)) -> x
3069 Function *F = OpC->getCalledFunction();
3070 LibFunc Func = F ? TLI->getLibFunc(F->getName()) : NotLibFunc;
3071 if (isLibFuncEmittable(M, TLI, Func)) {
3072 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName())
3073 .Case("tan", LibFunc_atan)
3074 .Case("atanh", LibFunc_tanh)
3075 .Case("sinh", LibFunc_asinh)
3076 .Case("cosh", LibFunc_acosh)
3077 .Case("tanf", LibFunc_atanf)
3078 .Case("atanhf", LibFunc_tanhf)
3079 .Case("sinhf", LibFunc_asinhf)
3080 .Case("coshf", LibFunc_acoshf)
3081 .Case("tanl", LibFunc_atanl)
3082 .Case("atanhl", LibFunc_tanhl)
3083 .Case("sinhl", LibFunc_asinhl)
3084 .Case("coshl", LibFunc_acoshl)
3085 .Case("asinh", LibFunc_sinh)
3086 .Case("asinhf", LibFunc_sinhf)
3087 .Case("asinhl", LibFunc_sinhl)
3088 .Default(NotLibFunc); // Used as error value
3089 if (Func == inverseFunc)
3090 Ret = OpC->getArgOperand(0);
3091 }
3092 return Ret;
3093}
3094
3095static bool isTrigLibCall(CallInst *CI) {
3096 // We can only hope to do anything useful if we can ignore things like errno
3097 // and floating-point exceptions.
3098 // We already checked the prototype.
3099 return CI->doesNotThrow() && CI->doesNotAccessMemory();
3100}
3101
3102static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
3103 bool UseFloat, Value *&Sin, Value *&Cos,
3104 Value *&SinCos, const TargetLibraryInfo *TLI) {
3105 Module *M = OrigCallee->getParent();
3106 Type *ArgTy = Arg->getType();
3107 Type *ResTy;
3108 StringRef Name;
3109
3110 Triple T(OrigCallee->getParent()->getTargetTriple());
3111 if (UseFloat) {
3112 Name = "__sincospif_stret";
3113
3114 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
3115 // x86_64 can't use {float, float} since that would be returned in both
3116 // xmm0 and xmm1, which isn't what a real struct would do.
3117 ResTy = T.getArch() == Triple::x86_64
3118 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
3119 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
3120 } else {
3121 Name = "__sincospi_stret";
3122 ResTy = StructType::get(ArgTy, ArgTy);
3123 }
3124
3125 if (!isLibFuncEmittable(M, TLI, Name))
3126 return false;
3127 LibFunc TheLibFunc = TLI->getLibFunc(Name);
3129 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
3130
3131 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
3132 // If the argument is an instruction, it must dominate all uses so put our
3133 // sincos call there.
3134 B.SetInsertPoint(++ArgInst->getIterator());
3135 } else {
3136 // Otherwise (e.g. for a constant) the beginning of the function is as
3137 // good a place as any.
3138 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
3139 B.SetInsertPoint(EntryBB.begin());
3140 }
3141
3142 SinCos = B.CreateCall(Callee, Arg, "sincospi");
3143
3144 if (SinCos->getType()->isStructTy()) {
3145 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
3146 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
3147 } else {
3148 Sin = B.CreateExtractElement(SinCos, uint64_t{0}, "sinpi");
3149 Cos = B.CreateExtractElement(SinCos, uint64_t{1}, "cospi");
3150 }
3151
3152 return true;
3153}
3154
3155/// Flushing a denormal to +0.0 breaks f(-x) = -f(x) for odd f.
3159 return Mode.inputsMayBePositiveZero() || Mode.outputsMayBePositiveZero();
3160}
3161
3162static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven,
3163 IRBuilderBase &B) {
3164 Value *X;
3165 Value *Src = CI->getArgOperand(0);
3166
3167 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3169 (IsEven || !mayFlushDenormalsToPositiveZero(CI))) {
3170 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3171 auto *CallInst = copyFlags(*CI, Call);
3172 if (IsEven) {
3173 // Even function: f(-x) = f(x)
3174 return CallInst;
3175 }
3176 // Odd function: f(-x) = -f(x)
3177 return B.CreateFNegFMF(CallInst, CI);
3178 }
3179
3180 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x)
3181 if (IsEven && (match(Src, m_FAbs(m_Value(X))) ||
3182 match(Src, m_CopySign(m_Value(X), m_Value())))) {
3183 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3184 return copyFlags(*CI, Call);
3185 }
3186
3187 return nullptr;
3188}
3189
3190Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func,
3191 IRBuilderBase &B) {
3192 switch (Func) {
3193 case LibFunc_cos:
3194 case LibFunc_cosf:
3195 case LibFunc_cosl:
3196
3197 case LibFunc_cosh:
3198 case LibFunc_coshf:
3199 case LibFunc_coshl:
3200 return optimizeSymmetricCall(CI, /*IsEven*/ true, B);
3201
3202 case LibFunc_cbrt:
3203 case LibFunc_cbrtf:
3204 case LibFunc_cbrtl:
3205
3206 case LibFunc_sin:
3207 case LibFunc_sinf:
3208 case LibFunc_sinl:
3209
3210 case LibFunc_sinh:
3211 case LibFunc_sinhf:
3212 case LibFunc_sinhl:
3213
3214 case LibFunc_asin:
3215 case LibFunc_asinf:
3216 case LibFunc_asinl:
3217
3218 case LibFunc_asinh:
3219 case LibFunc_asinhf:
3220 case LibFunc_asinhl:
3221
3222 case LibFunc_tan:
3223 case LibFunc_tanf:
3224 case LibFunc_tanl:
3225
3226 case LibFunc_tanh:
3227 case LibFunc_tanhf:
3228 case LibFunc_tanhl:
3229
3230 case LibFunc_atan:
3231 case LibFunc_atanf:
3232 case LibFunc_atanl:
3233
3234 case LibFunc_erf:
3235 case LibFunc_erff:
3236 case LibFunc_erfl:
3237 return optimizeSymmetricCall(CI, /*IsEven*/ false, B);
3238
3239 default:
3240 return nullptr;
3241 }
3242}
3243
3244Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) {
3245 // Make sure the prototype is as expected, otherwise the rest of the
3246 // function is probably invalid and likely to abort.
3247 if (!isTrigLibCall(CI))
3248 return nullptr;
3249
3250 Value *Arg = CI->getArgOperand(0);
3251 if (isa<ConstantData>(Arg))
3252 return nullptr;
3253
3256 SmallVector<CallInst *, 1> SinCosCalls;
3257
3258 bool IsFloat = Arg->getType()->isFloatTy();
3259
3260 // Look for all compatible sinpi, cospi and sincospi calls with the same
3261 // argument. If there are enough (in some sense) we can make the
3262 // substitution.
3263 Function *F = CI->getFunction();
3264 for (User *U : Arg->users())
3265 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
3266
3267 // It's only worthwhile if both sinpi and cospi are actually used.
3268 if (SinCalls.empty() || CosCalls.empty())
3269 return nullptr;
3270
3271 Value *Sin, *Cos, *SinCos;
3272 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
3273 SinCos, TLI))
3274 return nullptr;
3275
3276 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
3277 Value *Res) {
3278 for (CallInst *C : Calls)
3279 replaceAllUsesWith(C, Res);
3280 };
3281
3282 replaceTrigInsts(SinCalls, Sin);
3283 replaceTrigInsts(CosCalls, Cos);
3284 replaceTrigInsts(SinCosCalls, SinCos);
3285
3286 return IsSin ? Sin : Cos;
3287}
3288
3289void LibCallSimplifier::classifyArgUse(
3290 Value *Val, Function *F, bool IsFloat,
3293 SmallVectorImpl<CallInst *> &SinCosCalls) {
3294 auto *CI = dyn_cast<CallInst>(Val);
3295 if (!CI || CI->use_empty())
3296 return;
3297
3298 // Don't consider calls in other functions.
3299 if (CI->getFunction() != F)
3300 return;
3301
3302 Module *M = CI->getModule();
3304 LibFunc Func = Callee ? TLI->getLibFunc(*Callee) : NotLibFunc;
3305 if (!isLibFuncEmittable(M, TLI, Func) || !isTrigLibCall(CI))
3306 return;
3307
3308 if (IsFloat) {
3309 if (Func == LibFunc_sinpif)
3310 SinCalls.push_back(CI);
3311 else if (Func == LibFunc_cospif)
3312 CosCalls.push_back(CI);
3313 else if (Func == LibFunc_sincospif_stret)
3314 SinCosCalls.push_back(CI);
3315 } else {
3316 if (Func == LibFunc_sinpi)
3317 SinCalls.push_back(CI);
3318 else if (Func == LibFunc_cospi)
3319 CosCalls.push_back(CI);
3320 else if (Func == LibFunc_sincospi_stret)
3321 SinCosCalls.push_back(CI);
3322 }
3323}
3324
3325/// Constant folds remquo
3326Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) {
3327 const APFloat *X, *Y;
3328 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3329 !match(CI->getArgOperand(1), m_APFloat(Y)))
3330 return nullptr;
3331
3332 APFloat::opStatus Status;
3333 APFloat Quot = *X;
3334 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven);
3335 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3336 return nullptr;
3337 APFloat Rem = *X;
3338 if (Rem.remainder(*Y) != APFloat::opOK)
3339 return nullptr;
3340
3341 // TODO: We can only keep at least the three of the last bits of x/y
3342 unsigned IntBW = TLI->getIntSize();
3343 APSInt QuotInt(IntBW, /*isUnsigned=*/false);
3344 bool IsExact;
3345 Status =
3346 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact);
3347 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3348 return nullptr;
3349
3350 B.CreateAlignedStore(
3351 ConstantInt::getSigned(B.getIntNTy(IntBW), QuotInt.getExtValue()),
3352 CI->getArgOperand(2), CI->getParamAlign(2));
3353 return ConstantFP::get(CI->getType(), Rem);
3354}
3355
3356/// Constant folds fdim
3357Value *LibCallSimplifier::optimizeFdim(CallInst *CI, IRBuilderBase &B) {
3358 // Cannot perform the fold unless the call has attribute memory(none)
3359 if (!CI->doesNotAccessMemory())
3360 return nullptr;
3361
3362 // TODO : Handle undef values
3363 // Propagate poison if any
3364 if (isa<PoisonValue>(CI->getArgOperand(0)))
3365 return CI->getArgOperand(0);
3366 if (isa<PoisonValue>(CI->getArgOperand(1)))
3367 return CI->getArgOperand(1);
3368
3369 const APFloat *X, *Y;
3370 // Check if both values are constants
3371 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3372 !match(CI->getArgOperand(1), m_APFloat(Y)))
3373 return nullptr;
3374
3375 // C99 fdim(x, y) = (x > y) ? x - y : +0.
3376 if (X->compare(*Y) != APFloat::cmpGreaterThan && !X->isNaN() && !Y->isNaN())
3377 return ConstantFP::getZero(CI->getType());
3378 APFloat Difference = *X;
3380 return ConstantFP::get(CI->getType(), Difference);
3381}
3382
3383//===----------------------------------------------------------------------===//
3384// Integer Library Call Optimizations
3385//===----------------------------------------------------------------------===//
3386
3387Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
3388 // All variants of ffs return int which need not be 32 bits wide.
3389 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0
3390 Type *RetType = CI->getType();
3391 Value *Op = CI->getArgOperand(0);
3392 Type *ArgType = Op->getType();
3393 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()},
3394 nullptr, "cttz");
3395 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
3396 V = B.CreateIntCast(V, RetType, false);
3397
3398 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
3399 Value *S = B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0));
3401 return S;
3402 if (auto *SI = dyn_cast<SelectInst>(S))
3405 /*IsExpected=*/false);
3406 return S;
3407}
3408
3409Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
3410 // All variants of fls return int which need not be 32 bits wide.
3411 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false))
3412 Value *Op = CI->getArgOperand(0);
3413 Type *ArgType = Op->getType();
3414 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()},
3415 nullptr, "ctlz");
3416 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
3417 V);
3418 return B.CreateIntCast(V, CI->getType(), false);
3419}
3420
3421Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
3422 // abs(x) -> x <s 0 ? -x : x
3423 // The negation has 'nsw' because abs of INT_MIN is undefined.
3424 Value *X = CI->getArgOperand(0);
3425 Value *IsNeg = B.CreateIsNeg(X);
3426 Value *NegX = B.CreateNSWNeg(X, "neg");
3427 return B.CreateSelect(IsNeg, NegX, X);
3428}
3429
3430Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
3431 // isdigit(c) -> (c-'0') <u 10
3432 Value *Op = CI->getArgOperand(0);
3433 Type *ArgType = Op->getType();
3434 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp");
3435 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit");
3436 return B.CreateZExt(Op, CI->getType());
3437}
3438
3439Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
3440 // isascii(c) -> c <u 128
3441 Value *Op = CI->getArgOperand(0);
3442 Type *ArgType = Op->getType();
3443 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii");
3444 return B.CreateZExt(Op, CI->getType());
3445}
3446
3447Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
3448 // toascii(c) -> c & 0x7f
3449 return B.CreateAnd(CI->getArgOperand(0),
3450 ConstantInt::get(CI->getType(), 0x7F));
3451}
3452
3453// Fold calls to atoi, atol, and atoll.
3454Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
3455 StringRef Str;
3456 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3457 return nullptr;
3458
3459 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B);
3460}
3461
3462// Fold calls to strtol, strtoll, strtoul, and strtoull.
3463Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B,
3464 bool AsSigned) {
3465 Value *EndPtr = CI->getArgOperand(1);
3466 if (isa<ConstantPointerNull>(EndPtr)) {
3467 // With a null EndPtr, this function won't capture the main argument.
3468 // It would be readonly too, except that it still may write to errno.
3471 EndPtr = nullptr;
3472 } else if (!isKnownNonZero(EndPtr, DL))
3473 return nullptr;
3474
3475 StringRef Str;
3476 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3477 return nullptr;
3478
3479 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
3480 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B);
3481 }
3482
3483 return nullptr;
3484}
3485
3486//===----------------------------------------------------------------------===//
3487// Formatting and IO Library Call Optimizations
3488//===----------------------------------------------------------------------===//
3489
3490static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
3491
3492Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
3493 int StreamArg) {
3495 // Error reporting calls should be cold, mark them as such.
3496 // This applies even to non-builtin calls: it is only a hint and applies to
3497 // functions that the frontend might not understand as builtins.
3498
3499 // This heuristic was suggested in:
3500 // Improving Static Branch Prediction in a Compiler
3501 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
3502 // Proceedings of PACT'98, Oct. 1998, IEEE
3503 if (!CI->hasFnAttr(Attribute::Cold) &&
3504 isReportingError(Callee, CI, StreamArg)) {
3505 CI->addFnAttr(Attribute::Cold);
3506 }
3507
3508 return nullptr;
3509}
3510
3511static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
3512 if (!Callee || !Callee->isDeclaration())
3513 return false;
3514
3515 if (StreamArg < 0)
3516 return true;
3517
3518 // These functions might be considered cold, but only if their stream
3519 // argument is stderr.
3520
3521 if (StreamArg >= (int)CI->arg_size())
3522 return false;
3523 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
3524 if (!LI)
3525 return false;
3527 if (!GV || !GV->isDeclaration())
3528 return false;
3529 return GV->getName() == "stderr";
3530}
3531
3532Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
3533 // Check for a fixed format string.
3534 StringRef FormatStr;
3535 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
3536 return nullptr;
3537
3538 // Empty format string -> noop.
3539 if (FormatStr.empty()) // Tolerate printf's declared void.
3540 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
3541
3542 // Do not do any of the following transformations if the printf return value
3543 // is used, in general the printf return value is not compatible with either
3544 // putchar() or puts().
3545 if (!CI->use_empty())
3546 return nullptr;
3547
3548 Type *IntTy = CI->getType();
3549 // printf("x") -> putchar('x'), even for "%" and "%%".
3550 if (FormatStr.size() == 1 || FormatStr == "%%") {
3551 // Convert the character to unsigned char before passing it to putchar
3552 // to avoid host-specific sign extension in the IR. Putchar converts
3553 // it to unsigned char regardless.
3554 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]);
3555 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3556 }
3557
3558 // Try to remove call or emit putchar/puts.
3559 if (FormatStr == "%s" && CI->arg_size() > 1) {
3560 StringRef OperandStr;
3561 if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
3562 return nullptr;
3563 // printf("%s", "") --> NOP
3564 if (OperandStr.empty())
3565 return (Value *)CI;
3566 // printf("%s", "a") --> putchar('a')
3567 if (OperandStr.size() == 1) {
3568 // Convert the character to unsigned char before passing it to putchar
3569 // to avoid host-specific sign extension in the IR. Putchar converts
3570 // it to unsigned char regardless.
3571 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]);
3572 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3573 }
3574 // printf("%s", str"\n") --> puts(str)
3575 if (OperandStr.back() == '\n') {
3576 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3577 return nullptr;
3578 OperandStr = OperandStr.drop_back();
3579 Value *GV = B.CreateGlobalString(OperandStr, "str");
3580 return copyFlags(*CI, emitPutS(GV, B, TLI));
3581 }
3582 return nullptr;
3583 }
3584
3585 // printf("foo\n") --> puts("foo")
3586 if (FormatStr.back() == '\n' &&
3587 !FormatStr.contains('%')) { // No format characters.
3588 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3589 return nullptr;
3590 // Create a string literal with no \n on it. We expect the constant merge
3591 // pass to be run after this pass, to merge duplicate strings.
3592 FormatStr = FormatStr.drop_back();
3593 Value *GV = B.CreateGlobalString(FormatStr, "str");
3594 return copyFlags(*CI, emitPutS(GV, B, TLI));
3595 }
3596
3597 // Optimize specific format strings.
3598 // printf("%c", chr) --> putchar(chr)
3599 if (FormatStr == "%c" && CI->arg_size() > 1 &&
3600 CI->getArgOperand(1)->getType()->isIntegerTy()) {
3601 // Convert the argument to the type expected by putchar, i.e., int, which
3602 // need not be 32 bits wide but which is the same as printf's return type.
3603 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false);
3604 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3605 }
3606
3607 // printf("%s\n", str) --> puts(str)
3608 if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
3609 CI->getArgOperand(1)->getType()->isPointerTy())
3610 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
3611 return nullptr;
3612}
3613
3614Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
3615
3616 Module *M = CI->getModule();
3618 FunctionType *FT = Callee->getFunctionType();
3619 if (Value *V = optimizePrintFString(CI, B)) {
3620 return V;
3621 }
3622
3624
3625 // printf(format, ...) -> iprintf(format, ...) if no floating point
3626 // arguments.
3627 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
3629 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
3630 Callee->getAttributes());
3631 CallInst *New = cast<CallInst>(CI->clone());
3632 New->setCalledFunction(IPrintFFn);
3633 B.Insert(New);
3634 return New;
3635 }
3636
3637 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
3638 // arguments.
3639 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
3640 !callHasFP128Argument(CI)) {
3641 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
3642 Callee->getAttributes());
3643 CallInst *New = cast<CallInst>(CI->clone());
3644 New->setCalledFunction(SmallPrintFFn);
3645 B.Insert(New);
3646 return New;
3647 }
3648
3649 return nullptr;
3650}
3651
3652Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
3653 IRBuilderBase &B) {
3654 // Check for a fixed format string.
3655 StringRef FormatStr;
3656 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3657 return nullptr;
3658
3659 // If we just have a format string (nothing else crazy) transform it.
3660 Value *Dest = CI->getArgOperand(0);
3661 if (CI->arg_size() == 2) {
3662 // Make sure there's no % in the constant array. We could try to handle
3663 // %% -> % in the future if we cared.
3664 if (FormatStr.contains('%'))
3665 return nullptr; // we found a format specifier, bail out.
3666
3667 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
3668 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(1), Align(1),
3669 // Copy the null byte.
3670 TLI->getAsSizeT(FormatStr.size() + 1, *CI->getModule()));
3671 return ConstantInt::get(CI->getType(), FormatStr.size());
3672 }
3673
3674 // The remaining optimizations require the format string to be "%s" or "%c"
3675 // and have an extra operand.
3676 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3677 return nullptr;
3678
3679 // Decode the second character of the format string.
3680 if (FormatStr[1] == 'c') {
3681 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3682 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3683 return nullptr;
3684 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
3685 Value *Ptr = Dest;
3686 B.CreateStore(V, Ptr);
3687 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3688 B.CreateStore(B.getInt8(0), Ptr);
3689
3690 return ConstantInt::get(CI->getType(), 1);
3691 }
3692
3693 if (FormatStr[1] == 's') {
3694 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
3695 // strlen(str)+1)
3696 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3697 return nullptr;
3698
3699 if (CI->use_empty())
3700 // sprintf(dest, "%s", str) -> strcpy(dest, str)
3701 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
3702
3703 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
3704 if (SrcLen) {
3705 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1),
3706 TLI->getAsSizeT(SrcLen, *CI->getModule()));
3707 // Returns total number of characters written without null-character.
3708 return ConstantInt::get(CI->getType(), SrcLen - 1);
3709 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
3710 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
3711 Value *PtrDiff = B.CreatePtrDiff(V, Dest);
3712 return B.CreateIntCast(PtrDiff, CI->getType(), false);
3713 }
3714
3715 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3717 return nullptr;
3718
3719 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
3720 if (!Len)
3721 return nullptr;
3722 Value *IncLen =
3723 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
3724 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
3725
3726 // The sprintf result is the unincremented number of bytes in the string.
3727 return B.CreateIntCast(Len, CI->getType(), false);
3728 }
3729 return nullptr;
3730}
3731
3732Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
3733 Module *M = CI->getModule();
3735 FunctionType *FT = Callee->getFunctionType();
3736 if (Value *V = optimizeSPrintFString(CI, B)) {
3737 return V;
3738 }
3739
3741
3742 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
3743 // point arguments.
3744 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
3746 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
3747 FT, Callee->getAttributes());
3748 CallInst *New = cast<CallInst>(CI->clone());
3749 New->setCalledFunction(SIPrintFFn);
3750 B.Insert(New);
3751 return New;
3752 }
3753
3754 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
3755 // floating point arguments.
3756 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
3757 !callHasFP128Argument(CI)) {
3758 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
3759 Callee->getAttributes());
3760 CallInst *New = cast<CallInst>(CI->clone());
3761 New->setCalledFunction(SmallSPrintFFn);
3762 B.Insert(New);
3763 return New;
3764 }
3765
3766 return nullptr;
3767}
3768
3769// Transform an snprintf call CI with the bound N to format the string Str
3770// either to a call to memcpy, or to single character a store, or to nothing,
3771// and fold the result to a constant. A nonnull StrArg refers to the string
3772// argument being formatted. Otherwise the call is one with N < 2 and
3773// the "%c" directive to format a single character.
3774Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg,
3775 StringRef Str, uint64_t N,
3776 IRBuilderBase &B) {
3777 assert(StrArg || (N < 2 && Str.size() == 1));
3778
3779 unsigned IntBits = TLI->getIntSize();
3780 uint64_t IntMax = maxIntN(IntBits);
3781 if (Str.size() > IntMax)
3782 // Bail if the string is longer than INT_MAX. POSIX requires
3783 // implementations to set errno to EOVERFLOW in this case, in
3784 // addition to when N is larger than that (checked by the caller).
3785 return nullptr;
3786
3787 Value *StrLen = ConstantInt::get(CI->getType(), Str.size());
3788 if (N == 0)
3789 return StrLen;
3790
3791 // Set to the number of bytes to copy fron StrArg which is also
3792 // the offset of the terinating nul.
3793 uint64_t NCopy;
3794 if (N > Str.size())
3795 // Copy the full string, including the terminating nul (which must
3796 // be present regardless of the bound).
3797 NCopy = Str.size() + 1;
3798 else
3799 NCopy = N - 1;
3800
3801 Value *DstArg = CI->getArgOperand(0);
3802 if (NCopy && StrArg)
3803 // Transform the call to lvm.memcpy(dst, fmt, N).
3804 copyFlags(*CI, B.CreateMemCpy(DstArg, Align(1), StrArg, Align(1),
3805 TLI->getAsSizeT(NCopy, *CI->getModule())));
3806
3807 if (N > Str.size())
3808 // Return early when the whole format string, including the final nul,
3809 // has been copied.
3810 return StrLen;
3811
3812 // Otherwise, when truncating the string append a terminating nul.
3813 Type *Int8Ty = B.getInt8Ty();
3814 Value *NulOff = B.getIntN(IntBits, NCopy);
3815 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr");
3816 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd);
3817 return StrLen;
3818}
3819
3820Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
3821 IRBuilderBase &B) {
3822 // Check for size
3823 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3824 if (!Size)
3825 return nullptr;
3826
3827 uint64_t N = Size->getZExtValue();
3828 uint64_t IntMax = maxIntN(TLI->getIntSize());
3829 if (N > IntMax)
3830 // Bail if the bound exceeds INT_MAX. POSIX requires implementations
3831 // to set errno to EOVERFLOW in this case.
3832 return nullptr;
3833
3834 Value *DstArg = CI->getArgOperand(0);
3835 Value *FmtArg = CI->getArgOperand(2);
3836
3837 // Check for a fixed format string.
3838 StringRef FormatStr;
3839 if (!getConstantStringInfo(FmtArg, FormatStr))
3840 return nullptr;
3841
3842 // If we just have a format string (nothing else crazy) transform it.
3843 if (CI->arg_size() == 3) {
3844 if (FormatStr.contains('%'))
3845 // Bail if the format string contains a directive and there are
3846 // no arguments. We could handle "%%" in the future.
3847 return nullptr;
3848
3849 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B);
3850 }
3851
3852 // The remaining optimizations require the format string to be "%s" or "%c"
3853 // and have an extra operand.
3854 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4)
3855 return nullptr;
3856
3857 // Decode the second character of the format string.
3858 if (FormatStr[1] == 'c') {
3859 if (N <= 1) {
3860 // Use an arbitary string of length 1 to transform the call into
3861 // either a nul store (N == 1) or a no-op (N == 0) and fold it
3862 // to one.
3863 StringRef CharStr("*");
3864 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B);
3865 }
3866
3867 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3868 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
3869 return nullptr;
3870 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
3871 Value *Ptr = DstArg;
3872 B.CreateStore(V, Ptr);
3873 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3874 B.CreateStore(B.getInt8(0), Ptr);
3875 return ConstantInt::get(CI->getType(), 1);
3876 }
3877
3878 if (FormatStr[1] != 's')
3879 return nullptr;
3880
3881 Value *StrArg = CI->getArgOperand(3);
3882 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
3883 StringRef Str;
3884 if (!getConstantStringInfo(StrArg, Str))
3885 return nullptr;
3886
3887 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B);
3888}
3889
3890Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
3891 if (Value *V = optimizeSnPrintFString(CI, B)) {
3892 return V;
3893 }
3894
3895 if (isKnownNonZero(CI->getOperand(1), DL))
3897 return nullptr;
3898}
3899
3900Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
3901 IRBuilderBase &B) {
3902 optimizeErrorReporting(CI, B, 0);
3903
3904 // All the optimizations depend on the format string.
3905 StringRef FormatStr;
3906 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3907 return nullptr;
3908
3909 // Do not do any of the following transformations if the fprintf return
3910 // value is used, in general the fprintf return value is not compatible
3911 // with fwrite(), fputc() or fputs().
3912 if (!CI->use_empty())
3913 return nullptr;
3914
3915 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
3916 if (CI->arg_size() == 2) {
3917 // Could handle %% -> % if we cared.
3918 if (FormatStr.contains('%'))
3919 return nullptr; // We found a format specifier.
3920
3921 return copyFlags(
3922 *CI, emitFWrite(CI->getArgOperand(1),
3923 TLI->getAsSizeT(FormatStr.size(), *CI->getModule()),
3924 CI->getArgOperand(0), B, DL, TLI));
3925 }
3926
3927 // The remaining optimizations require the format string to be "%s" or "%c"
3928 // and have an extra operand.
3929 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3930 return nullptr;
3931
3932 // Decode the second character of the format string.
3933 if (FormatStr[1] == 'c') {
3934 // fprintf(F, "%c", chr) --> fputc((int)chr, F)
3935 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3936 return nullptr;
3937 Type *IntTy = B.getIntNTy(TLI->getIntSize());
3938 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true,
3939 "chari");
3940 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI));
3941 }
3942
3943 if (FormatStr[1] == 's') {
3944 // fprintf(F, "%s", str) --> fputs(str, F)
3945 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3946 return nullptr;
3947 return copyFlags(
3948 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
3949 }
3950 return nullptr;
3951}
3952
3953Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
3954 Module *M = CI->getModule();
3956 FunctionType *FT = Callee->getFunctionType();
3957 if (Value *V = optimizeFPrintFString(CI, B)) {
3958 return V;
3959 }
3960
3961 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
3962 // floating point arguments.
3963 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
3965 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
3966 FT, Callee->getAttributes());
3967 CallInst *New = cast<CallInst>(CI->clone());
3968 New->setCalledFunction(FIPrintFFn);
3969 B.Insert(New);
3970 return New;
3971 }
3972
3973 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
3974 // 128-bit floating point arguments.
3975 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
3976 !callHasFP128Argument(CI)) {
3977 auto SmallFPrintFFn =
3978 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
3979 Callee->getAttributes());
3980 CallInst *New = cast<CallInst>(CI->clone());
3981 New->setCalledFunction(SmallFPrintFFn);
3982 B.Insert(New);
3983 return New;
3984 }
3985
3986 return nullptr;
3987}
3988
3989Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
3990 optimizeErrorReporting(CI, B, 3);
3991
3992 // Get the element size and count.
3993 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3994 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
3995 if (SizeC && CountC) {
3996 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
3997
3998 // If this is writing zero records, remove the call (it's a noop).
3999 if (Bytes == 0)
4000 return ConstantInt::get(CI->getType(), 0);
4001
4002 // If this is writing one byte, turn it into fputc.
4003 // This optimisation is only valid, if the return value is unused.
4004 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
4005 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char");
4006 Type *IntTy = B.getIntNTy(TLI->getIntSize());
4007 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari");
4008 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI);
4009 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
4010 }
4011 }
4012
4013 return nullptr;
4014}
4015
4016Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
4017 optimizeErrorReporting(CI, B, 1);
4018
4019 // Don't rewrite fputs to fwrite when optimising for size because fwrite
4020 // requires more arguments and thus extra MOVs are required.
4021 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
4023 return nullptr;
4024
4025 // We can't optimize if return value is used.
4026 if (!CI->use_empty())
4027 return nullptr;
4028
4029 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
4031 if (!Len)
4032 return nullptr;
4033
4034 // Known to have no uses (see above).
4035 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
4036 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
4037 return copyFlags(
4038 *CI,
4040 ConstantInt::get(SizeTTy, Len - 1),
4041 CI->getArgOperand(1), B, DL, TLI));
4042}
4043
4044Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
4046 if (!CI->use_empty())
4047 return nullptr;
4048
4049 // Check for a constant string.
4050 // puts("") -> putchar('\n')
4051 StringRef Str;
4052 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) {
4053 // putchar takes an argument of the same type as puts returns, i.e.,
4054 // int, which need not be 32 bits wide.
4055 Type *IntTy = CI->getType();
4056 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI));
4057 }
4058
4059 return nullptr;
4060}
4061
4062Value *LibCallSimplifier::optimizeExit(CallInst *CI) {
4063
4064 // Mark 'exit' as cold if its not exit(0) (success).
4065 const APInt *C;
4066 if (!CI->hasFnAttr(Attribute::Cold) &&
4067 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) {
4068 CI->addFnAttr(Attribute::Cold);
4069 }
4070 return nullptr;
4071}
4072
4073Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
4074 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
4075 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
4076 CI->getArgOperand(0), Align(1),
4077 CI->getArgOperand(2)));
4078}
4079
4080bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
4081 SmallString<20> FloatFuncName = FuncName;
4082 FloatFuncName += 'f';
4083 return isLibFuncEmittable(M, TLI, FloatFuncName);
4084}
4085
4086Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
4087 IRBuilderBase &Builder) {
4088 Module *M = CI->getModule();
4090 LibFunc Func = TLI->getLibFunc(*Callee);
4091
4092 // Check for string/memory library functions.
4093 if (isLibFuncEmittable(M, TLI, Func)) {
4094 // Make sure we never change the calling convention.
4095 assert(
4096 (ignoreCallingConv(Func) ||
4098 "Optimizing string/memory libcall would change the calling convention");
4099 switch (Func) {
4100 case LibFunc_strcat:
4101 return optimizeStrCat(CI, Builder);
4102 case LibFunc_strncat:
4103 return optimizeStrNCat(CI, Builder);
4104 case LibFunc_strchr:
4105 return optimizeStrChr(CI, Builder);
4106 case LibFunc_strrchr:
4107 return optimizeStrRChr(CI, Builder);
4108 case LibFunc_strcmp:
4109 return optimizeStrCmp(CI, Builder);
4110 case LibFunc_strncmp:
4111 return optimizeStrNCmp(CI, Builder);
4112 case LibFunc_strcpy:
4113 return optimizeStrCpy(CI, Builder);
4114 case LibFunc_stpcpy:
4115 return optimizeStpCpy(CI, Builder);
4116 case LibFunc_strlcpy:
4117 return optimizeStrLCpy(CI, Builder);
4118 case LibFunc_stpncpy:
4119 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder);
4120 case LibFunc_strncpy:
4121 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder);
4122 case LibFunc_strlen:
4123 return optimizeStrLen(CI, Builder);
4124 case LibFunc_strnlen:
4125 return optimizeStrNLen(CI, Builder);
4126 case LibFunc_strpbrk:
4127 return optimizeStrPBrk(CI, Builder);
4128 case LibFunc_strndup:
4129 return optimizeStrNDup(CI, Builder);
4130 case LibFunc_strtol:
4131 case LibFunc_strtod:
4132 case LibFunc_strtof:
4133 case LibFunc_strtoul:
4134 case LibFunc_strtoll:
4135 case LibFunc_strtold:
4136 case LibFunc_strtoull:
4137 return optimizeStrTo(CI, Builder);
4138 case LibFunc_strspn:
4139 return optimizeStrSpn(CI, Builder);
4140 case LibFunc_strcspn:
4141 return optimizeStrCSpn(CI, Builder);
4142 case LibFunc_strstr:
4143 return optimizeStrStr(CI, Builder);
4144 case LibFunc_memchr:
4145 return optimizeMemChr(CI, Builder);
4146 case LibFunc_memrchr:
4147 return optimizeMemRChr(CI, Builder);
4148 case LibFunc_bcmp:
4149 return optimizeBCmp(CI, Builder);
4150 case LibFunc_memcmp:
4151 return optimizeMemCmp(CI, Builder);
4152 case LibFunc_memcpy:
4153 return optimizeMemCpy(CI, Builder);
4154 case LibFunc_memccpy:
4155 return optimizeMemCCpy(CI, Builder);
4156 case LibFunc_mempcpy:
4157 return optimizeMemPCpy(CI, Builder);
4158 case LibFunc_memmove:
4159 return optimizeMemMove(CI, Builder);
4160 case LibFunc_memset:
4161 return optimizeMemSet(CI, Builder);
4162 case LibFunc_realloc:
4163 return optimizeRealloc(CI, Builder);
4164 case LibFunc_wcslen:
4165 return optimizeWcslen(CI, Builder);
4166 case LibFunc_bcopy:
4167 return optimizeBCopy(CI, Builder);
4168 case LibFunc_Znwm:
4169 case LibFunc_ZnwmRKSt9nothrow_t:
4170 case LibFunc_ZnwmSt11align_val_t:
4171 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
4172 case LibFunc_Znam:
4173 case LibFunc_ZnamRKSt9nothrow_t:
4174 case LibFunc_ZnamSt11align_val_t:
4175 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
4176 case LibFunc_Znwm12__hot_cold_t:
4177 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
4178 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
4179 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4180 case LibFunc_Znam12__hot_cold_t:
4181 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
4182 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
4183 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4184 case LibFunc_size_returning_new:
4185 case LibFunc_size_returning_new_hot_cold:
4186 case LibFunc_size_returning_new_aligned:
4187 case LibFunc_size_returning_new_aligned_hot_cold:
4188 return optimizeNew(CI, Builder, Func);
4189 default:
4190 break;
4191 }
4192 }
4193 return nullptr;
4194}
4195
4196/// Constant folding nan/nanf/nanl.
4198 StringRef CharSeq;
4199 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq))
4200 return nullptr;
4201
4202 APInt Fill;
4203 // Treat empty strings as if they were zero.
4204 if (CharSeq.empty())
4205 Fill = APInt(32, 0);
4206 else if (CharSeq.getAsInteger(0, Fill))
4207 return nullptr;
4208
4209 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill);
4210}
4211
4212Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
4213 LibFunc Func,
4214 IRBuilderBase &Builder) {
4215 const Module *M = CI->getModule();
4216
4217 // Don't optimize calls that require strict floating point semantics.
4218 if (CI->isStrictFP())
4219 return nullptr;
4220
4221 if (Value *V = optimizeSymmetric(CI, Func, Builder))
4222 return V;
4223
4224 switch (Func) {
4225 case LibFunc_sinpif:
4226 case LibFunc_sinpi:
4227 return optimizeSinCosPi(CI, /*IsSin*/true, Builder);
4228 case LibFunc_cospif:
4229 case LibFunc_cospi:
4230 return optimizeSinCosPi(CI, /*IsSin*/false, Builder);
4231 case LibFunc_sinf:
4232 case LibFunc_sinl:
4233 if (CI->doesNotAccessMemory())
4234 return replaceUnaryCall(CI, Builder, Intrinsic::sin);
4235 return nullptr;
4236 case LibFunc_cosf:
4237 case LibFunc_cosl:
4238 if (CI->doesNotAccessMemory())
4239 return replaceUnaryCall(CI, Builder, Intrinsic::cos);
4240 return nullptr;
4241 case LibFunc_powf:
4242 case LibFunc_pow:
4243 case LibFunc_powl:
4244 return optimizePow(CI, Builder);
4245 case LibFunc_exp2l:
4246 case LibFunc_exp2:
4247 case LibFunc_exp2f:
4248 return optimizeExp2(CI, Builder);
4249 case LibFunc_ldexp:
4250 case LibFunc_ldexpf:
4251 case LibFunc_ldexpl:
4252 case LibFunc_scalbn:
4253 case LibFunc_scalbnf:
4254 case LibFunc_scalbnl:
4255 // LLVM floating-point types have radix 2, so scalbn is equivalent to
4256 // ldexp. Do not replace a libcall that may set errno.
4257 if (CI->doesNotAccessMemory()) {
4258 Value *NewCall =
4259 Builder.CreateLdexp(CI->getArgOperand(0), CI->getArgOperand(1), CI);
4260 NewCall->takeName(CI);
4261 return copyFlags(*CI, NewCall);
4262 }
4263 return nullptr;
4264 case LibFunc_fabsf:
4265 case LibFunc_fabs:
4266 case LibFunc_fabsl:
4267 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
4268 case LibFunc_sqrtf:
4269 case LibFunc_sqrt:
4270 case LibFunc_sqrtl:
4271 if (Value *V = optimizeSqrt(CI, Builder))
4272 return V;
4273 if (CI->doesNotAccessMemory())
4274 return replaceUnaryCall(CI, Builder, Intrinsic::sqrt);
4275 return nullptr;
4276 case LibFunc_fmod:
4277 case LibFunc_fmodf:
4278 case LibFunc_fmodl:
4279 return optimizeFMod(CI, Builder);
4280 case LibFunc_logf:
4281 case LibFunc_log:
4282 case LibFunc_logl:
4283 case LibFunc_log10f:
4284 case LibFunc_log10:
4285 case LibFunc_log10l:
4286 case LibFunc_log1pf:
4287 case LibFunc_log1p:
4288 case LibFunc_log1pl:
4289 case LibFunc_log2f:
4290 case LibFunc_log2:
4291 case LibFunc_log2l:
4292 case LibFunc_logbf:
4293 case LibFunc_logb:
4294 case LibFunc_logbl:
4295 return optimizeLog(CI, Builder);
4296 case LibFunc_tan:
4297 case LibFunc_tanf:
4298 case LibFunc_tanl:
4299 case LibFunc_sinh:
4300 case LibFunc_sinhf:
4301 case LibFunc_sinhl:
4302 case LibFunc_asinh:
4303 case LibFunc_asinhf:
4304 case LibFunc_asinhl:
4305 case LibFunc_cosh:
4306 case LibFunc_coshf:
4307 case LibFunc_coshl:
4308 case LibFunc_atanh:
4309 case LibFunc_atanhf:
4310 case LibFunc_atanhl:
4311 return optimizeTrigInversionPairs(CI, Builder);
4312 case LibFunc_ceilf:
4313 case LibFunc_ceil:
4314 case LibFunc_ceill:
4315 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
4316 case LibFunc_floorf:
4317 case LibFunc_floor:
4318 case LibFunc_floorl:
4319 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
4320 case LibFunc_roundf:
4321 case LibFunc_round:
4322 case LibFunc_roundl:
4323 return replaceUnaryCall(CI, Builder, Intrinsic::round);
4324 case LibFunc_roundevenf:
4325 case LibFunc_roundeven:
4326 case LibFunc_roundevenl:
4327 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
4328 case LibFunc_nearbyintf:
4329 case LibFunc_nearbyint:
4330 case LibFunc_nearbyintl:
4331 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
4332 case LibFunc_rintf:
4333 case LibFunc_rint:
4334 case LibFunc_rintl:
4335 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
4336 case LibFunc_truncf:
4337 case LibFunc_trunc:
4338 case LibFunc_truncl:
4339 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
4340 case LibFunc_sin:
4341 case LibFunc_cos:
4342 if (UnsafeFPShrink &&
4343 hasFloatVersion(M, CI->getCalledFunction()->getName()))
4344 if (Value *V = optimizeUnaryDoubleFP(CI, Builder, TLI, true))
4345 return V;
4346 if (CI->doesNotAccessMemory())
4347 return replaceUnaryCall(
4348 CI, Builder, Func == LibFunc_sin ? Intrinsic::sin : Intrinsic::cos);
4349 return nullptr;
4350 case LibFunc_acos:
4351 case LibFunc_acosh:
4352 case LibFunc_asin:
4353 case LibFunc_atan:
4354 case LibFunc_cbrt:
4355 case LibFunc_exp:
4356 case LibFunc_exp10:
4357 case LibFunc_expm1:
4358 case LibFunc_tanh:
4359 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
4360 return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
4361 return nullptr;
4362 case LibFunc_copysign:
4363 if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
4364 if (Value *V = optimizeBinaryDoubleFP(CI, Builder, TLI))
4365 return V;
4366 [[fallthrough]];
4367 case LibFunc_copysignf:
4368 case LibFunc_copysignl:
4369 return replaceBinaryCall(CI, Builder, Intrinsic::copysign);
4370 case LibFunc_fdim:
4371 case LibFunc_fdimf:
4372 case LibFunc_fdiml:
4373 return optimizeFdim(CI, Builder);
4374 case LibFunc_fminf:
4375 case LibFunc_fmin:
4376 case LibFunc_fminl:
4377 return optimizeFMinFMax(CI, Builder, Intrinsic::minnum);
4378 case LibFunc_fmaxf:
4379 case LibFunc_fmax:
4380 case LibFunc_fmaxl:
4381 return optimizeFMinFMax(CI, Builder, Intrinsic::maxnum);
4382 case LibFunc_fminimum_numf:
4383 case LibFunc_fminimum_num:
4384 case LibFunc_fminimum_numl:
4385 return replaceBinaryCall(CI, Builder, Intrinsic::minimumnum);
4386 case LibFunc_fmaximum_numf:
4387 case LibFunc_fmaximum_num:
4388 case LibFunc_fmaximum_numl:
4389 return replaceBinaryCall(CI, Builder, Intrinsic::maximumnum);
4390 case LibFunc_cabs:
4391 case LibFunc_cabsf:
4392 case LibFunc_cabsl:
4393 return optimizeCAbs(CI, Builder);
4394 case LibFunc_remquo:
4395 case LibFunc_remquof:
4396 case LibFunc_remquol:
4397 return optimizeRemquo(CI, Builder);
4398 case LibFunc_nan:
4399 case LibFunc_nanf:
4400 case LibFunc_nanl:
4401 return optimizeNaN(CI);
4402 default:
4403 return nullptr;
4404 }
4405}
4406
4408 Module *M = CI->getModule();
4409 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
4410
4411 Function *Callee = CI->getCalledFunction();
4412 LibFunc Func = TLI->getLibFunc(*Callee);
4413
4414 // Most calls are neither intrinsics nor known library functions. Bail out
4415 // before doing the (comparatively expensive) set-up below. This also covers
4416 // nobuiltin calls, since operator new calls are always library functions.
4417 if (Func == NotLibFunc && !isa<IntrinsicInst>(CI))
4418 return nullptr;
4419
4420 // TODO: Split out the code below that operates on FP calls so that
4421 // we can all non-FP calls with the StrictFP attribute to be
4422 // optimized.
4423 if (CI->isNoBuiltin()) {
4424 // Optionally update operator new calls.
4425 return maybeOptimizeNoBuiltinOperatorNew(CI, Builder);
4426 }
4427
4428 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4429
4431 CI->getOperandBundlesAsDefs(OpBundles);
4432
4434 Builder.setDefaultOperandBundles(OpBundles);
4435
4436 // Command-line parameter overrides instruction attribute.
4437 // This can't be moved to optimizeFloatingPointLibCall() because it may be
4438 // used by the intrinsic optimizations.
4439 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
4440 UnsafeFPShrink = EnableUnsafeFPShrink;
4441 else if (isa<FPMathOperator>(CI) && CI->isFast())
4442 UnsafeFPShrink = true;
4443
4444 // First, check for intrinsics.
4446 if (!IsCallingConvC)
4447 return nullptr;
4448 // The FP intrinsics have corresponding constrained versions so we don't
4449 // need to check for the StrictFP attribute here.
4450 switch (II->getIntrinsicID()) {
4451 case Intrinsic::pow:
4452 return optimizePow(CI, Builder);
4453 case Intrinsic::exp2:
4454 return optimizeExp2(CI, Builder);
4455 case Intrinsic::log:
4456 case Intrinsic::log2:
4457 case Intrinsic::log10:
4458 return optimizeLog(CI, Builder);
4459 case Intrinsic::sqrt:
4460 return optimizeSqrt(CI, Builder);
4461 case Intrinsic::memset:
4462 return optimizeMemSet(CI, Builder);
4463 case Intrinsic::memcpy:
4464 return optimizeMemCpy(CI, Builder);
4465 case Intrinsic::memmove:
4466 return optimizeMemMove(CI, Builder);
4467 case Intrinsic::sin:
4468 case Intrinsic::cos:
4469 if (UnsafeFPShrink)
4470 return optimizeUnaryDoubleFP(CI, Builder, TLI, /*isPrecise=*/true);
4471 return nullptr;
4472 case Intrinsic::sincos:
4473 if (UnsafeFPShrink)
4474 return optimizeSinCosDoubleFP(CI, Builder);
4475 return nullptr;
4476 default:
4477 return nullptr;
4478 }
4479 }
4480
4481 // Also try to simplify calls to fortified library functions.
4482 if (Value *SimplifiedFortifiedCI =
4483 FortifiedSimplifier.optimizeCall(CI, Builder))
4484 return SimplifiedFortifiedCI;
4485
4486 // Then check for known library functions.
4487 if (isLibFuncEmittable(M, TLI, Func)) {
4488 // We never change the calling convention.
4489 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4490 return nullptr;
4491 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
4492 return V;
4493 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
4494 return V;
4495 switch (Func) {
4496 case LibFunc_ffs:
4497 case LibFunc_ffsl:
4498 case LibFunc_ffsll:
4499 return optimizeFFS(CI, Builder);
4500 case LibFunc_fls:
4501 case LibFunc_flsl:
4502 case LibFunc_flsll:
4503 return optimizeFls(CI, Builder);
4504 case LibFunc_abs:
4505 case LibFunc_labs:
4506 case LibFunc_llabs:
4507 return optimizeAbs(CI, Builder);
4508 case LibFunc_isdigit:
4509 return optimizeIsDigit(CI, Builder);
4510 case LibFunc_isascii:
4511 return optimizeIsAscii(CI, Builder);
4512 case LibFunc_toascii:
4513 return optimizeToAscii(CI, Builder);
4514 case LibFunc_atoi:
4515 case LibFunc_atol:
4516 case LibFunc_atoll:
4517 return optimizeAtoi(CI, Builder);
4518 case LibFunc_strtol:
4519 case LibFunc_strtoll:
4520 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true);
4521 case LibFunc_strtoul:
4522 case LibFunc_strtoull:
4523 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false);
4524 case LibFunc_printf:
4525 return optimizePrintF(CI, Builder);
4526 case LibFunc_sprintf:
4527 return optimizeSPrintF(CI, Builder);
4528 case LibFunc_snprintf:
4529 return optimizeSnPrintF(CI, Builder);
4530 case LibFunc_fprintf:
4531 return optimizeFPrintF(CI, Builder);
4532 case LibFunc_fwrite:
4533 return optimizeFWrite(CI, Builder);
4534 case LibFunc_fputs:
4535 return optimizeFPuts(CI, Builder);
4536 case LibFunc_puts:
4537 return optimizePuts(CI, Builder);
4538 case LibFunc_perror:
4539 return optimizeErrorReporting(CI, Builder);
4540 case LibFunc_vfprintf:
4541 case LibFunc_fiprintf:
4542 return optimizeErrorReporting(CI, Builder, 0);
4543 case LibFunc_exit:
4544 case LibFunc_Exit:
4545 return optimizeExit(CI);
4546 default:
4547 return nullptr;
4548 }
4549 }
4550 return nullptr;
4551}
4552
4554 const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT,
4557 function_ref<void(Instruction *, Value *)> Replacer,
4558 function_ref<void(Instruction *)> Eraser)
4559 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), DT(DT), DC(DC), AC(AC),
4560 ORE(ORE), BFI(BFI), PSI(PSI), Replacer(Replacer), Eraser(Eraser) {}
4561
4562void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
4563 // Indirect through the replacer used in this instance.
4564 Replacer(I, With);
4565}
4566
4567void LibCallSimplifier::eraseFromParent(Instruction *I) {
4568 Eraser(I);
4569}
4570
4571// TODO:
4572// Additional cases that we need to add to this file:
4573//
4574// cbrt:
4575// * cbrt(expN(X)) -> expN(x/3)
4576// * cbrt(sqrt(x)) -> pow(x,1/6)
4577// * cbrt(cbrt(x)) -> pow(x,1/9)
4578//
4579// exp, expf, expl:
4580// * exp(log(x)) -> x
4581//
4582// log, logf, logl:
4583// * log(exp(x)) -> x
4584// * log(exp(y)) -> y*log(e)
4585// * log(exp10(y)) -> y*log(10)
4586// * log(sqrt(x)) -> 0.5*log(x)
4587//
4588// pow, powf, powl:
4589// * pow(sqrt(x),y) -> pow(x,y*0.5)
4590// * pow(pow(x,y),z)-> pow(x,y*z)
4591//
4592// signbit:
4593// * signbit(cnst) -> cnst'
4594// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
4595//
4596// sqrt, sqrtf, sqrtl:
4597// * sqrt(expN(x)) -> expN(x*0.5)
4598// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
4599// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
4600//
4601
4602//===----------------------------------------------------------------------===//
4603// Fortified Library Call Optimizations
4604//===----------------------------------------------------------------------===//
4605
4606bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(
4607 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp,
4608 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) {
4609 // If this function takes a flag argument, the implementation may use it to
4610 // perform extra checks. Don't fold into the non-checking variant.
4611 if (FlagOp) {
4612 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
4613 if (!Flag || !Flag->isZero())
4614 return false;
4615 }
4616
4617 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
4618 return true;
4619
4620 if (ConstantInt *ObjSizeCI =
4621 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
4622 if (ObjSizeCI->isMinusOne())
4623 return true;
4624 // If the object size wasn't -1 (unknown), bail out if we were asked to.
4625 if (OnlyLowerUnknownSize)
4626 return false;
4627 if (StrOp) {
4629 // If the length is 0 we don't know how long it is and so we can't
4630 // remove the check.
4631 if (Len)
4632 annotateDereferenceableBytes(CI, *StrOp, Len);
4633 else
4634 return false;
4635 return ObjSizeCI->getZExtValue() >= Len;
4636 }
4637
4638 if (SizeOp) {
4639 if (ConstantInt *SizeCI =
4641 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
4642 }
4643 }
4644 return false;
4645}
4646
4647Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
4648 IRBuilderBase &B) {
4649 if (isFortifiedCallFoldable(CI, 3, 2)) {
4650 CallInst *NewCI =
4651 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4652 Align(1), CI->getArgOperand(2));
4653 mergeAttributesAndFlags(NewCI, *CI);
4654 return CI->getArgOperand(0);
4655 }
4656 return nullptr;
4657}
4658
4659Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
4660 IRBuilderBase &B) {
4661 if (isFortifiedCallFoldable(CI, 3, 2)) {
4662 CallInst *NewCI =
4663 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4664 Align(1), CI->getArgOperand(2));
4665 mergeAttributesAndFlags(NewCI, *CI);
4666 return CI->getArgOperand(0);
4667 }
4668 return nullptr;
4669}
4670
4671Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
4672 IRBuilderBase &B) {
4673 if (isFortifiedCallFoldable(CI, 3, 2)) {
4674 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
4675 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
4676 CI->getArgOperand(2), Align(1));
4677 mergeAttributesAndFlags(NewCI, *CI);
4678 return CI->getArgOperand(0);
4679 }
4680 return nullptr;
4681}
4682
4683Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
4684 IRBuilderBase &B) {
4685 const DataLayout &DL = CI->getDataLayout();
4686 if (isFortifiedCallFoldable(CI, 3, 2))
4687 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4688 CI->getArgOperand(2), B, DL, TLI)) {
4690 }
4691 return nullptr;
4692}
4693
4694Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
4696 LibFunc Func) {
4697 const DataLayout &DL = CI->getDataLayout();
4698 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
4699 *ObjSize = CI->getArgOperand(2);
4700
4701 // __stpcpy_chk(x,x,...) -> x+strlen(x)
4702 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
4703 Value *StrLen = emitStrLen(Src, B, DL, TLI);
4704 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
4705 }
4706
4707 // If a) we don't have any length information, or b) we know this will
4708 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
4709 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
4710 // TODO: It might be nice to get a maximum length out of the possible
4711 // string lengths for varying.
4712 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) {
4713 if (Func == LibFunc_strcpy_chk)
4714 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
4715 else
4716 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
4717 }
4718
4719 if (OnlyLowerUnknownSize)
4720 return nullptr;
4721
4722 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
4724 if (Len)
4725 annotateDereferenceableBytes(CI, 1, Len);
4726 else
4727 return nullptr;
4728
4729 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
4730 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
4731 Value *LenV = ConstantInt::get(SizeTTy, Len);
4732 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
4733 // If the function was an __stpcpy_chk, and we were able to fold it into
4734 // a __memcpy_chk, we still need to return the correct end pointer.
4735 if (Ret && Func == LibFunc_stpcpy_chk)
4736 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst,
4737 ConstantInt::get(SizeTTy, Len - 1));
4738 return copyFlags(*CI, cast<CallInst>(Ret));
4739}
4740
4741Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
4742 IRBuilderBase &B) {
4743 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0))
4744 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
4745 CI->getDataLayout(), TLI));
4746 return nullptr;
4747}
4748
4749Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
4751 LibFunc Func) {
4752 if (isFortifiedCallFoldable(CI, 3, 2)) {
4753 if (Func == LibFunc_strncpy_chk)
4754 return copyFlags(*CI,
4756 CI->getArgOperand(2), B, TLI));
4757 else
4758 return copyFlags(*CI,
4760 CI->getArgOperand(2), B, TLI));
4761 }
4762
4763 return nullptr;
4764}
4765
4766Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
4767 IRBuilderBase &B) {
4768 if (isFortifiedCallFoldable(CI, 4, 3))
4769 return copyFlags(
4770 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4771 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
4772
4773 return nullptr;
4774}
4775
4776Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
4777 IRBuilderBase &B) {
4778 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) {
4779 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
4780 return copyFlags(*CI,
4782 CI->getArgOperand(4), VariadicArgs, B, TLI));
4783 }
4784
4785 return nullptr;
4786}
4787
4788Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
4789 IRBuilderBase &B) {
4790 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) {
4791 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
4792 return copyFlags(*CI,
4794 VariadicArgs, B, TLI));
4795 }
4796
4797 return nullptr;
4798}
4799
4800Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
4801 IRBuilderBase &B) {
4802 if (isFortifiedCallFoldable(CI, 2))
4803 return copyFlags(
4804 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
4805
4806 return nullptr;
4807}
4808
4809Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
4810 IRBuilderBase &B) {
4811 if (isFortifiedCallFoldable(CI, 3))
4812 return copyFlags(*CI,
4814 CI->getArgOperand(2), B, TLI));
4815
4816 return nullptr;
4817}
4818
4819Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
4820 IRBuilderBase &B) {
4821 if (isFortifiedCallFoldable(CI, 3))
4822 return copyFlags(*CI,
4824 CI->getArgOperand(2), B, TLI));
4825
4826 return nullptr;
4827}
4828
4829Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
4830 IRBuilderBase &B) {
4831 if (isFortifiedCallFoldable(CI, 3))
4832 return copyFlags(*CI,
4834 CI->getArgOperand(2), B, TLI));
4835
4836 return nullptr;
4837}
4838
4839Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
4840 IRBuilderBase &B) {
4841 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2))
4842 return copyFlags(
4843 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
4844 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
4845
4846 return nullptr;
4847}
4848
4849Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
4850 IRBuilderBase &B) {
4851 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1))
4852 return copyFlags(*CI,
4854 CI->getArgOperand(4), B, TLI));
4855
4856 return nullptr;
4857}
4858
4860 IRBuilderBase &Builder) {
4861 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
4862 // Some clang users checked for _chk libcall availability using:
4863 // __has_builtin(__builtin___memcpy_chk)
4864 // When compiling with -fno-builtin, this is always true.
4865 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
4866 // end up with fortified libcalls, which isn't acceptable in a freestanding
4867 // environment which only provides their non-fortified counterparts.
4868 //
4869 // Until we change clang and/or teach external users to check for availability
4870 // differently, disregard the "nobuiltin" attribute and TLI::has.
4871 //
4872 // PR23093.
4873
4874 Function *Callee = CI->getCalledFunction();
4875 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4876
4878 CI->getOperandBundlesAsDefs(OpBundles);
4879
4881 Builder.setDefaultOperandBundles(OpBundles);
4882
4883 // First, check that this is a known library functions and that the prototype
4884 // is correct.
4885 LibFunc Func = TLI->getLibFunc(*Callee);
4886 if (Func == NotLibFunc)
4887 return nullptr;
4888
4889 // We never change the calling convention.
4890 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4891 return nullptr;
4892
4893 switch (Func) {
4894 case LibFunc_memcpy_chk:
4895 return optimizeMemCpyChk(CI, Builder);
4896 case LibFunc_mempcpy_chk:
4897 return optimizeMemPCpyChk(CI, Builder);
4898 case LibFunc_memmove_chk:
4899 return optimizeMemMoveChk(CI, Builder);
4900 case LibFunc_memset_chk:
4901 return optimizeMemSetChk(CI, Builder);
4902 case LibFunc_stpcpy_chk:
4903 case LibFunc_strcpy_chk:
4904 return optimizeStrpCpyChk(CI, Builder, Func);
4905 case LibFunc_strlen_chk:
4906 return optimizeStrLenChk(CI, Builder);
4907 case LibFunc_stpncpy_chk:
4908 case LibFunc_strncpy_chk:
4909 return optimizeStrpNCpyChk(CI, Builder, Func);
4910 case LibFunc_memccpy_chk:
4911 return optimizeMemCCpyChk(CI, Builder);
4912 case LibFunc_snprintf_chk:
4913 return optimizeSNPrintfChk(CI, Builder);
4914 case LibFunc_sprintf_chk:
4915 return optimizeSPrintfChk(CI, Builder);
4916 case LibFunc_strcat_chk:
4917 return optimizeStrCatChk(CI, Builder);
4918 case LibFunc_strlcat_chk:
4919 return optimizeStrLCat(CI, Builder);
4920 case LibFunc_strncat_chk:
4921 return optimizeStrNCatChk(CI, Builder);
4922 case LibFunc_strlcpy_chk:
4923 return optimizeStrLCpyChk(CI, Builder);
4924 case LibFunc_vsnprintf_chk:
4925 return optimizeVSNPrintfChk(CI, Builder);
4926 case LibFunc_vsprintf_chk:
4927 return optimizeVSPrintfChk(CI, Builder);
4928 default:
4929 break;
4930 }
4931 return nullptr;
4932}
4933
4935 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
4936 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static bool mayFlushDenormalsToPositiveZero(const CallInst *CI)
Flushing a denormal to +0.0 breaks f(-x) = -f(x) for odd f.
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
static bool isBinary(MachineInstr &MI)
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static bool isOnlyUsedInEqualityComparison(Value *V, Value *With)
Return true if it is only used in equality comparisons with With.
static Value * optimizeSinCosDoubleFP(CallInst *CI, IRBuilderBase &B)
Shrink double -> float for llvm.sincos.
static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef< unsigned > ArgNos, Value *Size, const DataLayout &DL)
static cl::opt< unsigned, false, HotColdHintParser > ColdNewHintValue("cold-new-hint-value", cl::Hidden, cl::init(1), cl::desc("Value to pass to hot/cold operator new for cold allocation"))
static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg, bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos, const TargetLibraryInfo *TLI)
static Value * mergeAttributesAndFlags(CallInst *NewCI, const CallInst &Old)
static cl::opt< bool > OptimizeHotColdNew("optimize-hot-cold-new", cl::Hidden, cl::init(false), cl::desc("Enable hot/cold operator new library calls"))
static Value * optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float for binary functions.
static cl::opt< OptimizeExistingHotColdNewKind > OptimizeExistingHotColdNew("optimize-existing-hot-cold-new", cl::Hidden, cl::desc("Enable optimization of existing hot/cold operator new library calls"), cl::values(clEnumValN(OptimizeExistingHotColdNewKind::None, "none", "Do not optimize existing hot/cold operator new library calls"), clEnumValN(OptimizeExistingHotColdNewKind::Cold, "cold", "Only optimize existing hot/cold operator new library calls " "if determined to be cold"), clEnumValN(OptimizeExistingHotColdNewKind::Always, "always", "Always optimize existing hot/cold operator new library calls"), clEnumValN(OptimizeExistingHotColdNewKind::Always, "", "Always optimize existing hot/cold operator new library calls")), cl::init(OptimizeExistingHotColdNewKind::None), cl::ValueOptional)
static cl::opt< bool > MinExistingHotColdNewHint("min-existing-hot-cold-new-hint", cl::Hidden, cl::init(false), cl::desc("Take the minimum of compiler hint and existing hint when " "optimizing existing hot/cold operator new library calls"))
static bool ignoreCallingConv(LibFunc Func)
static void annotateDereferenceableBytes(CallInst *CI, ArrayRef< unsigned > ArgNos, uint64_t DereferenceableBytes)
static void copyFPMath(const CallInst &Old, Value *New)
Preserve the accuracy requirement of Old on the replacement New.
static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg)
static Value * optimizeDoubleFP(CallInst *CI, IRBuilderBase &B, bool isBinary, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float functions.
static Value * optimizeSymmetricCall(CallInst *CI, bool IsEven, IRBuilderBase &B)
static Value * getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, Module *M, IRBuilderBase &B, const TargetLibraryInfo *TLI)
static Value * replaceBinaryCall(CallInst *CI, IRBuilderBase &B, Intrinsic::ID IID)
static Value * valueHasFloatPrecision(Value *Val)
Return a variant of Val with float type.
static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI, ArrayRef< unsigned > ArgNos, uint64_t CharSize=1)
static Value * optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS, uint64_t Len, IRBuilderBase &B, const DataLayout &DL)
static Value * createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M, IRBuilderBase &B)
static Value * convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr, uint64_t Base, bool AsSigned, IRBuilderBase &B)
static Value * memChrToCharCompare(CallInst *CI, Value *NBytes, IRBuilderBase &B, const DataLayout &DL)
static Value * copyFlags(const CallInst &Old, Value *New)
static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, const SimplifyQuery &SQ)
static StringRef substr(StringRef Str, uint64_t Len)
static cl::opt< unsigned, false, HotColdHintParser > HotNewHintValue("hot-new-hint-value", cl::Hidden, cl::init(254), cl::desc("Value to pass to hot/cold operator new for hot allocation"))
static bool isTrigLibCall(CallInst *CI)
static Value * optimizeNaN(CallInst *CI)
Constant folding nan/nanf/nanl.
static bool isOnlyUsedInComparisonWithZero(Value *V)
static Value * replaceUnaryCall(CallInst *CI, IRBuilderBase &B, Intrinsic::ID IID)
static bool callHasFloatingPointArgument(const CallInst *CI)
static Value * optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B, const TargetLibraryInfo *TLI, bool isPrecise=false)
Shrink double -> float for unary functions.
static bool callHasFP128Argument(const CallInst *CI)
static cl::opt< bool > OptimizeNoBuiltinHotColdNew("optimize-nobuiltin-hot-cold-new-new", cl::Hidden, cl::init(false), cl::desc("Enable transformation of nobuiltin operator new library calls"))
static cl::opt< unsigned, false, HotColdHintParser > AmbiguousNewHintValue("ambiguous-new-hint-value", cl::Hidden, cl::init(222), cl::desc("Value to pass to hot/cold operator new for ambiguous allocation"))
static Value * optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS, Value *Size, bool StrNCmp, IRBuilderBase &B, const DataLayout &DL)
static Value * getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth)
static cl::opt< bool > EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, cl::init(false), cl::desc("Enable unsafe double to float " "shrinking for math lib calls"))
static cl::opt< unsigned, false, HotColdHintParser > NotColdNewHintValue("notcold-new-hint-value", cl::Hidden, cl::init(128), cl::desc("Value to pass to hot/cold operator new for " "notcold (warm) allocation"))
OptimizeExistingHotColdNewKind
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
bool isFiniteNonZero() const
Definition APFloat.h:1593
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6045
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1294
bool isNegative() const
Definition APFloat.h:1583
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6278
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Definition APFloat.h:1566
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
Definition APFloat.cpp:6306
opStatus remainder(const APFloat &RHS)
Definition APFloat.h:1321
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
static LLVM_ABI Attribute getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove)
Removes the attributes from the given argument.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Removes the attribute from the given argument.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
void removeRetAttrs(const AttributeMask &AttrsToRemove)
Removes the attributes from the return value.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
uint64_t getParamDereferenceableBytes(unsigned i) const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
AttributeSet getRetAttributes() const
Return the return attributes for this call.
void setAttributes(AttributeList A)
Set the attributes for this call.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
uint64_t getParamDereferenceableOrNullBytes(unsigned i) const
Extract the number of dereferenceable_or_null bytes for a parameter (0=unknown).
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
TailCallKind getTailCallKind() const
bool isMustTailCall() const
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This class represents an extension of floating point types.
This class represents a truncation of floating point types.
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
static FastMathFlags getFast()
Definition FMF.h:50
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
LLVM_ABI FortifiedLibCallSimplifier(const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize=false)
LLVM_ABI Value * optimizeCall(CallInst *CI, IRBuilderBase &B)
Take the given call instruction and return a more optimal value to replace the instruction with or 0 ...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:807
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateLdexp(Value *Src, Value *Exp, FMFSource FMFSource={}, const Twine &Name="")
Create call to the ldexp intrinsic.
Definition IRBuilder.h:1086
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI bool isFast() const LLVM_READONLY
Determine whether all fast-math-flags are set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
static constexpr FPClassTest OrderedLessThanZeroMask
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
LLVM_ABI LibCallSimplifier(const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT, DomConditionCache *DC, AssumptionCache *AC, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, function_ref< void(Instruction *, Value *)> Replacer=&replaceAllUsesWithDefault, function_ref< void(Instruction *)> Eraser=&eraseFromParentDefault)
LLVM_ABI Value * optimizeCall(CallInst *CI, IRBuilderBase &B)
optimizeCall - Take the given call instruction and return a more optimal value to replace the instruc...
An instruction for reading from memory.
Value * getPointerOperand()
static constexpr uint32_t kLikelyBranchWeight
The weight for a branch taken with high probability.
Definition MDBuilder.h:46
static constexpr uint32_t kUnlikelyBranchWeight
The weight for a branch taken with low probability.
Definition MDBuilder.h:53
Metadata node.
Definition Metadata.h:1081
iterator begin()
Definition MapVector.h:68
size_type size() const
Definition MapVector.h:59
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
The optimization diagnostic interface.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis providing profile information.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
int compare(StringRef RHS) const
Compare two strings; the result is negative, zero, or positive if this string is lexicographically le...
Definition StringRef.h:177
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
static LLVM_ABI bool isCallingConvCCompatible(CallBase *CI)
Returns true if call site / callee has cdecl-compatible calling conventions.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * emitHotColdSizeReturningNewAligned(Value *Num, Value *Align, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold, Type *RetTy)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
LLVM_ABI Value * emitUnaryFloatFnCall(Value *Op, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the unary function named 'Name' (e.g.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
LLVM_ABI Value * emitStrChr(Value *Ptr, char C, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strchr function to the builder, for the specified pointer and character.
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
LLVM_ABI Value * emitPutChar(Value *Char, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the putchar function. This assumes that Char is an 'int'.
LLVM_ABI Value * emitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the __memcpy_chk function to the builder.
LLVM_ABI Value * emitStrNCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strncpy function to the builder, for the specified pointer arguments and length.
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
@ Known
Known to have no common set bits.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1736
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI Value * emitSPrintf(Value *Dest, Value *Fmt, ArrayRef< Value * > VariadicArgs, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the sprintf function.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI Value * emitMemRChr(Value *Ptr, Value *Val, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memrchr function, analogously to emitMemChr.
LLVM_ABI Value * emitStrLCat(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strlcat function.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool hasFloatFn(const Module *M, const TargetLibraryInfo *TLI, Type *Ty, LibFunc DoubleFn, LibFunc FloatFn, LibFunc LongDoubleFn)
Check whether the overloaded floating point function corresponding to Ty is available.
LLVM_ABI Value * emitHotColdNewNoThrow(Value *Num, Value *NoThrow, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * emitStrNCat(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strncat function.
LLVM_ABI bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI Value * emitVSNPrintf(Value *Dest, Value *Size, Value *Fmt, Value *VAList, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the vsnprintf function.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI Value * emitStrNCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strncmp function to the builder.
LLVM_ABI Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
LLVM_ABI Value * emitBinaryFloatFnCall(Value *Op1, Value *Op2, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the binary function named 'Name' (e.g.
bool isAlpha(char C)
Checks if character C is a valid letter as classified by "C" locale.
LLVM_ABI Value * emitFPutS(Value *Str, Value *File, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the fputs function.
LLVM_ABI Value * emitStrDup(Value *Ptr, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strdup function to the builder, for the specified pointer.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI Value * emitHotColdNewAligned(Value *Num, Value *Align, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold)
LLVM_ABI Value * emitHotColdNewAlignedNoThrow(Value *Num, Value *Align, Value *NoThrow, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold)
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI Value * emitBCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the bcmp function.
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:684
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI FunctionCallee getOrInsertLibFunc(Module *M, const TargetLibraryInfo &TLI, LibFunc TheLibFunc, FunctionType *T, AttributeList AttributeList)
Calls getOrInsertFunction() and then makes sure to add mandatory argument attributes.
LLVM_ABI Value * emitStrLen(Value *Ptr, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
LLVM_ABI Value * emitFPutC(Value *Char, Value *File, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the fputc function.
LLVM_ABI Value * emitStpNCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the stpncpy function to the builder, for the specified pointer arguments and length.
LLVM_ABI Value * emitStrCat(Value *Dest, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strcat function.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * emitVSPrintf(Value *Dest, Value *Fmt, Value *VAList, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the vsprintf function.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI Value * emitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the fwrite function.
LLVM_ABI Value * emitSNPrintf(Value *Dest, Value *Size, Value *Fmt, ArrayRef< Value * > Args, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the snprintf function.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI Value * emitStpCpy(Value *Dst, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the stpcpy function to the builder, for the specified pointer arguments.
@ FMul
Product of floats.
@ And
Bitwise or logical AND of integers.
char toUpper(char x)
Returns the corresponding uppercase character if x is lowercase.
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Value * emitMalloc(Value *Num, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the malloc function.
LLVM_ABI Value * emitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memchr function.
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
LLVM_ABI Value * emitPutS(Value *Str, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the puts function. This assumes that Str is some pointer.
LLVM_ABI Value * emitMemCCpy(Value *Ptr1, Value *Ptr2, Value *Val, Value *Len, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the memccpy function.
LLVM_ABI Value * emitHotColdNew(Value *Num, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold)
Emit a call to the hot/cold operator new function.
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI Value * emitHotColdSizeReturningNew(Value *Num, IRBuilderBase &B, const TargetLibraryInfo *TLI, LibFunc NewFunc, Value *HotCold, Type *RetTy)
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:266
LLVM_ABI Value * emitStrLCpy(Value *Dest, Value *Src, Value *Size, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strlcpy function.
LLVM_ABI Value * emitStrCpy(Value *Dst, Value *Src, IRBuilderBase &B, const TargetLibraryInfo *TLI)
Emit a call to the strcpy function to the builder, for the specified pointer arguments.
@ Always
Always emit .debug_str_offsets talbes as DWARF64 for testing.
Definition DWP.h:32
LLVM_ABI Value * emitMemPCpy(Value *Dst, Value *Src, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the mempcpy function.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
Matching combinators.