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