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