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.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel");
1323 }
1324 }
1325
1326 // Truncate the string to search at most EndOff characters.
1327 Str = Str.substr(0, EndOff);
1328 if (Str.find_first_not_of(Str[0]) != StringRef::npos)
1329 return nullptr;
1330
1331 // If the source array consists of all equal characters, then for any
1332 // C and N (whether in bounds or not), fold memrchr(S, C, N) to
1333 // N != 0 && *S == C ? S + N - 1 : null
1334 Type *SizeTy = Size->getType();
1335 Type *Int8Ty = B.getInt8Ty();
1336 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1337 // Slice off the sought character's high end bits.
1338 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1339 Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal);
1340 Value *And = B.CreateLogicalAnd(NNeZ, CEqS0);
1341 Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1));
1342 Value *SrcPlus =
1343 B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus");
1344 return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel");
1345}
1346
1347Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) {
1348 Value *SrcStr = CI->getArgOperand(0);
1349 Value *Size = CI->getArgOperand(2);
1350
1351 if (isKnownNonZero(Size, DL)) {
1353 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1354 return memChrToCharCompare(CI, Size, B, DL);
1355 }
1356
1357 Value *CharVal = CI->getArgOperand(1);
1358 ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
1359 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1360 Value *NullPtr = Constant::getNullValue(CI->getType());
1361
1362 // memchr(x, y, 0) -> null
1363 if (LenC) {
1364 if (LenC->isZero())
1365 return NullPtr;
1366
1367 if (LenC->isOne()) {
1368 // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y,
1369 // constant or otherwise.
1370 Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0");
1371 // Slice off the character's high end bits.
1372 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1373 Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp");
1374 // The condition depends on the value of the string being equal to the
1375 // query, neither of which we know without value profiling, so mark the
1376 // profile unknown.
1377 return B.CreateSelectWithUnknownProfile(Cmp, SrcStr, NullPtr, DEBUG_TYPE,
1378 "memchr.sel");
1379 }
1380 }
1381
1382 StringRef Str;
1383 if (!getConstantStringInfo(SrcStr, Str, /*TrimAtNul=*/false))
1384 return nullptr;
1385
1386 if (CharC) {
1387 size_t Pos = Str.find(CharC->getZExtValue());
1388 if (Pos == StringRef::npos)
1389 // When the character is not in the source array fold the result
1390 // to null regardless of Size.
1391 return NullPtr;
1392
1393 // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos
1394 // When the constant Size is less than or equal to the character
1395 // position also fold the result to null.
1396 Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1397 "memchr.cmp");
1398 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos),
1399 "memchr.ptr");
1400 // The condition is dependent upon the value of n, which we cannot infer
1401 // without value profiling, so mark the profile unknown.
1402 return B.CreateSelectWithUnknownProfile(Cmp, NullPtr, SrcPlus, DEBUG_TYPE);
1403 }
1404
1405 if (Str.size() == 0)
1406 // If the array is empty fold memchr(A, C, N) to null for any value
1407 // of C and N on the basis that the only valid value of N is zero
1408 // (otherwise the call is undefined).
1409 return NullPtr;
1410
1411 if (LenC)
1412 Str = substr(Str, LenC->getZExtValue());
1413
1414 size_t Pos = Str.find_first_not_of(Str[0]);
1415 if (Pos == StringRef::npos
1416 || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) {
1417 // If the source array consists of at most two consecutive sequences
1418 // of the same characters, then for any C and N (whether in bounds or
1419 // not), fold memchr(S, C, N) to
1420 // N != 0 && *S == C ? S : null
1421 // or for the two sequences to:
1422 // N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null)
1423 // ^Sel2 ^Sel1 are denoted above.
1424 // The latter makes it also possible to fold strchr() calls with strings
1425 // of the same characters.
1426 Type *SizeTy = Size->getType();
1427 Type *Int8Ty = B.getInt8Ty();
1428
1429 // Slice off the sought character's high end bits.
1430 CharVal = B.CreateTrunc(CharVal, Int8Ty);
1431
1432 Value *Sel1 = NullPtr;
1433 if (Pos != StringRef::npos) {
1434 // Handle two consecutive sequences of the same characters.
1435 Value *PosVal = ConstantInt::get(SizeTy, Pos);
1436 Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]);
1437 Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos);
1438 Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal);
1439 Value *And = B.CreateAnd(CEqSPos, NGtPos);
1440 Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal);
1441 // The condition depends on the value of the query and size, neither of
1442 // which we know without value profiling, so mark the profile unknown.
1443 Sel1 = B.CreateSelectWithUnknownProfile(And, SrcPlus, NullPtr, DEBUG_TYPE,
1444 "memchr.sel1");
1445 }
1446
1447 Value *Str0 = ConstantInt::get(Int8Ty, Str[0]);
1448 Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal);
1449 Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1450 Value *And = B.CreateAnd(NNeZ, CEqS0);
1451 // The condition depends on the value of the query and size, neither of
1452 // which we know without value profiling, so mark the profile unknown.
1453 return B.CreateSelectWithUnknownProfile(And, SrcStr, Sel1, DEBUG_TYPE,
1454 "memchr.sel2");
1455 }
1456
1457 if (!LenC) {
1458 if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1459 // S is dereferenceable so it's safe to load from it and fold
1460 // memchr(S, C, N) == S to N && *S == C for any C and N.
1461 // TODO: This is safe even for nonconstant S.
1462 return memChrToCharCompare(CI, Size, B, DL);
1463
1464 // From now on we need a constant length and constant array.
1465 return nullptr;
1466 }
1467
1468 bool OptForSize = llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
1470
1471 // If the char is variable but the input str and length are not we can turn
1472 // this memchr call into a simple bit field test. Of course this only works
1473 // when the return value is only checked against null.
1474 //
1475 // It would be really nice to reuse switch lowering here but we can't change
1476 // the CFG at this point.
1477 //
1478 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
1479 // != 0
1480 // after bounds check.
1481 if (OptForSize || Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI))
1482 return nullptr;
1483
1484 unsigned char Max =
1485 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
1486 reinterpret_cast<const unsigned char *>(Str.end()));
1487
1488 // Make sure the bit field we're about to create fits in a register on the
1489 // target.
1490 // FIXME: On a 64 bit architecture this prevents us from using the
1491 // interesting range of alpha ascii chars. We could do better by emitting
1492 // two bitfields or shifting the range by 64 if no lower chars are used.
1493 if (!DL.fitsInLegalInteger(Max + 1)) {
1494 // Build chain of ORs
1495 // Transform:
1496 // memchr("abcd", C, 4) != nullptr
1497 // to:
1498 // (C == 'a' || C == 'b' || C == 'c' || C == 'd') != 0
1499 std::string SortedStr = Str.str();
1500 llvm::sort(SortedStr);
1501 // Compute the number of of non-contiguous ranges.
1502 unsigned NonContRanges = 1;
1503 for (size_t i = 1; i < SortedStr.size(); ++i) {
1504 if (SortedStr[i] > SortedStr[i - 1] + 1) {
1505 NonContRanges++;
1506 }
1507 }
1508
1509 // Restrict this optimization to profitable cases with one or two range
1510 // checks.
1511 if (NonContRanges > 2)
1512 return nullptr;
1513
1514 // Slice off the character's high end bits.
1515 CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1516
1517 SmallVector<Value *> CharCompares;
1518 for (unsigned char C : SortedStr)
1519 CharCompares.push_back(B.CreateICmpEQ(CharVal, B.getInt8(C)));
1520
1521 return B.CreateIntToPtr(B.CreateOr(CharCompares), CI->getType());
1522 }
1523
1524 // For the bit field use a power-of-2 type with at least 8 bits to avoid
1525 // creating unnecessary illegal types.
1526 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
1527
1528 // Now build the bit field.
1529 APInt Bitfield(Width, 0);
1530 for (char C : Str)
1531 Bitfield.setBit((unsigned char)C);
1532 Value *BitfieldC = B.getInt(Bitfield);
1533
1534 // Adjust width of "C" to the bitfield width, then mask off the high bits.
1535 Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType());
1536 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
1537
1538 // First check that the bit field access is within bounds.
1539 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
1540 "memchr.bounds");
1541
1542 // Create code that checks if the given bit is set in the field.
1543 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
1544 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
1545
1546 // Finally merge both checks and cast to pointer type. The inttoptr
1547 // implicitly zexts the i1 to intptr type.
1548 Value *Memchr = B.CreateLogicalAnd(Bounds, Bits, "memchr");
1549 // We construct an and between the value of the memory and the bytes to search
1550 // for. We cannot infer how often this would be true without value profiling
1551 // for the query, so mark the profile unknown.
1552 if (auto *SI = dyn_cast<SelectInst>(Memchr))
1554 return B.CreateIntToPtr(Memchr, CI->getType());
1555}
1556
1557// Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
1558// arrays LHS and RHS and nonconstant Size.
1560 Value *Size, bool StrNCmp,
1561 IRBuilderBase &B, const DataLayout &DL) {
1562 if (LHS == RHS) // memcmp(s,s,x) -> 0
1563 return Constant::getNullValue(CI->getType());
1564
1565 StringRef LStr, RStr;
1566 if (!getConstantStringInfo(LHS, LStr, /*TrimAtNul=*/false) ||
1567 !getConstantStringInfo(RHS, RStr, /*TrimAtNul=*/false))
1568 return nullptr;
1569
1570 // If the contents of both constant arrays are known, fold a call to
1571 // memcmp(A, B, N) to
1572 // N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0)
1573 // where Pos is the first mismatch between A and B, determined below.
1574
1575 uint64_t Pos = 0;
1576 Value *Zero = ConstantInt::get(CI->getType(), 0);
1577 for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) {
1578 if (Pos == MinSize ||
1579 (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) {
1580 // One array is a leading part of the other of equal or greater
1581 // size, or for strncmp, the arrays are equal strings.
1582 // Fold the result to zero. Size is assumed to be in bounds, since
1583 // otherwise the call would be undefined.
1584 return Zero;
1585 }
1586
1587 if (LStr[Pos] != RStr[Pos])
1588 break;
1589 }
1590
1591 // Normalize the result.
1592 typedef unsigned char UChar;
1593 int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
1594 Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
1595 Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
1596 Value *Res = ConstantInt::getSigned(CI->getType(), IRes);
1597 return B.CreateSelect(Cmp, Zero, Res);
1598}
1599
1600// Optimize a memcmp call CI with constant size Len.
1602 uint64_t Len, IRBuilderBase &B,
1603 const DataLayout &DL) {
1604 if (Len == 0) // memcmp(s1,s2,0) -> 0
1605 return Constant::getNullValue(CI->getType());
1606
1607 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1608 if (Len == 1) {
1609 Value *LHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), LHS, "lhsc"),
1610 CI->getType(), "lhsv");
1611 Value *RHSV = B.CreateZExt(B.CreateLoad(B.getInt8Ty(), RHS, "rhsc"),
1612 CI->getType(), "rhsv");
1613 return B.CreateSub(LHSV, RHSV, "chardiff");
1614 }
1615
1616 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
1617 // TODO: The case where both inputs are constants does not need to be limited
1618 // to legal integers or equality comparison. See block below this.
1619 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
1620 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1621 Align PrefAlignment = DL.getPrefTypeAlign(IntType);
1622
1623 // First, see if we can fold either argument to a constant.
1624 Value *LHSV = nullptr;
1625 if (auto *LHSC = dyn_cast<Constant>(LHS))
1626 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1627
1628 Value *RHSV = nullptr;
1629 if (auto *RHSC = dyn_cast<Constant>(RHS))
1630 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1631
1632 // Don't generate unaligned loads. If either source is constant data,
1633 // alignment doesn't matter for that source because there is no load.
1634 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1635 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1636 if (!LHSV)
1637 LHSV = B.CreateLoad(IntType, LHS, "lhsv");
1638 if (!RHSV)
1639 RHSV = B.CreateLoad(IntType, RHS, "rhsv");
1640 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
1641 }
1642 }
1643
1644 return nullptr;
1645}
1646
1647// Most simplifications for memcmp also apply to bcmp.
1648Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1649 IRBuilderBase &B) {
1650 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1651 Value *Size = CI->getArgOperand(2);
1652
1653 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1654
1655 if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL))
1656 return Res;
1657
1658 // Handle constant Size.
1659 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1660 if (!LenC)
1661 return nullptr;
1662
1663 return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL);
1664}
1665
1666Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
1667 Module *M = CI->getModule();
1668 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1669 return V;
1670
1671 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
1672 // bcmp can be more efficient than memcmp because it only has to know that
1673 // there is a difference, not how different one is to the other.
1674 if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) &&
1676 Value *LHS = CI->getArgOperand(0);
1677 Value *RHS = CI->getArgOperand(1);
1678 Value *Size = CI->getArgOperand(2);
1679 return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
1680 }
1681
1682 return nullptr;
1683}
1684
1685Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
1686 return optimizeMemCmpBCmpCommon(CI, B);
1687}
1688
1689Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
1690 Value *Size = CI->getArgOperand(2);
1691 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1692 if (isa<IntrinsicInst>(CI))
1693 return nullptr;
1694
1695 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
1696 CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
1697 CI->getArgOperand(1), Align(1), Size);
1698 mergeAttributesAndFlags(NewCI, *CI);
1699 return CI->getArgOperand(0);
1700}
1701
1702Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
1703 Value *Dst = CI->getArgOperand(0);
1704 Value *Src = CI->getArgOperand(1);
1705 ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1706 ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
1707 StringRef SrcStr;
1708 if (CI->use_empty() && Dst == Src)
1709 return Dst;
1710 // memccpy(d, s, c, 0) -> nullptr
1711 if (N) {
1712 if (N->isNullValue())
1713 return Constant::getNullValue(CI->getType());
1714 if (!getConstantStringInfo(Src, SrcStr, /*TrimAtNul=*/false) ||
1715 // TODO: Handle zeroinitializer.
1716 !StopChar)
1717 return nullptr;
1718 } else {
1719 return nullptr;
1720 }
1721
1722 // Wrap arg 'c' of type int to char
1723 size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
1724 if (Pos == StringRef::npos) {
1725 if (N->getZExtValue() <= SrcStr.size()) {
1726 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
1727 CI->getArgOperand(3)));
1728 return Constant::getNullValue(CI->getType());
1729 }
1730 return nullptr;
1731 }
1732
1733 Value *NewN =
1734 ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
1735 // memccpy -> llvm.memcpy
1736 copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
1737 return Pos + 1 <= N->getZExtValue()
1738 ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
1740}
1741
1742Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
1743 Value *Dst = CI->getArgOperand(0);
1744 Value *N = CI->getArgOperand(2);
1745 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1746 CallInst *NewCI =
1747 B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
1748 // Propagate attributes, but memcpy has no return value, so make sure that
1749 // any return attributes are compliant.
1750 // TODO: Attach return value attributes to the 1st operand to preserve them?
1751 mergeAttributesAndFlags(NewCI, *CI);
1752 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1753}
1754
1755Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
1756 Value *Size = CI->getArgOperand(2);
1757 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1758 if (isa<IntrinsicInst>(CI))
1759 return nullptr;
1760
1761 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1762 CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
1763 CI->getArgOperand(1), Align(1), Size);
1764 mergeAttributesAndFlags(NewCI, *CI);
1765 return CI->getArgOperand(0);
1766}
1767
1768Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
1769 Value *Size = CI->getArgOperand(2);
1771 if (isa<IntrinsicInst>(CI))
1772 return nullptr;
1773
1774 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1775 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1776 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
1777 mergeAttributesAndFlags(NewCI, *CI);
1778 return CI->getArgOperand(0);
1779}
1780
1781Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
1783 Value *Malloc = emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1784 if (auto *MallocCI = dyn_cast_or_null<CallInst>(Malloc))
1785 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alloc_token))
1786 MallocCI->setMetadata(LLVMContext::MD_alloc_token, MD);
1787 return copyFlags(*CI, Malloc);
1788 }
1789
1790 return nullptr;
1791}
1792
1793// Optionally allow optimization of nobuiltin calls to operator new and its
1794// variants.
1795Value *LibCallSimplifier::maybeOptimizeNoBuiltinOperatorNew(CallInst *CI,
1796 IRBuilderBase &B) {
1797 if (!OptimizeHotColdNew)
1798 return nullptr;
1800 if (!Callee)
1801 return nullptr;
1802 LibFunc Func = TLI->getLibFunc(*Callee);
1803 if (Func == NotLibFunc)
1804 return nullptr;
1805 switch (Func) {
1806 case LibFunc_Znwm:
1807 case LibFunc_ZnwmRKSt9nothrow_t:
1808 case LibFunc_ZnwmSt11align_val_t:
1809 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1810 case LibFunc_Znam:
1811 case LibFunc_ZnamRKSt9nothrow_t:
1812 case LibFunc_ZnamSt11align_val_t:
1813 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
1814 case LibFunc_size_returning_new:
1815 case LibFunc_size_returning_new_aligned:
1816 // By default normal operator new calls (not already passing a hot_cold_t
1817 // parameter) are not mutated if the call is not marked builtin. Optionally
1818 // enable that in cases where it is known to be safe.
1820 return nullptr;
1821 break;
1822 case LibFunc_Znwm12__hot_cold_t:
1823 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1824 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1825 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1826 case LibFunc_Znam12__hot_cold_t:
1827 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1828 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1829 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1830 case LibFunc_size_returning_new_hot_cold:
1831 case LibFunc_size_returning_new_aligned_hot_cold:
1832 // If the nobuiltin call already passes a hot_cold_t parameter, allow update
1833 // of that parameter when enabled.
1835 return nullptr;
1836 break;
1837 default:
1838 return nullptr;
1839 }
1840 return optimizeNew(CI, B, Func);
1841}
1842
1843// When enabled, replace operator new() calls marked with a hot or cold memprof
1844// attribute with an operator new() call that takes a __hot_cold_t parameter.
1845// Currently this is supported by the open source version of tcmalloc, see:
1846// https://github.com/google/tcmalloc/blob/master/tcmalloc/new_extension.h
1847Value *LibCallSimplifier::optimizeNew(CallInst *CI, IRBuilderBase &B,
1848 LibFunc &Func) {
1849 if (!OptimizeHotColdNew)
1850 return nullptr;
1851
1852 uint8_t HotCold;
1853 bool IsCold = false;
1854 if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "cold") {
1855 HotCold = ColdNewHintValue;
1856 IsCold = true;
1857 } else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1858 "notcold")
1859 HotCold = NotColdNewHintValue;
1860 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() == "hot")
1861 HotCold = HotNewHintValue;
1862 else if (CI->getAttributes().getFnAttr("memprof").getValueAsString() ==
1863 "ambiguous")
1864 HotCold = AmbiguousNewHintValue;
1865 else
1866 return nullptr;
1867
1868 bool ShouldOptimizeExistingHotColdNew =
1871 IsCold);
1872
1873 Value *HotColdVal = B.getInt8(HotCold);
1874 auto getHotColdHintForExisting = [&](uint8_t HotCold) -> Value * {
1875 // If not taking the minimum, simply use the compiler hint value.
1877 return HotColdVal;
1878 Value *ExistingHint = CI->getArgOperand(CI->arg_size() - 1);
1879 if (ExistingHint->getType() != B.getInt8Ty())
1880 ExistingHint = B.CreateTruncOrBitCast(ExistingHint, B.getInt8Ty());
1881 // Emit a umin intrinsic to take the minimum of the existing hint and the
1882 // compiler hint. When the existing hint is a compile-time constant, the
1883 // IRBuilder folder will automatically constant-fold this into a constant.
1884 return B.CreateBinaryIntrinsic(Intrinsic::umin, ExistingHint, HotColdVal);
1885 };
1886
1887 // For calls that already pass a hot/cold hint, only update the hint if
1888 // directed by OptimizeExistingHotColdNew. For other calls to new, add a hint
1889 // if cold or hot, and leave as-is for default handling if "notcold" aka warm.
1890 // Note that in cases where we decide it is "notcold", it might be slightly
1891 // better to replace the hinted call with a non hinted call, to avoid the
1892 // extra parameter and the if condition check of the hint value in the
1893 // allocator. This can be considered in the future.
1894 Value *NewCall = nullptr;
1895 switch (Func) {
1896 case LibFunc_Znwm12__hot_cold_t:
1897 if (ShouldOptimizeExistingHotColdNew)
1898 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1899 LibFunc_Znwm12__hot_cold_t,
1900 getHotColdHintForExisting(HotCold));
1901 break;
1902 case LibFunc_Znwm:
1903 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1904 LibFunc_Znwm12__hot_cold_t, HotColdVal);
1905 break;
1906 case LibFunc_Znam12__hot_cold_t:
1907 if (ShouldOptimizeExistingHotColdNew)
1908 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1909 LibFunc_Znam12__hot_cold_t,
1910 getHotColdHintForExisting(HotCold));
1911 break;
1912 case LibFunc_Znam:
1913 NewCall = emitHotColdNew(CI->getArgOperand(0), B, TLI,
1914 LibFunc_Znam12__hot_cold_t, HotColdVal);
1915 break;
1916 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
1917 if (ShouldOptimizeExistingHotColdNew)
1918 NewCall =
1920 TLI, LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t,
1921 getHotColdHintForExisting(HotCold));
1922 break;
1923 case LibFunc_ZnwmRKSt9nothrow_t:
1924 NewCall = emitHotColdNewNoThrow(
1925 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1926 LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t, HotColdVal);
1927 break;
1928 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
1929 if (ShouldOptimizeExistingHotColdNew)
1930 NewCall =
1932 TLI, LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t,
1933 getHotColdHintForExisting(HotCold));
1934 break;
1935 case LibFunc_ZnamRKSt9nothrow_t:
1936 NewCall = emitHotColdNewNoThrow(
1937 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1938 LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t, HotColdVal);
1939 break;
1940 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
1941 if (ShouldOptimizeExistingHotColdNew)
1942 NewCall =
1944 TLI, LibFunc_ZnwmSt11align_val_t12__hot_cold_t,
1945 getHotColdHintForExisting(HotCold));
1946 break;
1947 case LibFunc_ZnwmSt11align_val_t:
1948 NewCall = emitHotColdNewAligned(
1949 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1950 LibFunc_ZnwmSt11align_val_t12__hot_cold_t, HotColdVal);
1951 break;
1952 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
1953 if (ShouldOptimizeExistingHotColdNew)
1954 NewCall =
1956 TLI, LibFunc_ZnamSt11align_val_t12__hot_cold_t,
1957 getHotColdHintForExisting(HotCold));
1958 break;
1959 case LibFunc_ZnamSt11align_val_t:
1960 NewCall = emitHotColdNewAligned(
1961 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
1962 LibFunc_ZnamSt11align_val_t12__hot_cold_t, HotColdVal);
1963 break;
1964 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1965 if (ShouldOptimizeExistingHotColdNew)
1967 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1968 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1969 getHotColdHintForExisting(HotCold));
1970 break;
1971 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
1973 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1974 TLI, LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1975 HotColdVal);
1976 break;
1977 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
1978 if (ShouldOptimizeExistingHotColdNew)
1980 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1981 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1982 getHotColdHintForExisting(HotCold));
1983 break;
1984 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
1986 CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2), B,
1987 TLI, LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t,
1988 HotColdVal);
1989 break;
1990 case LibFunc_size_returning_new:
1991 NewCall = emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI,
1992 LibFunc_size_returning_new_hot_cold,
1993 HotColdVal);
1994 break;
1995 case LibFunc_size_returning_new_hot_cold:
1996 if (ShouldOptimizeExistingHotColdNew)
1997 NewCall = emitHotColdSizeReturningNew(CI->getArgOperand(0), B, TLI,
1998 LibFunc_size_returning_new_hot_cold,
1999 getHotColdHintForExisting(HotCold));
2000 break;
2001 case LibFunc_size_returning_new_aligned:
2003 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
2004 LibFunc_size_returning_new_aligned_hot_cold, HotColdVal);
2005 break;
2006 case LibFunc_size_returning_new_aligned_hot_cold:
2007 if (ShouldOptimizeExistingHotColdNew)
2009 CI->getArgOperand(0), CI->getArgOperand(1), B, TLI,
2010 LibFunc_size_returning_new_aligned_hot_cold,
2011 getHotColdHintForExisting(HotCold));
2012 break;
2013 default:
2014 return nullptr;
2015 }
2016
2017 if (auto *NewCI = dyn_cast_or_null<Instruction>(NewCall))
2018 NewCI->copyMetadata(*CI);
2019
2020 return NewCall;
2021}
2022
2023//===----------------------------------------------------------------------===//
2024// Math Library Optimizations
2025//===----------------------------------------------------------------------===//
2026
2027/// Preserve the accuracy requirement of \p Old on the replacement \p New.
2028static void copyFPMath(const CallInst &Old, Value *New) {
2029 if (auto *NewI = dyn_cast<Instruction>(New))
2030 if (MDNode *MD = Old.getMetadata(LLVMContext::MD_fpmath))
2031 NewI->setMetadata(LLVMContext::MD_fpmath, MD);
2032}
2033
2034// Replace a libcall \p CI with a call to intrinsic \p IID
2036 Intrinsic::ID IID) {
2037 Value *NewCall = B.CreateUnaryIntrinsic(IID, CI->getArgOperand(0), CI);
2038 NewCall->takeName(CI);
2039 copyFPMath(*CI, NewCall);
2040 return copyFlags(*CI, NewCall);
2041}
2042
2044 Intrinsic::ID IID) {
2045 Value *NewCall = B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
2046 CI->getArgOperand(1), CI);
2047 NewCall->takeName(CI);
2048 copyFPMath(*CI, NewCall);
2049 return copyFlags(*CI, NewCall);
2050}
2051
2052/// Return a variant of Val with float type.
2053/// Currently this works in two cases: If Val is an FPExtension of a float
2054/// value to something bigger, simply return the operand.
2055/// If Val is a ConstantFP but can be converted to a float ConstantFP without
2056/// loss of precision do so.
2058 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
2059 Value *Op = Cast->getOperand(0);
2060 if (Op->getType()->isFloatTy())
2061 return Op;
2062 }
2063 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
2064 APFloat F = Const->getValueAPF();
2065 bool losesInfo;
2067 &losesInfo);
2068 if (!losesInfo)
2069 return ConstantFP::get(Const->getContext(), F);
2070 }
2071 return nullptr;
2072}
2073
2074/// Shrink double -> float functions.
2076 bool isBinary, const TargetLibraryInfo *TLI,
2077 bool isPrecise = false) {
2078 Function *CalleeFn = CI->getCalledFunction();
2079 if (!CI->getType()->isDoubleTy() || !CalleeFn)
2080 return nullptr;
2081
2082 // If not all the uses of the function are converted to float, then bail out.
2083 // This matters if the precision of the result is more important than the
2084 // precision of the arguments.
2085 if (isPrecise)
2086 for (User *U : CI->users()) {
2088 if (!Cast || !Cast->getType()->isFloatTy())
2089 return nullptr;
2090 }
2091
2092 // If this is something like 'g((double) float)', convert to 'gf(float)'.
2093 Value *V[2];
2095 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
2096 if (!V[0] || (isBinary && !V[1]))
2097 return nullptr;
2098
2099 // If call isn't an intrinsic, check that it isn't within a function with the
2100 // same name as the float version of this call, otherwise the result is an
2101 // infinite loop. For example, from MinGW-w64:
2102 //
2103 // float expf(float val) { return (float) exp((double) val); }
2104 StringRef CalleeName = CalleeFn->getName();
2105 bool IsIntrinsic = CalleeFn->isIntrinsic();
2106 if (!IsIntrinsic) {
2107 StringRef CallerName = CI->getFunction()->getName();
2108 if (CallerName.ends_with('f') &&
2109 CallerName.size() == (CalleeName.size() + 1) &&
2110 CallerName.starts_with(CalleeName))
2111 return nullptr;
2112 }
2113
2114 // Propagate the math semantics from the current function to the new function.
2116 B.setFastMathFlags(CI->getFastMathFlags());
2117
2118 // g((double) float) -> (double) gf(float)
2119 Value *R;
2120 if (IsIntrinsic) {
2121 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
2122 R = isBinary ? B.CreateIntrinsic(IID, B.getFloatTy(), V)
2123 : B.CreateIntrinsic(IID, B.getFloatTy(), V[0]);
2124 } else {
2125 AttributeList CallsiteAttrs = CI->getAttributes();
2126 R = isBinary
2127 ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B,
2128 CallsiteAttrs)
2129 : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CallsiteAttrs);
2130 }
2131 return B.CreateFPExt(R, B.getDoubleTy());
2132}
2133
2134/// Shrink double -> float for unary functions.
2136 const TargetLibraryInfo *TLI,
2137 bool isPrecise = false) {
2138 return optimizeDoubleFP(CI, B, false, TLI, isPrecise);
2139}
2140
2141/// Shrink double -> float for binary functions.
2143 const TargetLibraryInfo *TLI,
2144 bool isPrecise = false) {
2145 return optimizeDoubleFP(CI, B, true, TLI, isPrecise);
2146}
2147
2148/// Shrink double -> float for llvm.sincos.
2150 auto *RetTy = dyn_cast<StructType>(CI->getType());
2151 if (!RetTy || RetTy->getNumElements() != 2 ||
2152 !RetTy->getElementType(0)->getScalarType()->isDoubleTy())
2153 return nullptr;
2154
2156 if (!X)
2157 if (auto *Ext = dyn_cast<FPExtInst>(CI->getArgOperand(0)))
2158 if (Ext->getOperand(0)->getType()->getScalarType()->isFloatTy())
2159 X = Ext->getOperand(0);
2160 if (!X)
2161 return nullptr;
2162
2163 for (User *U : CI->users()) {
2164 auto *EV = dyn_cast<ExtractValueInst>(U);
2165 if (!EV)
2166 return nullptr;
2167 for (User *EVU : EV->users()) {
2168 auto *Cast = dyn_cast<FPTruncInst>(EVU);
2169 if (!Cast || !Cast->getType()->getScalarType()->isFloatTy())
2170 return nullptr;
2171 }
2172 }
2173
2175 B.setFastMathFlags(CI->getFastMathFlags());
2176
2177 Value *NewCall = B.CreateIntrinsic(Intrinsic::sincos, X->getType(), X);
2178 cast<Instruction>(NewCall)->setMetadata(
2179 LLVMContext::MD_fpmath, CI->getMetadata(LLVMContext::MD_fpmath));
2180 Value *Res = PoisonValue::get(RetTy);
2181 for (unsigned I = 0; I != 2; ++I) {
2182 Value *Ext = B.CreateFPExt(B.CreateExtractValue(NewCall, I),
2183 RetTy->getElementType(I));
2184 Res = B.CreateInsertValue(Res, Ext, I);
2185 }
2186 return Res;
2187}
2188
2189// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
2190Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
2191 Value *Real, *Imag;
2192
2193 if (CI->arg_size() == 1) {
2194
2195 if (!CI->isFast())
2196 return nullptr;
2197
2198 Value *Op = CI->getArgOperand(0);
2199 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
2200
2201 Real = B.CreateExtractValue(Op, 0, "real");
2202 Imag = B.CreateExtractValue(Op, 1, "imag");
2203
2204 } else {
2205 assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
2206
2207 Real = CI->getArgOperand(0);
2208 Imag = CI->getArgOperand(1);
2209
2210 // if real or imaginary part is zero, simplify to abs(cimag(z))
2211 // or abs(creal(z))
2212 Value *AbsOp = nullptr;
2213 if (ConstantFP *ConstReal = dyn_cast<ConstantFP>(Real)) {
2214 if (ConstReal->isZero())
2215 AbsOp = Imag;
2216
2217 } else if (ConstantFP *ConstImag = dyn_cast<ConstantFP>(Imag)) {
2218 if (ConstImag->isZero())
2219 AbsOp = Real;
2220 }
2221
2222 if (AbsOp)
2223 return copyFlags(*CI, B.CreateFAbs(AbsOp, CI, "cabs"));
2224
2225 if (!CI->isFast())
2226 return nullptr;
2227 }
2228
2229 // Propagate fast-math flags from the existing call to new instructions.
2230 Value *RealReal = B.CreateFMulFMF(Real, Real, CI);
2231 Value *ImagImag = B.CreateFMulFMF(Imag, Imag, CI);
2232 return copyFlags(
2233 *CI, B.CreateUnaryIntrinsic(Intrinsic::sqrt,
2234 B.CreateFAddFMF(RealReal, ImagImag, CI), CI,
2235 "cabs"));
2236}
2237
2238// Return a properly extended integer (DstWidth bits wide) if the operation is
2239// an itofp.
2240static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
2241 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
2242 Value *Op = cast<Instruction>(I2F)->getOperand(0);
2243 // Make sure that the exponent fits inside an "int" of size DstWidth,
2244 // thus avoiding any range issues that FP has not.
2245 unsigned BitWidth = Op->getType()->getScalarSizeInBits();
2246 if (BitWidth < DstWidth || (BitWidth == DstWidth && isa<SIToFPInst>(I2F))) {
2247 Type *IntTy = Op->getType()->getWithNewBitWidth(DstWidth);
2248 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, IntTy)
2249 : B.CreateZExt(Op, IntTy);
2250 }
2251 }
2252
2253 return nullptr;
2254}
2255
2256/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
2257/// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
2258/// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
2259Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
2260 Module *M = Pow->getModule();
2261 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2262 Type *Ty = Pow->getType();
2263 bool Ignored;
2264
2265 // Evaluate special cases related to a nested function as the base.
2266
2267 // pow(exp(x), y) -> exp(x * y)
2268 // pow(exp2(x), y) -> exp2(x * y)
2269 // If exp{,2}() is used only once, it is better to fold two transcendental
2270 // math functions into one. If used again, exp{,2}() would still have to be
2271 // called with the original argument, then keep both original transcendental
2272 // functions. However, this transformation is only safe with fully relaxed
2273 // math semantics, since, besides rounding differences, it changes overflow
2274 // and underflow behavior quite dramatically. For example:
2275 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
2276 // Whereas:
2277 // exp(1000 * 0.001) = exp(1)
2278 // TODO: Loosen the requirement for fully relaxed math semantics.
2279 // TODO: Handle exp10() when more targets have it available.
2280 CallInst *BaseFn = dyn_cast<CallInst>(Base);
2281 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
2282 Function *CalleeFn = BaseFn->getCalledFunction();
2283 LibFunc LibFn =
2284 CalleeFn ? TLI->getLibFunc(CalleeFn->getName()) : NotLibFunc;
2285 if (isLibFuncEmittable(M, TLI, LibFn)) {
2286 StringRef ExpName;
2288 Value *ExpFn;
2289 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
2290
2291 switch (LibFn) {
2292 default:
2293 return nullptr;
2294 case LibFunc_expf:
2295 case LibFunc_exp:
2296 case LibFunc_expl:
2297 ExpName = TLI->getName(LibFunc_exp);
2298 ID = Intrinsic::exp;
2299 LibFnFloat = LibFunc_expf;
2300 LibFnDouble = LibFunc_exp;
2301 LibFnLongDouble = LibFunc_expl;
2302 break;
2303 case LibFunc_exp2f:
2304 case LibFunc_exp2:
2305 case LibFunc_exp2l:
2306 ExpName = TLI->getName(LibFunc_exp2);
2307 ID = Intrinsic::exp2;
2308 LibFnFloat = LibFunc_exp2f;
2309 LibFnDouble = LibFunc_exp2;
2310 LibFnLongDouble = LibFunc_exp2l;
2311 break;
2312 }
2313
2314 // Create new exp{,2}() with the product as its argument.
2315 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
2316 ExpFn = BaseFn->doesNotAccessMemory()
2317 ? B.CreateUnaryIntrinsic(ID, FMul, nullptr, ExpName)
2318 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
2319 LibFnLongDouble, B,
2320 BaseFn->getAttributes());
2321
2322 // Since the new exp{,2}() is different from the original one, dead code
2323 // elimination cannot be trusted to remove it, since it may have side
2324 // effects (e.g., errno). When the only consumer for the original
2325 // exp{,2}() is pow(), then it has to be explicitly erased.
2326 substituteInParent(BaseFn, ExpFn);
2327 return ExpFn;
2328 }
2329 }
2330
2331 // Evaluate special cases related to a constant base.
2332
2333 const APFloat *BaseF;
2334 if (!match(Base, m_APFloat(BaseF)))
2335 return nullptr;
2336
2337 AttributeList NoAttrs; // Attributes are only meaningful on the original call
2338
2339 const bool UseIntrinsic = Pow->doesNotAccessMemory();
2340
2341 // pow(2.0, itofp(x)) -> ldexp(1.0, x)
2342 if ((UseIntrinsic || !Ty->isVectorTy()) && BaseF->isExactlyValue(2.0) &&
2343 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
2344 (UseIntrinsic ||
2345 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2346
2347 // TODO: Shouldn't really need to depend on getIntToFPVal for intrinsic. Can
2348 // just directly use the original integer type.
2349 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize())) {
2350 Constant *One = ConstantFP::get(Ty, 1.0);
2351
2352 if (UseIntrinsic) {
2353 return copyFlags(*Pow, B.CreateIntrinsic(Intrinsic::ldexp,
2354 {Ty, ExpoI->getType()},
2355 {One, ExpoI}, Pow, "exp2"));
2356 }
2357
2359 One, ExpoI, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2360 LibFunc_ldexpl, B, NoAttrs));
2361 }
2362 }
2363
2364 // pow(2.0 ** n, x) -> exp2(n * x)
2365 if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
2366 APFloat BaseR = APFloat(1.0);
2367 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
2368 BaseR = BaseR / *BaseF;
2369 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
2370 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
2371 APSInt NI(64, false);
2372 if ((IsInteger || IsReciprocal) &&
2373 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
2374 APFloat::opOK &&
2375 NI > 1 && NI.isPowerOf2()) {
2376 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
2377 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
2378 if (Pow->doesNotAccessMemory())
2379 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2380 nullptr, "exp2"));
2381 else
2382 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2383 LibFunc_exp2f,
2384 LibFunc_exp2l, B, NoAttrs));
2385 }
2386 }
2387
2388 // pow(10.0, x) -> exp10(x)
2389 if (BaseF->isExactlyValue(10.0) &&
2390 hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l)) {
2391
2392 if (Pow->doesNotAccessMemory()) {
2393 return B.CreateIntrinsic(Intrinsic::exp10, {Ty}, {Expo}, Pow, "exp10", {},
2394 [Pow](CallInst *CI) { CI->copyIRFlags(Pow); });
2395 }
2396
2397 return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
2398 LibFunc_exp10f, LibFunc_exp10l,
2399 B, NoAttrs));
2400 }
2401
2402 // pow(x, y) -> exp2(log2(x) * y)
2403 if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
2404 !BaseF->isNegative()) {
2405 // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
2406 // Luckily optimizePow has already handled the x == 1 case.
2407 assert(!match(Base, m_FPOne()) &&
2408 "pow(1.0, y) should have been simplified earlier!");
2409
2410 Value *Log = nullptr;
2411 if (Ty->isFloatTy())
2412 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
2413 else if (Ty->isDoubleTy())
2414 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
2415
2416 if (Log) {
2417 Value *FMul = B.CreateFMul(Log, Expo, "mul");
2418 if (Pow->doesNotAccessMemory())
2419 return copyFlags(*Pow, B.CreateUnaryIntrinsic(Intrinsic::exp2, FMul,
2420 nullptr, "exp2"));
2421 else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f,
2422 LibFunc_exp2l))
2423 return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
2424 LibFunc_exp2f,
2425 LibFunc_exp2l, B, NoAttrs));
2426 }
2427 }
2428
2429 return nullptr;
2430}
2431
2432static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
2433 Module *M, IRBuilderBase &B,
2434 const TargetLibraryInfo *TLI) {
2435 // If errno is never set, then use the intrinsic for sqrt().
2436 if (NoErrno)
2437 return B.CreateUnaryIntrinsic(Intrinsic::sqrt, V, nullptr, "sqrt");
2438
2439 // Otherwise, use the libcall for sqrt().
2440 if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
2441 LibFunc_sqrtl))
2442 // TODO: We also should check that the target can in fact lower the sqrt()
2443 // libcall. We currently have no way to ask this question, so we ask if
2444 // the target has a sqrt() libcall, which is not exactly the same.
2445 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
2446 LibFunc_sqrtl, B, Attrs);
2447
2448 return nullptr;
2449}
2450
2451/// Use square root in place of pow(x, +/-0.5).
2452Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
2453 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
2454 Module *Mod = Pow->getModule();
2455 Type *Ty = Pow->getType();
2456
2457 const APFloat *ExpoF;
2458 if (!match(Expo, m_APFloat(ExpoF)) ||
2459 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
2460 return nullptr;
2461
2462 // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
2463 // so that requires fast-math-flags (afn or reassoc).
2464 if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
2465 return nullptr;
2466
2467 // If we have a pow() library call (accesses memory) and we can't guarantee
2468 // that the base is not an infinity, give up:
2469 // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
2470 // errno), but sqrt(-Inf) is required by various standards to set errno.
2471 if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
2473 Base, SimplifyQuery(DL, TLI, DT, AC, Pow, true, true, DC)))
2474 return nullptr;
2475
2476 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), Mod, B,
2477 TLI);
2478 if (!Sqrt)
2479 return nullptr;
2480
2481 // Handle signed zero base by expanding to fabs(sqrt(x)).
2482 if (!Pow->hasNoSignedZeros())
2483 Sqrt = B.CreateFAbs(Sqrt, nullptr, "abs");
2484
2485 Sqrt = copyFlags(*Pow, Sqrt);
2486
2487 // Handle non finite base by expanding to
2488 // (x == -infinity ? +infinity : sqrt(x)).
2489 if (!Pow->hasNoInfs()) {
2490 Value *PosInf = ConstantFP::getInfinity(Ty),
2491 *NegInf = ConstantFP::getInfinity(Ty, true);
2492 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
2493 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
2494 // We assume that the case where x == -infinity is unlikely, so we assign
2495 // unlikely branch weights to that arm of the select.
2497 if (auto *SqrtSI = dyn_cast<SelectInst>(Sqrt))
2499 *SqrtSI,
2501 /*IsExpected=*/false);
2502 }
2503 }
2504
2505 // If the exponent is negative, then get the reciprocal.
2506 if (ExpoF->isNegative())
2507 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
2508
2509 return Sqrt;
2510}
2511
2513 IRBuilderBase &B) {
2514 Value *Args[] = {Base, Expo};
2515 Type *Types[] = {Base->getType(), Expo->getType()};
2516 return B.CreateIntrinsic(Intrinsic::powi, Types, Args);
2517}
2518
2519Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
2520 Value *Base = Pow->getArgOperand(0);
2521 Value *Expo = Pow->getArgOperand(1);
2522 Function *Callee = Pow->getCalledFunction();
2523 StringRef Name = Callee->getName();
2524 Type *Ty = Pow->getType();
2525 Module *M = Pow->getModule();
2526 bool AllowApprox = Pow->hasApproxFunc();
2527 bool Ignored;
2528
2529 // Propagate the math semantics from the call to any created instructions.
2530 IRBuilderBase::FastMathFlagGuard Guard(B);
2531 B.setFastMathFlags(Pow->getFastMathFlags());
2532 // Evaluate special cases related to the base.
2533
2534 // pow(1.0, x) -> 1.0
2535 if (match(Base, m_FPOne()))
2536 return Base;
2537
2538 if (Value *Exp = replacePowWithExp(Pow, B))
2539 return Exp;
2540
2541 // Evaluate special cases related to the exponent.
2542
2543 // pow(x, -1.0) -> 1.0 / x
2544 if (match(Expo, m_SpecificFP(-1.0)))
2545 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
2546
2547 // pow(x, +/-0.0) -> 1.0
2548 if (match(Expo, m_AnyZeroFP()))
2549 return ConstantFP::get(Ty, 1.0);
2550
2551 // pow(x, 1.0) -> x
2552 if (match(Expo, m_FPOne()))
2553 return Base;
2554
2555 // pow(x, 2.0) -> x * x
2556 if (match(Expo, m_SpecificFP(2.0)) && Pow->doesNotAccessMemory())
2557 return B.CreateFMul(Base, Base, "square");
2558
2559 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
2560 return Sqrt;
2561
2562 // If we can approximate pow:
2563 // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction
2564 // pow(x, n) -> powi(x, n) if n is a constant signed integer value
2565 const APFloat *ExpoF;
2566 if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
2567 !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
2568 APFloat ExpoA(abs(*ExpoF));
2569 APFloat ExpoI(*ExpoF);
2570 Value *Sqrt = nullptr;
2571 if (!ExpoA.isInteger()) {
2572 APFloat Expo2 = ExpoA;
2573 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
2574 // is no floating point exception and the result is an integer, then
2575 // ExpoA == integer + 0.5
2576 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
2577 return nullptr;
2578
2579 if (!Expo2.isInteger())
2580 return nullptr;
2581
2582 if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) !=
2584 return nullptr;
2585 if (!ExpoI.isInteger())
2586 return nullptr;
2587 ExpoF = &ExpoI;
2588
2589 Sqrt = getSqrtCall(Base, AttributeList(), Pow->doesNotAccessMemory(), M,
2590 B, TLI);
2591 if (!Sqrt)
2592 return nullptr;
2593 }
2594
2595 // 0.5 fraction is now optionally handled.
2596 // Do pow -> powi for remaining integer exponent
2597 APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
2598 if (ExpoF->isInteger() &&
2599 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
2600 APFloat::opOK) {
2601 Value *PowI = copyFlags(
2602 *Pow,
2604 Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
2605 M, B));
2606
2607 if (PowI && Sqrt)
2608 return B.CreateFMul(PowI, Sqrt);
2609
2610 return PowI;
2611 }
2612 }
2613
2614 // powf(x, itofp(y)) -> powi(x, y)
2615 // The powi exponent must be a scalar integer, so a vector y is not usable.
2616 if (AllowApprox && !Expo->getType()->isVectorTy() &&
2617 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
2618 if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
2619 return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
2620 }
2621
2622 // Shrink pow() to powf() if the arguments are single precision,
2623 // unless the result is expected to be double precision.
2624 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
2625 hasFloatVersion(M, Name)) {
2626 if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
2627 return Shrunk;
2628 }
2629
2630 return nullptr;
2631}
2632
2633Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
2634 Module *M = CI->getModule();
2636 StringRef Name = Callee->getName();
2637 Value *Ret = nullptr;
2638 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
2639 hasFloatVersion(M, Name))
2640 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2641
2642 // If we have an llvm.exp2 intrinsic, emit the llvm.ldexp intrinsic. If we
2643 // have the libcall, emit the libcall.
2644 //
2645 // TODO: In principle we should be able to just always use the intrinsic for
2646 // any doesNotAccessMemory callsite.
2647
2648 const bool UseIntrinsic = Callee->isIntrinsic();
2649 // Bail out for vectors because the code below only expects scalars.
2650 Type *Ty = CI->getType();
2651 if (!UseIntrinsic && Ty->isVectorTy())
2652 return Ret;
2653
2654 // exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize
2655 // exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize
2656 Value *Op = CI->getArgOperand(0);
2657 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
2658 (UseIntrinsic ||
2659 hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl))) {
2660 if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize())) {
2661 Constant *One = ConstantFP::get(Ty, 1.0);
2662
2663 if (UseIntrinsic) {
2664 return copyFlags(*CI, B.CreateIntrinsic(Intrinsic::ldexp,
2665 {Ty, Exp->getType()},
2666 {One, Exp}, CI));
2667 }
2668
2669 IRBuilderBase::FastMathFlagGuard Guard(B);
2670 B.setFastMathFlags(CI->getFastMathFlags());
2671 return copyFlags(*CI, emitBinaryFloatFnCall(
2672 One, Exp, TLI, LibFunc_ldexp, LibFunc_ldexpf,
2673 LibFunc_ldexpl, B, AttributeList()));
2674 }
2675 }
2676
2677 return Ret;
2678}
2679
2680Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B,
2681 Intrinsic::ID IID) {
2682 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
2683 // the intrinsics for improved optimization (for example, vectorization).
2684 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
2685 // From the C standard draft WG14/N1256:
2686 // "Ideally, fmax would be sensitive to the sign of zero, for example
2687 // fmax(-0.0, +0.0) would return +0; however, implementation in software
2688 // might be impractical."
2689 FastMathFlags FMF = CI->getFastMathFlags();
2690 FMF.setNoSignedZeros();
2691 return copyFlags(*CI, B.CreateBinaryIntrinsic(IID, CI->getArgOperand(0),
2692 CI->getArgOperand(1), FMF));
2693}
2694
2695Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
2696 Function *LogFn = Log->getCalledFunction();
2697 StringRef LogNm = LogFn->getName();
2698 Intrinsic::ID LogID = LogFn->getIntrinsicID();
2699 Module *Mod = Log->getModule();
2700 Type *Ty = Log->getType();
2701
2702 if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm))
2703 if (Value *Ret = optimizeUnaryDoubleFP(Log, B, TLI, true))
2704 return Ret;
2705
2706 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2707
2708 // This is only applicable to log(), log2(), log10().
2709 LogLb = TLI->getLibFunc(LogNm);
2710 if (LogLb != NotLibFunc) {
2711 switch (LogLb) {
2712 case LibFunc_logf:
2713 LogID = Intrinsic::log;
2714 ExpLb = LibFunc_expf;
2715 Exp2Lb = LibFunc_exp2f;
2716 Exp10Lb = LibFunc_exp10f;
2717 PowLb = LibFunc_powf;
2718 break;
2719 case LibFunc_log:
2720 LogID = Intrinsic::log;
2721 ExpLb = LibFunc_exp;
2722 Exp2Lb = LibFunc_exp2;
2723 Exp10Lb = LibFunc_exp10;
2724 PowLb = LibFunc_pow;
2725 break;
2726 case LibFunc_logl:
2727 LogID = Intrinsic::log;
2728 ExpLb = LibFunc_expl;
2729 Exp2Lb = LibFunc_exp2l;
2730 Exp10Lb = LibFunc_exp10l;
2731 PowLb = LibFunc_powl;
2732 break;
2733 case LibFunc_log2f:
2734 LogID = Intrinsic::log2;
2735 ExpLb = LibFunc_expf;
2736 Exp2Lb = LibFunc_exp2f;
2737 Exp10Lb = LibFunc_exp10f;
2738 PowLb = LibFunc_powf;
2739 break;
2740 case LibFunc_log2:
2741 LogID = Intrinsic::log2;
2742 ExpLb = LibFunc_exp;
2743 Exp2Lb = LibFunc_exp2;
2744 Exp10Lb = LibFunc_exp10;
2745 PowLb = LibFunc_pow;
2746 break;
2747 case LibFunc_log2l:
2748 LogID = Intrinsic::log2;
2749 ExpLb = LibFunc_expl;
2750 Exp2Lb = LibFunc_exp2l;
2751 Exp10Lb = LibFunc_exp10l;
2752 PowLb = LibFunc_powl;
2753 break;
2754 case LibFunc_log10f:
2755 LogID = Intrinsic::log10;
2756 ExpLb = LibFunc_expf;
2757 Exp2Lb = LibFunc_exp2f;
2758 Exp10Lb = LibFunc_exp10f;
2759 PowLb = LibFunc_powf;
2760 break;
2761 case LibFunc_log10:
2762 LogID = Intrinsic::log10;
2763 ExpLb = LibFunc_exp;
2764 Exp2Lb = LibFunc_exp2;
2765 Exp10Lb = LibFunc_exp10;
2766 PowLb = LibFunc_pow;
2767 break;
2768 case LibFunc_log10l:
2769 LogID = Intrinsic::log10;
2770 ExpLb = LibFunc_expl;
2771 Exp2Lb = LibFunc_exp2l;
2772 Exp10Lb = LibFunc_exp10l;
2773 PowLb = LibFunc_powl;
2774 break;
2775 default:
2776 return nullptr;
2777 }
2778
2779 // Convert libcall to intrinsic if the value is known > 0.
2780 bool IsKnownNoErrno = Log->hasNoNaNs() && Log->hasNoInfs();
2781 if (!IsKnownNoErrno) {
2782 SimplifyQuery SQ(DL, TLI, DT, AC, Log, true, true, DC);
2783 KnownFPClass Known = computeKnownFPClass(
2784 Log->getOperand(0),
2786 Function *F = Log->getParent()->getParent();
2787 const fltSemantics &FltSem = Ty->getScalarType()->getFltSemantics();
2788 IsKnownNoErrno =
2789 Known.cannotBeOrderedLessThanZero() &&
2790 Known.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
2791 }
2792 if (IsKnownNoErrno) {
2793 Value *NewLog = B.CreateUnaryIntrinsic(LogID, Log->getArgOperand(0), Log);
2794 if (auto *I = dyn_cast<Instruction>(NewLog)) {
2795 I->copyMetadata(*Log);
2796 return copyFlags(*Log, I);
2797 }
2798 return NewLog;
2799 }
2800 } else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2801 LogID == Intrinsic::log10) {
2802 if (Ty->getScalarType()->isFloatTy()) {
2803 ExpLb = LibFunc_expf;
2804 Exp2Lb = LibFunc_exp2f;
2805 Exp10Lb = LibFunc_exp10f;
2806 PowLb = LibFunc_powf;
2807 } else if (Ty->getScalarType()->isDoubleTy()) {
2808 ExpLb = LibFunc_exp;
2809 Exp2Lb = LibFunc_exp2;
2810 Exp10Lb = LibFunc_exp10;
2811 PowLb = LibFunc_pow;
2812 } else
2813 return nullptr;
2814 } else
2815 return nullptr;
2816
2817 // The earlier call must also be 'fast' in order to do these transforms.
2818 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2819 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2820 return nullptr;
2821
2822 IRBuilderBase::FastMathFlagGuard Guard(B);
2823 B.setFastMathFlags(FastMathFlags::getFast());
2824
2825 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2826 LibFunc ArgLb = TLI->getLibFunc(*Arg);
2827
2828 // log(pow(x,y)) -> y*log(x)
2829 AttributeList NoAttrs;
2830 if (ArgLb == PowLb || ArgID == Intrinsic::pow || ArgID == Intrinsic::powi) {
2831 Value *LogX =
2832 Log->doesNotAccessMemory()
2833 ? B.CreateUnaryIntrinsic(LogID, Arg->getOperand(0), nullptr, "log")
2834 : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, NoAttrs);
2835 Value *Y = Arg->getArgOperand(1);
2836 // Cast exponent to FP if integer.
2837 if (ArgID == Intrinsic::powi)
2838 Y = B.CreateSIToFP(Y, Ty, "cast");
2839 Value *MulY = B.CreateFMul(Y, LogX, "mul");
2840 // Since pow() may have side effects, e.g. errno,
2841 // dead code elimination may not be trusted to remove it.
2842 substituteInParent(Arg, MulY);
2843 return MulY;
2844 }
2845
2846 // log(exp{,2,10}(y)) -> y*log({e,2,10})
2847 // TODO: There is no exp10() intrinsic yet.
2848 if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2849 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2850 Constant *Eul;
2851 if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2852 // FIXME: Add more precise value of e for long double.
2853 Eul = ConstantFP::get(Log->getType(), numbers::e);
2854 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2855 Eul = ConstantFP::get(Log->getType(), 2.0);
2856 else
2857 Eul = ConstantFP::get(Log->getType(), 10.0);
2858 Value *LogE = Log->doesNotAccessMemory()
2859 ? B.CreateUnaryIntrinsic(LogID, Eul, nullptr, "log")
2860 : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, NoAttrs);
2861 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2862 // Since exp() may have side effects, e.g. errno,
2863 // dead code elimination may not be trusted to remove it.
2864 substituteInParent(Arg, MulY);
2865 return MulY;
2866 }
2867
2868 return nullptr;
2869}
2870
2871// sqrt(exp(X)) -> exp(X * 0.5)
2872Value *LibCallSimplifier::mergeSqrtToExp(CallInst *CI, IRBuilderBase &B) {
2873 if (!CI->hasAllowReassoc())
2874 return nullptr;
2875
2876 Function *SqrtFn = CI->getCalledFunction();
2877 CallInst *Arg = dyn_cast<CallInst>(CI->getArgOperand(0));
2878 if (!Arg || !Arg->hasAllowReassoc() || !Arg->hasOneUse())
2879 return nullptr;
2880 Intrinsic::ID ArgID = Arg->getIntrinsicID();
2881 LibFunc ArgLb = TLI->getLibFunc(*Arg);
2882
2883 LibFunc SqrtLb, ExpLb, Exp2Lb, Exp10Lb;
2884
2885 SqrtLb = TLI->getLibFunc(SqrtFn->getName());
2886 if (SqrtLb != NotLibFunc)
2887 switch (SqrtLb) {
2888 case LibFunc_sqrtf:
2889 ExpLb = LibFunc_expf;
2890 Exp2Lb = LibFunc_exp2f;
2891 Exp10Lb = LibFunc_exp10f;
2892 break;
2893 case LibFunc_sqrt:
2894 ExpLb = LibFunc_exp;
2895 Exp2Lb = LibFunc_exp2;
2896 Exp10Lb = LibFunc_exp10;
2897 break;
2898 case LibFunc_sqrtl:
2899 ExpLb = LibFunc_expl;
2900 Exp2Lb = LibFunc_exp2l;
2901 Exp10Lb = LibFunc_exp10l;
2902 break;
2903 default:
2904 return nullptr;
2905 }
2906 else if (SqrtFn->getIntrinsicID() == Intrinsic::sqrt) {
2907 if (CI->getType()->getScalarType()->isFloatTy()) {
2908 ExpLb = LibFunc_expf;
2909 Exp2Lb = LibFunc_exp2f;
2910 Exp10Lb = LibFunc_exp10f;
2911 } else if (CI->getType()->getScalarType()->isDoubleTy()) {
2912 ExpLb = LibFunc_exp;
2913 Exp2Lb = LibFunc_exp2;
2914 Exp10Lb = LibFunc_exp10;
2915 } else
2916 return nullptr;
2917 } else
2918 return nullptr;
2919
2920 if (ArgLb != ExpLb && ArgLb != Exp2Lb && ArgLb != Exp10Lb &&
2921 ArgID != Intrinsic::exp && ArgID != Intrinsic::exp2)
2922 return nullptr;
2923
2924 IRBuilderBase::InsertPointGuard Guard(B);
2925 B.SetInsertPoint(Arg);
2926 auto *ExpOperand = Arg->getOperand(0);
2927 auto *FMul =
2928 B.CreateFMulFMF(ExpOperand, ConstantFP::get(ExpOperand->getType(), 0.5),
2929 CI, "merged.sqrt");
2930
2931 Arg->setOperand(0, FMul);
2932 return Arg;
2933}
2934
2935Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2936 Module *M = CI->getModule();
2938 Value *Ret = nullptr;
2939 // TODO: Once we have a way (other than checking for the existince of the
2940 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2941 // condition below.
2942 if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2943 (Callee->getName() == "sqrt" ||
2944 Callee->getIntrinsicID() == Intrinsic::sqrt))
2945 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2946
2947 if (Value *Opt = mergeSqrtToExp(CI, B))
2948 return Opt;
2949
2950 if (!CI->isFast())
2951 return Ret;
2952
2954 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2955 return Ret;
2956
2957 // We're looking for a repeated factor in a multiplication tree,
2958 // so we can do this fold: sqrt(x * x) -> fabs(x);
2959 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2960 Value *Op0 = I->getOperand(0);
2961 Value *Op1 = I->getOperand(1);
2962 Value *RepeatOp = nullptr;
2963 Value *OtherOp = nullptr;
2964 if (Op0 == Op1) {
2965 // Simple match: the operands of the multiply are identical.
2966 RepeatOp = Op0;
2967 } else {
2968 // Look for a more complicated pattern: one of the operands is itself
2969 // a multiply, so search for a common factor in that multiply.
2970 // Note: We don't bother looking any deeper than this first level or for
2971 // variations of this pattern because instcombine's visitFMUL and/or the
2972 // reassociation pass should give us this form.
2973 Value *MulOp;
2974 if (match(Op0, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2975 cast<Instruction>(Op0)->isFast()) {
2976 // Pattern: sqrt((x * x) * z)
2977 RepeatOp = MulOp;
2978 OtherOp = Op1;
2979 } else if (match(Op1, m_FMul(m_Value(MulOp), m_Deferred(MulOp))) &&
2980 cast<Instruction>(Op1)->isFast()) {
2981 // Pattern: sqrt(z * (x * x))
2982 RepeatOp = MulOp;
2983 OtherOp = Op0;
2984 }
2985 }
2986 if (!RepeatOp)
2987 return Ret;
2988
2989 // Fast math flags for any created instructions should match the sqrt
2990 // and multiply.
2991
2992 // If we found a repeated factor, hoist it out of the square root and
2993 // replace it with the fabs of that factor.
2994 Value *FabsCall = B.CreateFAbs(RepeatOp, I, "fabs");
2995 if (OtherOp) {
2996 // If we found a non-repeated factor, we still need to get its square
2997 // root. We then multiply that by the value that was simplified out
2998 // of the square root calculation.
2999 Value *SqrtCall =
3000 B.CreateUnaryIntrinsic(Intrinsic::sqrt, OtherOp, I, "sqrt");
3001 return copyFlags(*CI, B.CreateFMulFMF(FabsCall, SqrtCall, I));
3002 }
3003 return copyFlags(*CI, FabsCall);
3004}
3005
3006Value *LibCallSimplifier::optimizeFMod(CallInst *CI, IRBuilderBase &B) {
3007
3008 // fmod(x,y) sets errno if y == 0 or x == +/-inf. frem does not set errno,
3009 // so the fold is valid only when we can prove fmod wouldn't either.
3010 bool IsNoErrno = CI->hasNoNaNs();
3011 if (!IsNoErrno) {
3012 SimplifyQuery SQ(DL, TLI, DT, AC, CI, true, true, DC);
3013 KnownFPClass Known0 = computeKnownFPClass(CI->getOperand(0), fcInf, SQ);
3014 if (Known0.isKnownNeverInfinity()) {
3015 KnownFPClass Known1 =
3017 Function *F = CI->getParent()->getParent();
3018 const fltSemantics &FltSem =
3020 IsNoErrno = Known1.isKnownNeverLogicalZero(F->getDenormalMode(FltSem));
3021 }
3022 }
3023
3024 if (IsNoErrno)
3025 return B.CreateFRemFMF(CI->getOperand(0), CI->getOperand(1), CI);
3026 return nullptr;
3027}
3028
3029Value *LibCallSimplifier::optimizeTrigInversionPairs(CallInst *CI,
3030 IRBuilderBase &B) {
3031 Module *M = CI->getModule();
3033 Value *Ret = nullptr;
3034 StringRef Name = Callee->getName();
3035 if (UnsafeFPShrink &&
3036 (Name == "tan" || Name == "atanh" || Name == "sinh" || Name == "cosh" ||
3037 Name == "asinh") &&
3038 hasFloatVersion(M, Name))
3039 Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
3040
3041 Value *Op1 = CI->getArgOperand(0);
3042 auto *OpC = dyn_cast<CallInst>(Op1);
3043 if (!OpC)
3044 return Ret;
3045
3046 // Both calls must be 'fast' in order to remove them.
3047 if (!CI->isFast() || !OpC->isFast())
3048 return Ret;
3049
3050 // tan(atan(x)) -> x
3051 // atanh(tanh(x)) -> x
3052 // sinh(asinh(x)) -> x
3053 // asinh(sinh(x)) -> x
3054 // cosh(acosh(x)) -> x
3055 Function *F = OpC->getCalledFunction();
3056 LibFunc Func = F ? TLI->getLibFunc(F->getName()) : NotLibFunc;
3057 if (isLibFuncEmittable(M, TLI, Func)) {
3058 LibFunc inverseFunc = llvm::StringSwitch<LibFunc>(Callee->getName())
3059 .Case("tan", LibFunc_atan)
3060 .Case("atanh", LibFunc_tanh)
3061 .Case("sinh", LibFunc_asinh)
3062 .Case("cosh", LibFunc_acosh)
3063 .Case("tanf", LibFunc_atanf)
3064 .Case("atanhf", LibFunc_tanhf)
3065 .Case("sinhf", LibFunc_asinhf)
3066 .Case("coshf", LibFunc_acoshf)
3067 .Case("tanl", LibFunc_atanl)
3068 .Case("atanhl", LibFunc_tanhl)
3069 .Case("sinhl", LibFunc_asinhl)
3070 .Case("coshl", LibFunc_acoshl)
3071 .Case("asinh", LibFunc_sinh)
3072 .Case("asinhf", LibFunc_sinhf)
3073 .Case("asinhl", LibFunc_sinhl)
3074 .Default(NotLibFunc); // Used as error value
3075 if (Func == inverseFunc)
3076 Ret = OpC->getArgOperand(0);
3077 }
3078 return Ret;
3079}
3080
3081static bool isTrigLibCall(CallInst *CI) {
3082 // We can only hope to do anything useful if we can ignore things like errno
3083 // and floating-point exceptions.
3084 // We already checked the prototype.
3085 return CI->doesNotThrow() && CI->doesNotAccessMemory();
3086}
3087
3088static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
3089 bool UseFloat, Value *&Sin, Value *&Cos,
3090 Value *&SinCos, const TargetLibraryInfo *TLI) {
3091 Module *M = OrigCallee->getParent();
3092 Type *ArgTy = Arg->getType();
3093 Type *ResTy;
3094 StringRef Name;
3095
3096 Triple T(OrigCallee->getParent()->getTargetTriple());
3097 if (UseFloat) {
3098 Name = "__sincospif_stret";
3099
3100 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
3101 // x86_64 can't use {float, float} since that would be returned in both
3102 // xmm0 and xmm1, which isn't what a real struct would do.
3103 ResTy = T.getArch() == Triple::x86_64
3104 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
3105 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
3106 } else {
3107 Name = "__sincospi_stret";
3108 ResTy = StructType::get(ArgTy, ArgTy);
3109 }
3110
3111 if (!isLibFuncEmittable(M, TLI, Name))
3112 return false;
3113 LibFunc TheLibFunc = TLI->getLibFunc(Name);
3115 M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
3116
3117 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
3118 // If the argument is an instruction, it must dominate all uses so put our
3119 // sincos call there.
3120 B.SetInsertPoint(++ArgInst->getIterator());
3121 } else {
3122 // Otherwise (e.g. for a constant) the beginning of the function is as
3123 // good a place as any.
3124 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
3125 B.SetInsertPoint(EntryBB.begin());
3126 }
3127
3128 SinCos = B.CreateCall(Callee, Arg, "sincospi");
3129
3130 if (SinCos->getType()->isStructTy()) {
3131 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
3132 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
3133 } else {
3134 Sin = B.CreateExtractElement(SinCos, uint64_t{0}, "sinpi");
3135 Cos = B.CreateExtractElement(SinCos, uint64_t{1}, "cospi");
3136 }
3137
3138 return true;
3139}
3140
3141/// Flushing a denormal to +0.0 breaks f(-x) = -f(x) for odd f.
3145 return Mode.inputsMayBePositiveZero() || Mode.outputsMayBePositiveZero();
3146}
3147
3148static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven,
3149 IRBuilderBase &B) {
3150 Value *X;
3151 Value *Src = CI->getArgOperand(0);
3152
3153 if (match(Src, m_OneUse(m_FNeg(m_Value(X)))) &&
3154 (IsEven || !mayFlushDenormalsToPositiveZero(CI))) {
3155 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3156 auto *CallInst = copyFlags(*CI, Call);
3157 if (IsEven) {
3158 // Even function: f(-x) = f(x)
3159 return CallInst;
3160 }
3161 // Odd function: f(-x) = -f(x)
3162 return B.CreateFNegFMF(CallInst, CI);
3163 }
3164
3165 // Even function: f(abs(x)) = f(x), f(copysign(x, y)) = f(x)
3166 if (IsEven && (match(Src, m_FAbs(m_Value(X))) ||
3167 match(Src, m_CopySign(m_Value(X), m_Value())))) {
3168 auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
3169 return copyFlags(*CI, Call);
3170 }
3171
3172 return nullptr;
3173}
3174
3175Value *LibCallSimplifier::optimizeSymmetric(CallInst *CI, LibFunc Func,
3176 IRBuilderBase &B) {
3177 switch (Func) {
3178 case LibFunc_cos:
3179 case LibFunc_cosf:
3180 case LibFunc_cosl:
3181
3182 case LibFunc_cosh:
3183 case LibFunc_coshf:
3184 case LibFunc_coshl:
3185 return optimizeSymmetricCall(CI, /*IsEven*/ true, B);
3186
3187 case LibFunc_cbrt:
3188 case LibFunc_cbrtf:
3189 case LibFunc_cbrtl:
3190
3191 case LibFunc_sin:
3192 case LibFunc_sinf:
3193 case LibFunc_sinl:
3194
3195 case LibFunc_sinh:
3196 case LibFunc_sinhf:
3197 case LibFunc_sinhl:
3198
3199 case LibFunc_asin:
3200 case LibFunc_asinf:
3201 case LibFunc_asinl:
3202
3203 case LibFunc_asinh:
3204 case LibFunc_asinhf:
3205 case LibFunc_asinhl:
3206
3207 case LibFunc_tan:
3208 case LibFunc_tanf:
3209 case LibFunc_tanl:
3210
3211 case LibFunc_tanh:
3212 case LibFunc_tanhf:
3213 case LibFunc_tanhl:
3214
3215 case LibFunc_atan:
3216 case LibFunc_atanf:
3217 case LibFunc_atanl:
3218
3219 case LibFunc_erf:
3220 case LibFunc_erff:
3221 case LibFunc_erfl:
3222 return optimizeSymmetricCall(CI, /*IsEven*/ false, B);
3223
3224 default:
3225 return nullptr;
3226 }
3227}
3228
3229Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, bool IsSin, IRBuilderBase &B) {
3230 // Make sure the prototype is as expected, otherwise the rest of the
3231 // function is probably invalid and likely to abort.
3232 if (!isTrigLibCall(CI))
3233 return nullptr;
3234
3235 Value *Arg = CI->getArgOperand(0);
3236 if (isa<ConstantData>(Arg))
3237 return nullptr;
3238
3241 SmallVector<CallInst *, 1> SinCosCalls;
3242
3243 bool IsFloat = Arg->getType()->isFloatTy();
3244
3245 // Look for all compatible sinpi, cospi and sincospi calls with the same
3246 // argument. If there are enough (in some sense) we can make the
3247 // substitution.
3248 Function *F = CI->getFunction();
3249 for (User *U : Arg->users())
3250 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
3251
3252 // It's only worthwhile if both sinpi and cospi are actually used.
3253 if (SinCalls.empty() || CosCalls.empty())
3254 return nullptr;
3255
3256 Value *Sin, *Cos, *SinCos;
3257 if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
3258 SinCos, TLI))
3259 return nullptr;
3260
3261 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
3262 Value *Res) {
3263 for (CallInst *C : Calls)
3264 replaceAllUsesWith(C, Res);
3265 };
3266
3267 replaceTrigInsts(SinCalls, Sin);
3268 replaceTrigInsts(CosCalls, Cos);
3269 replaceTrigInsts(SinCosCalls, SinCos);
3270
3271 return IsSin ? Sin : Cos;
3272}
3273
3274void LibCallSimplifier::classifyArgUse(
3275 Value *Val, Function *F, bool IsFloat,
3278 SmallVectorImpl<CallInst *> &SinCosCalls) {
3279 auto *CI = dyn_cast<CallInst>(Val);
3280 if (!CI || CI->use_empty())
3281 return;
3282
3283 // Don't consider calls in other functions.
3284 if (CI->getFunction() != F)
3285 return;
3286
3287 Module *M = CI->getModule();
3289 LibFunc Func = Callee ? TLI->getLibFunc(*Callee) : NotLibFunc;
3290 if (!isLibFuncEmittable(M, TLI, Func) || !isTrigLibCall(CI))
3291 return;
3292
3293 if (IsFloat) {
3294 if (Func == LibFunc_sinpif)
3295 SinCalls.push_back(CI);
3296 else if (Func == LibFunc_cospif)
3297 CosCalls.push_back(CI);
3298 else if (Func == LibFunc_sincospif_stret)
3299 SinCosCalls.push_back(CI);
3300 } else {
3301 if (Func == LibFunc_sinpi)
3302 SinCalls.push_back(CI);
3303 else if (Func == LibFunc_cospi)
3304 CosCalls.push_back(CI);
3305 else if (Func == LibFunc_sincospi_stret)
3306 SinCosCalls.push_back(CI);
3307 }
3308}
3309
3310/// Constant folds remquo
3311Value *LibCallSimplifier::optimizeRemquo(CallInst *CI, IRBuilderBase &B) {
3312 const APFloat *X, *Y;
3313 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3314 !match(CI->getArgOperand(1), m_APFloat(Y)))
3315 return nullptr;
3316
3317 APFloat::opStatus Status;
3318 APFloat Quot = *X;
3319 Status = Quot.divide(*Y, APFloat::rmNearestTiesToEven);
3320 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3321 return nullptr;
3322 APFloat Rem = *X;
3323 if (Rem.remainder(*Y) != APFloat::opOK)
3324 return nullptr;
3325
3326 // TODO: We can only keep at least the three of the last bits of x/y
3327 unsigned IntBW = TLI->getIntSize();
3328 APSInt QuotInt(IntBW, /*isUnsigned=*/false);
3329 bool IsExact;
3330 Status =
3331 Quot.convertToInteger(QuotInt, APFloat::rmNearestTiesToEven, &IsExact);
3332 if (Status != APFloat::opOK && Status != APFloat::opInexact)
3333 return nullptr;
3334
3335 B.CreateAlignedStore(
3336 ConstantInt::getSigned(B.getIntNTy(IntBW), QuotInt.getExtValue()),
3337 CI->getArgOperand(2), CI->getParamAlign(2));
3338 return ConstantFP::get(CI->getType(), Rem);
3339}
3340
3341/// Constant folds fdim
3342Value *LibCallSimplifier::optimizeFdim(CallInst *CI, IRBuilderBase &B) {
3343 // Cannot perform the fold unless the call has attribute memory(none)
3344 if (!CI->doesNotAccessMemory())
3345 return nullptr;
3346
3347 // TODO : Handle undef values
3348 // Propagate poison if any
3349 if (isa<PoisonValue>(CI->getArgOperand(0)))
3350 return CI->getArgOperand(0);
3351 if (isa<PoisonValue>(CI->getArgOperand(1)))
3352 return CI->getArgOperand(1);
3353
3354 const APFloat *X, *Y;
3355 // Check if both values are constants
3356 if (!match(CI->getArgOperand(0), m_APFloat(X)) ||
3357 !match(CI->getArgOperand(1), m_APFloat(Y)))
3358 return nullptr;
3359
3360 // C99 fdim(x, y) = (x > y) ? x - y : +0.
3361 if (X->compare(*Y) != APFloat::cmpGreaterThan && !X->isNaN() && !Y->isNaN())
3362 return ConstantFP::getZero(CI->getType());
3363 APFloat Difference = *X;
3365 return ConstantFP::get(CI->getType(), Difference);
3366}
3367
3368//===----------------------------------------------------------------------===//
3369// Integer Library Call Optimizations
3370//===----------------------------------------------------------------------===//
3371
3372Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
3373 // All variants of ffs return int which need not be 32 bits wide.
3374 // ffs{,l,ll}(x) -> x != 0 ? (int)llvm.cttz(x)+1 : 0
3375 Type *RetType = CI->getType();
3376 Value *Op = CI->getArgOperand(0);
3377 Type *ArgType = Op->getType();
3378 Value *V = B.CreateIntrinsic(Intrinsic::cttz, {ArgType}, {Op, B.getTrue()},
3379 nullptr, "cttz");
3380 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
3381 V = B.CreateIntCast(V, RetType, false);
3382
3383 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
3384 Value *S = B.CreateSelect(Cond, V, ConstantInt::get(RetType, 0));
3386 return S;
3387 if (auto *SI = dyn_cast<SelectInst>(S))
3390 /*IsExpected=*/false);
3391 return S;
3392}
3393
3394Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
3395 // All variants of fls return int which need not be 32 bits wide.
3396 // fls{,l,ll}(x) -> (int)(sizeInBits(x) - llvm.ctlz(x, false))
3397 Value *Op = CI->getArgOperand(0);
3398 Type *ArgType = Op->getType();
3399 Value *V = B.CreateIntrinsic(Intrinsic::ctlz, {ArgType}, {Op, B.getFalse()},
3400 nullptr, "ctlz");
3401 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
3402 V);
3403 return B.CreateIntCast(V, CI->getType(), false);
3404}
3405
3406Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
3407 // abs(x) -> x <s 0 ? -x : x
3408 // The negation has 'nsw' because abs of INT_MIN is undefined.
3409 Value *X = CI->getArgOperand(0);
3410 Value *IsNeg = B.CreateIsNeg(X);
3411 Value *NegX = B.CreateNSWNeg(X, "neg");
3412 return B.CreateSelect(IsNeg, NegX, X);
3413}
3414
3415Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
3416 // isdigit(c) -> (c-'0') <u 10
3417 Value *Op = CI->getArgOperand(0);
3418 Type *ArgType = Op->getType();
3419 Op = B.CreateSub(Op, ConstantInt::get(ArgType, '0'), "isdigittmp");
3420 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 10), "isdigit");
3421 return B.CreateZExt(Op, CI->getType());
3422}
3423
3424Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
3425 // isascii(c) -> c <u 128
3426 Value *Op = CI->getArgOperand(0);
3427 Type *ArgType = Op->getType();
3428 Op = B.CreateICmpULT(Op, ConstantInt::get(ArgType, 128), "isascii");
3429 return B.CreateZExt(Op, CI->getType());
3430}
3431
3432Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
3433 // toascii(c) -> c & 0x7f
3434 return B.CreateAnd(CI->getArgOperand(0),
3435 ConstantInt::get(CI->getType(), 0x7F));
3436}
3437
3438// Fold calls to atoi, atol, and atoll.
3439Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
3440 StringRef Str;
3441 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3442 return nullptr;
3443
3444 return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B);
3445}
3446
3447// Fold calls to strtol, strtoll, strtoul, and strtoull.
3448Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B,
3449 bool AsSigned) {
3450 Value *EndPtr = CI->getArgOperand(1);
3451 if (isa<ConstantPointerNull>(EndPtr)) {
3452 // With a null EndPtr, this function won't capture the main argument.
3453 // It would be readonly too, except that it still may write to errno.
3456 EndPtr = nullptr;
3457 } else if (!isKnownNonZero(EndPtr, DL))
3458 return nullptr;
3459
3460 StringRef Str;
3461 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
3462 return nullptr;
3463
3464 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
3465 return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B);
3466 }
3467
3468 return nullptr;
3469}
3470
3471//===----------------------------------------------------------------------===//
3472// Formatting and IO Library Call Optimizations
3473//===----------------------------------------------------------------------===//
3474
3475static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
3476
3477Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
3478 int StreamArg) {
3480 // Error reporting calls should be cold, mark them as such.
3481 // This applies even to non-builtin calls: it is only a hint and applies to
3482 // functions that the frontend might not understand as builtins.
3483
3484 // This heuristic was suggested in:
3485 // Improving Static Branch Prediction in a Compiler
3486 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
3487 // Proceedings of PACT'98, Oct. 1998, IEEE
3488 if (!CI->hasFnAttr(Attribute::Cold) &&
3489 isReportingError(Callee, CI, StreamArg)) {
3490 CI->addFnAttr(Attribute::Cold);
3491 }
3492
3493 return nullptr;
3494}
3495
3496static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
3497 if (!Callee || !Callee->isDeclaration())
3498 return false;
3499
3500 if (StreamArg < 0)
3501 return true;
3502
3503 // These functions might be considered cold, but only if their stream
3504 // argument is stderr.
3505
3506 if (StreamArg >= (int)CI->arg_size())
3507 return false;
3508 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
3509 if (!LI)
3510 return false;
3512 if (!GV || !GV->isDeclaration())
3513 return false;
3514 return GV->getName() == "stderr";
3515}
3516
3517Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
3518 // Check for a fixed format string.
3519 StringRef FormatStr;
3520 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
3521 return nullptr;
3522
3523 // Empty format string -> noop.
3524 if (FormatStr.empty()) // Tolerate printf's declared void.
3525 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
3526
3527 // Do not do any of the following transformations if the printf return value
3528 // is used, in general the printf return value is not compatible with either
3529 // putchar() or puts().
3530 if (!CI->use_empty())
3531 return nullptr;
3532
3533 Type *IntTy = CI->getType();
3534 // printf("x") -> putchar('x'), even for "%" and "%%".
3535 if (FormatStr.size() == 1 || FormatStr == "%%") {
3536 // Convert the character to unsigned char before passing it to putchar
3537 // to avoid host-specific sign extension in the IR. Putchar converts
3538 // it to unsigned char regardless.
3539 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)FormatStr[0]);
3540 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3541 }
3542
3543 // Try to remove call or emit putchar/puts.
3544 if (FormatStr == "%s" && CI->arg_size() > 1) {
3545 StringRef OperandStr;
3546 if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
3547 return nullptr;
3548 // printf("%s", "") --> NOP
3549 if (OperandStr.empty())
3550 return (Value *)CI;
3551 // printf("%s", "a") --> putchar('a')
3552 if (OperandStr.size() == 1) {
3553 // Convert the character to unsigned char before passing it to putchar
3554 // to avoid host-specific sign extension in the IR. Putchar converts
3555 // it to unsigned char regardless.
3556 Value *IntChar = ConstantInt::get(IntTy, (unsigned char)OperandStr[0]);
3557 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3558 }
3559 // printf("%s", str"\n") --> puts(str)
3560 if (OperandStr.back() == '\n') {
3561 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3562 return nullptr;
3563 OperandStr = OperandStr.drop_back();
3564 Value *GV = B.CreateGlobalString(OperandStr, "str");
3565 return copyFlags(*CI, emitPutS(GV, B, TLI));
3566 }
3567 return nullptr;
3568 }
3569
3570 // printf("foo\n") --> puts("foo")
3571 if (FormatStr.back() == '\n' &&
3572 !FormatStr.contains('%')) { // No format characters.
3573 if (!isLibFuncEmittable(CI->getModule(), TLI, LibFunc_puts))
3574 return nullptr;
3575 // Create a string literal with no \n on it. We expect the constant merge
3576 // pass to be run after this pass, to merge duplicate strings.
3577 FormatStr = FormatStr.drop_back();
3578 Value *GV = B.CreateGlobalString(FormatStr, "str");
3579 return copyFlags(*CI, emitPutS(GV, B, TLI));
3580 }
3581
3582 // Optimize specific format strings.
3583 // printf("%c", chr) --> putchar(chr)
3584 if (FormatStr == "%c" && CI->arg_size() > 1 &&
3585 CI->getArgOperand(1)->getType()->isIntegerTy()) {
3586 // Convert the argument to the type expected by putchar, i.e., int, which
3587 // need not be 32 bits wide but which is the same as printf's return type.
3588 Value *IntChar = B.CreateIntCast(CI->getArgOperand(1), IntTy, false);
3589 return copyFlags(*CI, emitPutChar(IntChar, B, TLI));
3590 }
3591
3592 // printf("%s\n", str) --> puts(str)
3593 if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
3594 CI->getArgOperand(1)->getType()->isPointerTy())
3595 return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
3596 return nullptr;
3597}
3598
3599Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
3600
3601 Module *M = CI->getModule();
3603 FunctionType *FT = Callee->getFunctionType();
3604 if (Value *V = optimizePrintFString(CI, B)) {
3605 return V;
3606 }
3607
3609
3610 // printf(format, ...) -> iprintf(format, ...) if no floating point
3611 // arguments.
3612 if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
3614 FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
3615 Callee->getAttributes());
3616 CallInst *New = cast<CallInst>(CI->clone());
3617 New->setCalledFunction(IPrintFFn);
3618 B.Insert(New);
3619 return New;
3620 }
3621
3622 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
3623 // arguments.
3624 if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
3625 !callHasFP128Argument(CI)) {
3626 auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
3627 Callee->getAttributes());
3628 CallInst *New = cast<CallInst>(CI->clone());
3629 New->setCalledFunction(SmallPrintFFn);
3630 B.Insert(New);
3631 return New;
3632 }
3633
3634 return nullptr;
3635}
3636
3637Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
3638 IRBuilderBase &B) {
3639 // Check for a fixed format string.
3640 StringRef FormatStr;
3641 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3642 return nullptr;
3643
3644 // If we just have a format string (nothing else crazy) transform it.
3645 Value *Dest = CI->getArgOperand(0);
3646 if (CI->arg_size() == 2) {
3647 // Make sure there's no % in the constant array. We could try to handle
3648 // %% -> % in the future if we cared.
3649 if (FormatStr.contains('%'))
3650 return nullptr; // we found a format specifier, bail out.
3651
3652 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
3653 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(1), Align(1),
3654 // Copy the null byte.
3655 TLI->getAsSizeT(FormatStr.size() + 1, *CI->getModule()));
3656 return ConstantInt::get(CI->getType(), FormatStr.size());
3657 }
3658
3659 // The remaining optimizations require the format string to be "%s" or "%c"
3660 // and have an extra operand.
3661 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3662 return nullptr;
3663
3664 // Decode the second character of the format string.
3665 if (FormatStr[1] == 'c') {
3666 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3667 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3668 return nullptr;
3669 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
3670 Value *Ptr = Dest;
3671 B.CreateStore(V, Ptr);
3672 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3673 B.CreateStore(B.getInt8(0), Ptr);
3674
3675 return ConstantInt::get(CI->getType(), 1);
3676 }
3677
3678 if (FormatStr[1] == 's') {
3679 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
3680 // strlen(str)+1)
3681 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3682 return nullptr;
3683
3684 if (CI->use_empty())
3685 // sprintf(dest, "%s", str) -> strcpy(dest, str)
3686 return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
3687
3688 uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
3689 if (SrcLen) {
3690 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1),
3691 TLI->getAsSizeT(SrcLen, *CI->getModule()));
3692 // Returns total number of characters written without null-character.
3693 return ConstantInt::get(CI->getType(), SrcLen - 1);
3694 } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
3695 // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
3696 Value *PtrDiff = B.CreatePtrDiff(V, Dest);
3697 return B.CreateIntCast(PtrDiff, CI->getType(), false);
3698 }
3699
3700 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3702 return nullptr;
3703
3704 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
3705 if (!Len)
3706 return nullptr;
3707 Value *IncLen =
3708 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
3709 B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
3710
3711 // The sprintf result is the unincremented number of bytes in the string.
3712 return B.CreateIntCast(Len, CI->getType(), false);
3713 }
3714 return nullptr;
3715}
3716
3717Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
3718 Module *M = CI->getModule();
3720 FunctionType *FT = Callee->getFunctionType();
3721 if (Value *V = optimizeSPrintFString(CI, B)) {
3722 return V;
3723 }
3724
3726
3727 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
3728 // point arguments.
3729 if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
3731 FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
3732 FT, Callee->getAttributes());
3733 CallInst *New = cast<CallInst>(CI->clone());
3734 New->setCalledFunction(SIPrintFFn);
3735 B.Insert(New);
3736 return New;
3737 }
3738
3739 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
3740 // floating point arguments.
3741 if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
3742 !callHasFP128Argument(CI)) {
3743 auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
3744 Callee->getAttributes());
3745 CallInst *New = cast<CallInst>(CI->clone());
3746 New->setCalledFunction(SmallSPrintFFn);
3747 B.Insert(New);
3748 return New;
3749 }
3750
3751 return nullptr;
3752}
3753
3754// Transform an snprintf call CI with the bound N to format the string Str
3755// either to a call to memcpy, or to single character a store, or to nothing,
3756// and fold the result to a constant. A nonnull StrArg refers to the string
3757// argument being formatted. Otherwise the call is one with N < 2 and
3758// the "%c" directive to format a single character.
3759Value *LibCallSimplifier::emitSnPrintfMemCpy(CallInst *CI, Value *StrArg,
3760 StringRef Str, uint64_t N,
3761 IRBuilderBase &B) {
3762 assert(StrArg || (N < 2 && Str.size() == 1));
3763
3764 unsigned IntBits = TLI->getIntSize();
3765 uint64_t IntMax = maxIntN(IntBits);
3766 if (Str.size() > IntMax)
3767 // Bail if the string is longer than INT_MAX. POSIX requires
3768 // implementations to set errno to EOVERFLOW in this case, in
3769 // addition to when N is larger than that (checked by the caller).
3770 return nullptr;
3771
3772 Value *StrLen = ConstantInt::get(CI->getType(), Str.size());
3773 if (N == 0)
3774 return StrLen;
3775
3776 // Set to the number of bytes to copy fron StrArg which is also
3777 // the offset of the terinating nul.
3778 uint64_t NCopy;
3779 if (N > Str.size())
3780 // Copy the full string, including the terminating nul (which must
3781 // be present regardless of the bound).
3782 NCopy = Str.size() + 1;
3783 else
3784 NCopy = N - 1;
3785
3786 Value *DstArg = CI->getArgOperand(0);
3787 if (NCopy && StrArg)
3788 // Transform the call to lvm.memcpy(dst, fmt, N).
3789 copyFlags(*CI, B.CreateMemCpy(DstArg, Align(1), StrArg, Align(1),
3790 TLI->getAsSizeT(NCopy, *CI->getModule())));
3791
3792 if (N > Str.size())
3793 // Return early when the whole format string, including the final nul,
3794 // has been copied.
3795 return StrLen;
3796
3797 // Otherwise, when truncating the string append a terminating nul.
3798 Type *Int8Ty = B.getInt8Ty();
3799 Value *NulOff = B.getIntN(IntBits, NCopy);
3800 Value *DstEnd = B.CreateInBoundsGEP(Int8Ty, DstArg, NulOff, "endptr");
3801 B.CreateStore(ConstantInt::get(Int8Ty, 0), DstEnd);
3802 return StrLen;
3803}
3804
3805Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
3806 IRBuilderBase &B) {
3807 // Check for size
3808 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3809 if (!Size)
3810 return nullptr;
3811
3812 uint64_t N = Size->getZExtValue();
3813 uint64_t IntMax = maxIntN(TLI->getIntSize());
3814 if (N > IntMax)
3815 // Bail if the bound exceeds INT_MAX. POSIX requires implementations
3816 // to set errno to EOVERFLOW in this case.
3817 return nullptr;
3818
3819 Value *DstArg = CI->getArgOperand(0);
3820 Value *FmtArg = CI->getArgOperand(2);
3821
3822 // Check for a fixed format string.
3823 StringRef FormatStr;
3824 if (!getConstantStringInfo(FmtArg, FormatStr))
3825 return nullptr;
3826
3827 // If we just have a format string (nothing else crazy) transform it.
3828 if (CI->arg_size() == 3) {
3829 if (FormatStr.contains('%'))
3830 // Bail if the format string contains a directive and there are
3831 // no arguments. We could handle "%%" in the future.
3832 return nullptr;
3833
3834 return emitSnPrintfMemCpy(CI, FmtArg, FormatStr, N, B);
3835 }
3836
3837 // The remaining optimizations require the format string to be "%s" or "%c"
3838 // and have an extra operand.
3839 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() != 4)
3840 return nullptr;
3841
3842 // Decode the second character of the format string.
3843 if (FormatStr[1] == 'c') {
3844 if (N <= 1) {
3845 // Use an arbitary string of length 1 to transform the call into
3846 // either a nul store (N == 1) or a no-op (N == 0) and fold it
3847 // to one.
3848 StringRef CharStr("*");
3849 return emitSnPrintfMemCpy(CI, nullptr, CharStr, N, B);
3850 }
3851
3852 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
3853 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
3854 return nullptr;
3855 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
3856 Value *Ptr = DstArg;
3857 B.CreateStore(V, Ptr);
3858 Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
3859 B.CreateStore(B.getInt8(0), Ptr);
3860 return ConstantInt::get(CI->getType(), 1);
3861 }
3862
3863 if (FormatStr[1] != 's')
3864 return nullptr;
3865
3866 Value *StrArg = CI->getArgOperand(3);
3867 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
3868 StringRef Str;
3869 if (!getConstantStringInfo(StrArg, Str))
3870 return nullptr;
3871
3872 return emitSnPrintfMemCpy(CI, StrArg, Str, N, B);
3873}
3874
3875Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
3876 if (Value *V = optimizeSnPrintFString(CI, B)) {
3877 return V;
3878 }
3879
3880 if (isKnownNonZero(CI->getOperand(1), DL))
3882 return nullptr;
3883}
3884
3885Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
3886 IRBuilderBase &B) {
3887 optimizeErrorReporting(CI, B, 0);
3888
3889 // All the optimizations depend on the format string.
3890 StringRef FormatStr;
3891 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3892 return nullptr;
3893
3894 // Do not do any of the following transformations if the fprintf return
3895 // value is used, in general the fprintf return value is not compatible
3896 // with fwrite(), fputc() or fputs().
3897 if (!CI->use_empty())
3898 return nullptr;
3899
3900 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
3901 if (CI->arg_size() == 2) {
3902 // Could handle %% -> % if we cared.
3903 if (FormatStr.contains('%'))
3904 return nullptr; // We found a format specifier.
3905
3906 return copyFlags(
3907 *CI, emitFWrite(CI->getArgOperand(1),
3908 TLI->getAsSizeT(FormatStr.size(), *CI->getModule()),
3909 CI->getArgOperand(0), B, DL, TLI));
3910 }
3911
3912 // The remaining optimizations require the format string to be "%s" or "%c"
3913 // and have an extra operand.
3914 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3915 return nullptr;
3916
3917 // Decode the second character of the format string.
3918 if (FormatStr[1] == 'c') {
3919 // fprintf(F, "%c", chr) --> fputc((int)chr, F)
3920 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3921 return nullptr;
3922 Type *IntTy = B.getIntNTy(TLI->getIntSize());
3923 Value *V = B.CreateIntCast(CI->getArgOperand(2), IntTy, /*isSigned*/ true,
3924 "chari");
3925 return copyFlags(*CI, emitFPutC(V, CI->getArgOperand(0), B, TLI));
3926 }
3927
3928 if (FormatStr[1] == 's') {
3929 // fprintf(F, "%s", str) --> fputs(str, F)
3930 if (!CI->getArgOperand(2)->getType()->isPointerTy())
3931 return nullptr;
3932 return copyFlags(
3933 *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
3934 }
3935 return nullptr;
3936}
3937
3938Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
3939 Module *M = CI->getModule();
3941 FunctionType *FT = Callee->getFunctionType();
3942 if (Value *V = optimizeFPrintFString(CI, B)) {
3943 return V;
3944 }
3945
3946 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
3947 // floating point arguments.
3948 if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
3950 FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
3951 FT, Callee->getAttributes());
3952 CallInst *New = cast<CallInst>(CI->clone());
3953 New->setCalledFunction(FIPrintFFn);
3954 B.Insert(New);
3955 return New;
3956 }
3957
3958 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
3959 // 128-bit floating point arguments.
3960 if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
3961 !callHasFP128Argument(CI)) {
3962 auto SmallFPrintFFn =
3963 getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
3964 Callee->getAttributes());
3965 CallInst *New = cast<CallInst>(CI->clone());
3966 New->setCalledFunction(SmallFPrintFFn);
3967 B.Insert(New);
3968 return New;
3969 }
3970
3971 return nullptr;
3972}
3973
3974Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
3975 optimizeErrorReporting(CI, B, 3);
3976
3977 // Get the element size and count.
3978 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3979 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
3980 if (SizeC && CountC) {
3981 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
3982
3983 // If this is writing zero records, remove the call (it's a noop).
3984 if (Bytes == 0)
3985 return ConstantInt::get(CI->getType(), 0);
3986
3987 // If this is writing one byte, turn it into fputc.
3988 // This optimisation is only valid, if the return value is unused.
3989 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
3990 Value *Char = B.CreateLoad(B.getInt8Ty(), CI->getArgOperand(0), "char");
3991 Type *IntTy = B.getIntNTy(TLI->getIntSize());
3992 Value *Cast = B.CreateIntCast(Char, IntTy, /*isSigned*/ true, "chari");
3993 Value *NewCI = emitFPutC(Cast, CI->getArgOperand(3), B, TLI);
3994 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
3995 }
3996 }
3997
3998 return nullptr;
3999}
4000
4001Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
4002 optimizeErrorReporting(CI, B, 1);
4003
4004 // Don't rewrite fputs to fwrite when optimising for size because fwrite
4005 // requires more arguments and thus extra MOVs are required.
4006 if (llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
4008 return nullptr;
4009
4010 // We can't optimize if return value is used.
4011 if (!CI->use_empty())
4012 return nullptr;
4013
4014 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
4016 if (!Len)
4017 return nullptr;
4018
4019 // Known to have no uses (see above).
4020 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
4021 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
4022 return copyFlags(
4023 *CI,
4025 ConstantInt::get(SizeTTy, Len - 1),
4026 CI->getArgOperand(1), B, DL, TLI));
4027}
4028
4029Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
4031 if (!CI->use_empty())
4032 return nullptr;
4033
4034 // Check for a constant string.
4035 // puts("") -> putchar('\n')
4036 StringRef Str;
4037 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty()) {
4038 // putchar takes an argument of the same type as puts returns, i.e.,
4039 // int, which need not be 32 bits wide.
4040 Type *IntTy = CI->getType();
4041 return copyFlags(*CI, emitPutChar(ConstantInt::get(IntTy, '\n'), B, TLI));
4042 }
4043
4044 return nullptr;
4045}
4046
4047Value *LibCallSimplifier::optimizeExit(CallInst *CI) {
4048
4049 // Mark 'exit' as cold if its not exit(0) (success).
4050 const APInt *C;
4051 if (!CI->hasFnAttr(Attribute::Cold) &&
4052 match(CI->getArgOperand(0), m_APInt(C)) && !C->isZero()) {
4053 CI->addFnAttr(Attribute::Cold);
4054 }
4055 return nullptr;
4056}
4057
4058Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
4059 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
4060 return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
4061 CI->getArgOperand(0), Align(1),
4062 CI->getArgOperand(2)));
4063}
4064
4065bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
4066 SmallString<20> FloatFuncName = FuncName;
4067 FloatFuncName += 'f';
4068 return isLibFuncEmittable(M, TLI, FloatFuncName);
4069}
4070
4071Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
4072 IRBuilderBase &Builder) {
4073 Module *M = CI->getModule();
4075 LibFunc Func = TLI->getLibFunc(*Callee);
4076
4077 // Check for string/memory library functions.
4078 if (isLibFuncEmittable(M, TLI, Func)) {
4079 // Make sure we never change the calling convention.
4080 assert(
4081 (ignoreCallingConv(Func) ||
4083 "Optimizing string/memory libcall would change the calling convention");
4084 switch (Func) {
4085 case LibFunc_strcat:
4086 return optimizeStrCat(CI, Builder);
4087 case LibFunc_strncat:
4088 return optimizeStrNCat(CI, Builder);
4089 case LibFunc_strchr:
4090 return optimizeStrChr(CI, Builder);
4091 case LibFunc_strrchr:
4092 return optimizeStrRChr(CI, Builder);
4093 case LibFunc_strcmp:
4094 return optimizeStrCmp(CI, Builder);
4095 case LibFunc_strncmp:
4096 return optimizeStrNCmp(CI, Builder);
4097 case LibFunc_strcpy:
4098 return optimizeStrCpy(CI, Builder);
4099 case LibFunc_stpcpy:
4100 return optimizeStpCpy(CI, Builder);
4101 case LibFunc_strlcpy:
4102 return optimizeStrLCpy(CI, Builder);
4103 case LibFunc_stpncpy:
4104 return optimizeStringNCpy(CI, /*RetEnd=*/true, Builder);
4105 case LibFunc_strncpy:
4106 return optimizeStringNCpy(CI, /*RetEnd=*/false, Builder);
4107 case LibFunc_strlen:
4108 return optimizeStrLen(CI, Builder);
4109 case LibFunc_strnlen:
4110 return optimizeStrNLen(CI, Builder);
4111 case LibFunc_strpbrk:
4112 return optimizeStrPBrk(CI, Builder);
4113 case LibFunc_strndup:
4114 return optimizeStrNDup(CI, Builder);
4115 case LibFunc_strtol:
4116 case LibFunc_strtod:
4117 case LibFunc_strtof:
4118 case LibFunc_strtoul:
4119 case LibFunc_strtoll:
4120 case LibFunc_strtold:
4121 case LibFunc_strtoull:
4122 return optimizeStrTo(CI, Builder);
4123 case LibFunc_strspn:
4124 return optimizeStrSpn(CI, Builder);
4125 case LibFunc_strcspn:
4126 return optimizeStrCSpn(CI, Builder);
4127 case LibFunc_strstr:
4128 return optimizeStrStr(CI, Builder);
4129 case LibFunc_memchr:
4130 return optimizeMemChr(CI, Builder);
4131 case LibFunc_memrchr:
4132 return optimizeMemRChr(CI, Builder);
4133 case LibFunc_bcmp:
4134 return optimizeBCmp(CI, Builder);
4135 case LibFunc_memcmp:
4136 return optimizeMemCmp(CI, Builder);
4137 case LibFunc_memcpy:
4138 return optimizeMemCpy(CI, Builder);
4139 case LibFunc_memccpy:
4140 return optimizeMemCCpy(CI, Builder);
4141 case LibFunc_mempcpy:
4142 return optimizeMemPCpy(CI, Builder);
4143 case LibFunc_memmove:
4144 return optimizeMemMove(CI, Builder);
4145 case LibFunc_memset:
4146 return optimizeMemSet(CI, Builder);
4147 case LibFunc_realloc:
4148 return optimizeRealloc(CI, Builder);
4149 case LibFunc_wcslen:
4150 return optimizeWcslen(CI, Builder);
4151 case LibFunc_bcopy:
4152 return optimizeBCopy(CI, Builder);
4153 case LibFunc_Znwm:
4154 case LibFunc_ZnwmRKSt9nothrow_t:
4155 case LibFunc_ZnwmSt11align_val_t:
4156 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
4157 case LibFunc_Znam:
4158 case LibFunc_ZnamRKSt9nothrow_t:
4159 case LibFunc_ZnamSt11align_val_t:
4160 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
4161 case LibFunc_Znwm12__hot_cold_t:
4162 case LibFunc_ZnwmRKSt9nothrow_t12__hot_cold_t:
4163 case LibFunc_ZnwmSt11align_val_t12__hot_cold_t:
4164 case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4165 case LibFunc_Znam12__hot_cold_t:
4166 case LibFunc_ZnamRKSt9nothrow_t12__hot_cold_t:
4167 case LibFunc_ZnamSt11align_val_t12__hot_cold_t:
4168 case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t12__hot_cold_t:
4169 case LibFunc_size_returning_new:
4170 case LibFunc_size_returning_new_hot_cold:
4171 case LibFunc_size_returning_new_aligned:
4172 case LibFunc_size_returning_new_aligned_hot_cold:
4173 return optimizeNew(CI, Builder, Func);
4174 default:
4175 break;
4176 }
4177 }
4178 return nullptr;
4179}
4180
4181/// Constant folding nan/nanf/nanl.
4183 StringRef CharSeq;
4184 if (!getConstantStringInfo(CI->getArgOperand(0), CharSeq))
4185 return nullptr;
4186
4187 APInt Fill;
4188 // Treat empty strings as if they were zero.
4189 if (CharSeq.empty())
4190 Fill = APInt(32, 0);
4191 else if (CharSeq.getAsInteger(0, Fill))
4192 return nullptr;
4193
4194 return ConstantFP::getQNaN(CI->getType(), /*Negative=*/false, &Fill);
4195}
4196
4197Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
4198 LibFunc Func,
4199 IRBuilderBase &Builder) {
4200 const Module *M = CI->getModule();
4201
4202 // Don't optimize calls that require strict floating point semantics.
4203 if (CI->isStrictFP())
4204 return nullptr;
4205
4206 if (Value *V = optimizeSymmetric(CI, Func, Builder))
4207 return V;
4208
4209 switch (Func) {
4210 case LibFunc_sinpif:
4211 case LibFunc_sinpi:
4212 return optimizeSinCosPi(CI, /*IsSin*/true, Builder);
4213 case LibFunc_cospif:
4214 case LibFunc_cospi:
4215 return optimizeSinCosPi(CI, /*IsSin*/false, Builder);
4216 case LibFunc_sinf:
4217 case LibFunc_sinl:
4218 if (CI->doesNotAccessMemory())
4219 return replaceUnaryCall(CI, Builder, Intrinsic::sin);
4220 return nullptr;
4221 case LibFunc_cosf:
4222 case LibFunc_cosl:
4223 if (CI->doesNotAccessMemory())
4224 return replaceUnaryCall(CI, Builder, Intrinsic::cos);
4225 return nullptr;
4226 case LibFunc_powf:
4227 case LibFunc_pow:
4228 case LibFunc_powl:
4229 return optimizePow(CI, Builder);
4230 case LibFunc_exp2l:
4231 case LibFunc_exp2:
4232 case LibFunc_exp2f:
4233 return optimizeExp2(CI, Builder);
4234 case LibFunc_scalbn:
4235 case LibFunc_scalbnf:
4236 case LibFunc_scalbnl:
4237 // LLVM floating-point types have radix 2, so scalbn is equivalent to
4238 // ldexp. Do not replace a libcall that may set errno.
4239 if (CI->doesNotAccessMemory()) {
4240 Value *NewCall =
4241 Builder.CreateLdexp(CI->getArgOperand(0), CI->getArgOperand(1), CI);
4242 NewCall->takeName(CI);
4243 return copyFlags(*CI, NewCall);
4244 }
4245 return nullptr;
4246 case LibFunc_fabsf:
4247 case LibFunc_fabs:
4248 case LibFunc_fabsl:
4249 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
4250 case LibFunc_sqrtf:
4251 case LibFunc_sqrt:
4252 case LibFunc_sqrtl:
4253 return optimizeSqrt(CI, Builder);
4254 case LibFunc_fmod:
4255 case LibFunc_fmodf:
4256 case LibFunc_fmodl:
4257 return optimizeFMod(CI, Builder);
4258 case LibFunc_logf:
4259 case LibFunc_log:
4260 case LibFunc_logl:
4261 case LibFunc_log10f:
4262 case LibFunc_log10:
4263 case LibFunc_log10l:
4264 case LibFunc_log1pf:
4265 case LibFunc_log1p:
4266 case LibFunc_log1pl:
4267 case LibFunc_log2f:
4268 case LibFunc_log2:
4269 case LibFunc_log2l:
4270 case LibFunc_logbf:
4271 case LibFunc_logb:
4272 case LibFunc_logbl:
4273 return optimizeLog(CI, Builder);
4274 case LibFunc_tan:
4275 case LibFunc_tanf:
4276 case LibFunc_tanl:
4277 case LibFunc_sinh:
4278 case LibFunc_sinhf:
4279 case LibFunc_sinhl:
4280 case LibFunc_asinh:
4281 case LibFunc_asinhf:
4282 case LibFunc_asinhl:
4283 case LibFunc_cosh:
4284 case LibFunc_coshf:
4285 case LibFunc_coshl:
4286 case LibFunc_atanh:
4287 case LibFunc_atanhf:
4288 case LibFunc_atanhl:
4289 return optimizeTrigInversionPairs(CI, Builder);
4290 case LibFunc_ceil:
4291 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
4292 case LibFunc_floor:
4293 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
4294 case LibFunc_round:
4295 return replaceUnaryCall(CI, Builder, Intrinsic::round);
4296 case LibFunc_roundeven:
4297 return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
4298 case LibFunc_nearbyint:
4299 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
4300 case LibFunc_rint:
4301 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
4302 case LibFunc_trunc:
4303 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
4304 case LibFunc_sin:
4305 case LibFunc_cos:
4306 if (UnsafeFPShrink &&
4307 hasFloatVersion(M, CI->getCalledFunction()->getName()))
4308 if (Value *V = optimizeUnaryDoubleFP(CI, Builder, TLI, true))
4309 return V;
4310 if (CI->doesNotAccessMemory())
4311 return replaceUnaryCall(
4312 CI, Builder, Func == LibFunc_sin ? Intrinsic::sin : Intrinsic::cos);
4313 return nullptr;
4314 case LibFunc_acos:
4315 case LibFunc_acosh:
4316 case LibFunc_asin:
4317 case LibFunc_atan:
4318 case LibFunc_cbrt:
4319 case LibFunc_exp:
4320 case LibFunc_exp10:
4321 case LibFunc_expm1:
4322 case LibFunc_tanh:
4323 if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
4324 return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
4325 return nullptr;
4326 case LibFunc_copysign:
4327 if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
4328 return optimizeBinaryDoubleFP(CI, Builder, TLI);
4329 return nullptr;
4330 case LibFunc_fdim:
4331 case LibFunc_fdimf:
4332 case LibFunc_fdiml:
4333 return optimizeFdim(CI, Builder);
4334 case LibFunc_fminf:
4335 case LibFunc_fmin:
4336 case LibFunc_fminl:
4337 return optimizeFMinFMax(CI, Builder, Intrinsic::minnum);
4338 case LibFunc_fmaxf:
4339 case LibFunc_fmax:
4340 case LibFunc_fmaxl:
4341 return optimizeFMinFMax(CI, Builder, Intrinsic::maxnum);
4342 case LibFunc_fminimum_numf:
4343 case LibFunc_fminimum_num:
4344 case LibFunc_fminimum_numl:
4345 return replaceBinaryCall(CI, Builder, Intrinsic::minimumnum);
4346 case LibFunc_fmaximum_numf:
4347 case LibFunc_fmaximum_num:
4348 case LibFunc_fmaximum_numl:
4349 return replaceBinaryCall(CI, Builder, Intrinsic::maximumnum);
4350 case LibFunc_cabs:
4351 case LibFunc_cabsf:
4352 case LibFunc_cabsl:
4353 return optimizeCAbs(CI, Builder);
4354 case LibFunc_remquo:
4355 case LibFunc_remquof:
4356 case LibFunc_remquol:
4357 return optimizeRemquo(CI, Builder);
4358 case LibFunc_nan:
4359 case LibFunc_nanf:
4360 case LibFunc_nanl:
4361 return optimizeNaN(CI);
4362 default:
4363 return nullptr;
4364 }
4365}
4366
4368 Module *M = CI->getModule();
4369 assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
4370
4371 // TODO: Split out the code below that operates on FP calls so that
4372 // we can all non-FP calls with the StrictFP attribute to be
4373 // optimized.
4374 if (CI->isNoBuiltin()) {
4375 // Optionally update operator new calls.
4376 return maybeOptimizeNoBuiltinOperatorNew(CI, Builder);
4377 }
4378
4379 Function *Callee = CI->getCalledFunction();
4380 LibFunc Func = TLI->getLibFunc(*Callee);
4381 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4382
4384 CI->getOperandBundlesAsDefs(OpBundles);
4385
4387 Builder.setDefaultOperandBundles(OpBundles);
4388
4389 // Command-line parameter overrides instruction attribute.
4390 // This can't be moved to optimizeFloatingPointLibCall() because it may be
4391 // used by the intrinsic optimizations.
4392 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
4393 UnsafeFPShrink = EnableUnsafeFPShrink;
4394 else if (isa<FPMathOperator>(CI) && CI->isFast())
4395 UnsafeFPShrink = true;
4396
4397 // First, check for intrinsics.
4399 if (!IsCallingConvC)
4400 return nullptr;
4401 // The FP intrinsics have corresponding constrained versions so we don't
4402 // need to check for the StrictFP attribute here.
4403 switch (II->getIntrinsicID()) {
4404 case Intrinsic::pow:
4405 return optimizePow(CI, Builder);
4406 case Intrinsic::exp2:
4407 return optimizeExp2(CI, Builder);
4408 case Intrinsic::log:
4409 case Intrinsic::log2:
4410 case Intrinsic::log10:
4411 return optimizeLog(CI, Builder);
4412 case Intrinsic::sqrt:
4413 return optimizeSqrt(CI, Builder);
4414 case Intrinsic::memset:
4415 return optimizeMemSet(CI, Builder);
4416 case Intrinsic::memcpy:
4417 return optimizeMemCpy(CI, Builder);
4418 case Intrinsic::memmove:
4419 return optimizeMemMove(CI, Builder);
4420 case Intrinsic::sin:
4421 case Intrinsic::cos:
4422 if (UnsafeFPShrink)
4423 return optimizeUnaryDoubleFP(CI, Builder, TLI, /*isPrecise=*/true);
4424 return nullptr;
4425 case Intrinsic::sincos:
4426 if (UnsafeFPShrink)
4427 return optimizeSinCosDoubleFP(CI, Builder);
4428 return nullptr;
4429 default:
4430 return nullptr;
4431 }
4432 }
4433
4434 // Also try to simplify calls to fortified library functions.
4435 if (Value *SimplifiedFortifiedCI =
4436 FortifiedSimplifier.optimizeCall(CI, Builder))
4437 return SimplifiedFortifiedCI;
4438
4439 // Then check for known library functions.
4440 if (isLibFuncEmittable(M, TLI, Func)) {
4441 // We never change the calling convention.
4442 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4443 return nullptr;
4444 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
4445 return V;
4446 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
4447 return V;
4448 switch (Func) {
4449 case LibFunc_ffs:
4450 case LibFunc_ffsl:
4451 case LibFunc_ffsll:
4452 return optimizeFFS(CI, Builder);
4453 case LibFunc_fls:
4454 case LibFunc_flsl:
4455 case LibFunc_flsll:
4456 return optimizeFls(CI, Builder);
4457 case LibFunc_abs:
4458 case LibFunc_labs:
4459 case LibFunc_llabs:
4460 return optimizeAbs(CI, Builder);
4461 case LibFunc_isdigit:
4462 return optimizeIsDigit(CI, Builder);
4463 case LibFunc_isascii:
4464 return optimizeIsAscii(CI, Builder);
4465 case LibFunc_toascii:
4466 return optimizeToAscii(CI, Builder);
4467 case LibFunc_atoi:
4468 case LibFunc_atol:
4469 case LibFunc_atoll:
4470 return optimizeAtoi(CI, Builder);
4471 case LibFunc_strtol:
4472 case LibFunc_strtoll:
4473 return optimizeStrToInt(CI, Builder, /*AsSigned=*/true);
4474 case LibFunc_strtoul:
4475 case LibFunc_strtoull:
4476 return optimizeStrToInt(CI, Builder, /*AsSigned=*/false);
4477 case LibFunc_printf:
4478 return optimizePrintF(CI, Builder);
4479 case LibFunc_sprintf:
4480 return optimizeSPrintF(CI, Builder);
4481 case LibFunc_snprintf:
4482 return optimizeSnPrintF(CI, Builder);
4483 case LibFunc_fprintf:
4484 return optimizeFPrintF(CI, Builder);
4485 case LibFunc_fwrite:
4486 return optimizeFWrite(CI, Builder);
4487 case LibFunc_fputs:
4488 return optimizeFPuts(CI, Builder);
4489 case LibFunc_puts:
4490 return optimizePuts(CI, Builder);
4491 case LibFunc_perror:
4492 return optimizeErrorReporting(CI, Builder);
4493 case LibFunc_vfprintf:
4494 case LibFunc_fiprintf:
4495 return optimizeErrorReporting(CI, Builder, 0);
4496 case LibFunc_exit:
4497 case LibFunc_Exit:
4498 return optimizeExit(CI);
4499 default:
4500 return nullptr;
4501 }
4502 }
4503 return nullptr;
4504}
4505
4507 const DataLayout &DL, const TargetLibraryInfo *TLI, DominatorTree *DT,
4510 function_ref<void(Instruction *, Value *)> Replacer,
4511 function_ref<void(Instruction *)> Eraser)
4512 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), DT(DT), DC(DC), AC(AC),
4513 ORE(ORE), BFI(BFI), PSI(PSI), Replacer(Replacer), Eraser(Eraser) {}
4514
4515void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
4516 // Indirect through the replacer used in this instance.
4517 Replacer(I, With);
4518}
4519
4520void LibCallSimplifier::eraseFromParent(Instruction *I) {
4521 Eraser(I);
4522}
4523
4524// TODO:
4525// Additional cases that we need to add to this file:
4526//
4527// cbrt:
4528// * cbrt(expN(X)) -> expN(x/3)
4529// * cbrt(sqrt(x)) -> pow(x,1/6)
4530// * cbrt(cbrt(x)) -> pow(x,1/9)
4531//
4532// exp, expf, expl:
4533// * exp(log(x)) -> x
4534//
4535// log, logf, logl:
4536// * log(exp(x)) -> x
4537// * log(exp(y)) -> y*log(e)
4538// * log(exp10(y)) -> y*log(10)
4539// * log(sqrt(x)) -> 0.5*log(x)
4540//
4541// pow, powf, powl:
4542// * pow(sqrt(x),y) -> pow(x,y*0.5)
4543// * pow(pow(x,y),z)-> pow(x,y*z)
4544//
4545// signbit:
4546// * signbit(cnst) -> cnst'
4547// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
4548//
4549// sqrt, sqrtf, sqrtl:
4550// * sqrt(expN(x)) -> expN(x*0.5)
4551// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
4552// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
4553//
4554
4555//===----------------------------------------------------------------------===//
4556// Fortified Library Call Optimizations
4557//===----------------------------------------------------------------------===//
4558
4559bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(
4560 CallInst *CI, unsigned ObjSizeOp, std::optional<unsigned> SizeOp,
4561 std::optional<unsigned> StrOp, std::optional<unsigned> FlagOp) {
4562 // If this function takes a flag argument, the implementation may use it to
4563 // perform extra checks. Don't fold into the non-checking variant.
4564 if (FlagOp) {
4565 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
4566 if (!Flag || !Flag->isZero())
4567 return false;
4568 }
4569
4570 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
4571 return true;
4572
4573 if (ConstantInt *ObjSizeCI =
4574 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
4575 if (ObjSizeCI->isMinusOne())
4576 return true;
4577 // If the object size wasn't -1 (unknown), bail out if we were asked to.
4578 if (OnlyLowerUnknownSize)
4579 return false;
4580 if (StrOp) {
4582 // If the length is 0 we don't know how long it is and so we can't
4583 // remove the check.
4584 if (Len)
4585 annotateDereferenceableBytes(CI, *StrOp, Len);
4586 else
4587 return false;
4588 return ObjSizeCI->getZExtValue() >= Len;
4589 }
4590
4591 if (SizeOp) {
4592 if (ConstantInt *SizeCI =
4594 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
4595 }
4596 }
4597 return false;
4598}
4599
4600Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
4601 IRBuilderBase &B) {
4602 if (isFortifiedCallFoldable(CI, 3, 2)) {
4603 CallInst *NewCI =
4604 B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4605 Align(1), CI->getArgOperand(2));
4606 mergeAttributesAndFlags(NewCI, *CI);
4607 return CI->getArgOperand(0);
4608 }
4609 return nullptr;
4610}
4611
4612Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
4613 IRBuilderBase &B) {
4614 if (isFortifiedCallFoldable(CI, 3, 2)) {
4615 CallInst *NewCI =
4616 B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
4617 Align(1), CI->getArgOperand(2));
4618 mergeAttributesAndFlags(NewCI, *CI);
4619 return CI->getArgOperand(0);
4620 }
4621 return nullptr;
4622}
4623
4624Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
4625 IRBuilderBase &B) {
4626 if (isFortifiedCallFoldable(CI, 3, 2)) {
4627 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
4628 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
4629 CI->getArgOperand(2), Align(1));
4630 mergeAttributesAndFlags(NewCI, *CI);
4631 return CI->getArgOperand(0);
4632 }
4633 return nullptr;
4634}
4635
4636Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
4637 IRBuilderBase &B) {
4638 const DataLayout &DL = CI->getDataLayout();
4639 if (isFortifiedCallFoldable(CI, 3, 2))
4640 if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4641 CI->getArgOperand(2), B, DL, TLI)) {
4643 }
4644 return nullptr;
4645}
4646
4647Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
4649 LibFunc Func) {
4650 const DataLayout &DL = CI->getDataLayout();
4651 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
4652 *ObjSize = CI->getArgOperand(2);
4653
4654 // __stpcpy_chk(x,x,...) -> x+strlen(x)
4655 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
4656 Value *StrLen = emitStrLen(Src, B, DL, TLI);
4657 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
4658 }
4659
4660 // If a) we don't have any length information, or b) we know this will
4661 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
4662 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
4663 // TODO: It might be nice to get a maximum length out of the possible
4664 // string lengths for varying.
4665 if (isFortifiedCallFoldable(CI, 2, std::nullopt, 1)) {
4666 if (Func == LibFunc_strcpy_chk)
4667 return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
4668 else
4669 return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
4670 }
4671
4672 if (OnlyLowerUnknownSize)
4673 return nullptr;
4674
4675 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
4677 if (Len)
4678 annotateDereferenceableBytes(CI, 1, Len);
4679 else
4680 return nullptr;
4681
4682 unsigned SizeTBits = TLI->getSizeTSize(*CI->getModule());
4683 Type *SizeTTy = IntegerType::get(CI->getContext(), SizeTBits);
4684 Value *LenV = ConstantInt::get(SizeTTy, Len);
4685 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
4686 // If the function was an __stpcpy_chk, and we were able to fold it into
4687 // a __memcpy_chk, we still need to return the correct end pointer.
4688 if (Ret && Func == LibFunc_stpcpy_chk)
4689 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst,
4690 ConstantInt::get(SizeTTy, Len - 1));
4691 return copyFlags(*CI, cast<CallInst>(Ret));
4692}
4693
4694Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
4695 IRBuilderBase &B) {
4696 if (isFortifiedCallFoldable(CI, 1, std::nullopt, 0))
4697 return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
4698 CI->getDataLayout(), TLI));
4699 return nullptr;
4700}
4701
4702Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
4704 LibFunc Func) {
4705 if (isFortifiedCallFoldable(CI, 3, 2)) {
4706 if (Func == LibFunc_strncpy_chk)
4707 return copyFlags(*CI,
4709 CI->getArgOperand(2), B, TLI));
4710 else
4711 return copyFlags(*CI,
4713 CI->getArgOperand(2), B, TLI));
4714 }
4715
4716 return nullptr;
4717}
4718
4719Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
4720 IRBuilderBase &B) {
4721 if (isFortifiedCallFoldable(CI, 4, 3))
4722 return copyFlags(
4723 *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
4724 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
4725
4726 return nullptr;
4727}
4728
4729Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
4730 IRBuilderBase &B) {
4731 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2)) {
4732 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
4733 return copyFlags(*CI,
4735 CI->getArgOperand(4), VariadicArgs, B, TLI));
4736 }
4737
4738 return nullptr;
4739}
4740
4741Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
4742 IRBuilderBase &B) {
4743 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1)) {
4744 SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
4745 return copyFlags(*CI,
4747 VariadicArgs, B, TLI));
4748 }
4749
4750 return nullptr;
4751}
4752
4753Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
4754 IRBuilderBase &B) {
4755 if (isFortifiedCallFoldable(CI, 2))
4756 return copyFlags(
4757 *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
4758
4759 return nullptr;
4760}
4761
4762Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
4763 IRBuilderBase &B) {
4764 if (isFortifiedCallFoldable(CI, 3))
4765 return copyFlags(*CI,
4767 CI->getArgOperand(2), B, TLI));
4768
4769 return nullptr;
4770}
4771
4772Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
4773 IRBuilderBase &B) {
4774 if (isFortifiedCallFoldable(CI, 3))
4775 return copyFlags(*CI,
4777 CI->getArgOperand(2), B, TLI));
4778
4779 return nullptr;
4780}
4781
4782Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
4783 IRBuilderBase &B) {
4784 if (isFortifiedCallFoldable(CI, 3))
4785 return copyFlags(*CI,
4787 CI->getArgOperand(2), B, TLI));
4788
4789 return nullptr;
4790}
4791
4792Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
4793 IRBuilderBase &B) {
4794 if (isFortifiedCallFoldable(CI, 3, 1, std::nullopt, 2))
4795 return copyFlags(
4796 *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
4797 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
4798
4799 return nullptr;
4800}
4801
4802Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
4803 IRBuilderBase &B) {
4804 if (isFortifiedCallFoldable(CI, 2, std::nullopt, std::nullopt, 1))
4805 return copyFlags(*CI,
4807 CI->getArgOperand(4), B, TLI));
4808
4809 return nullptr;
4810}
4811
4813 IRBuilderBase &Builder) {
4814 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
4815 // Some clang users checked for _chk libcall availability using:
4816 // __has_builtin(__builtin___memcpy_chk)
4817 // When compiling with -fno-builtin, this is always true.
4818 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
4819 // end up with fortified libcalls, which isn't acceptable in a freestanding
4820 // environment which only provides their non-fortified counterparts.
4821 //
4822 // Until we change clang and/or teach external users to check for availability
4823 // differently, disregard the "nobuiltin" attribute and TLI::has.
4824 //
4825 // PR23093.
4826
4827 Function *Callee = CI->getCalledFunction();
4828 bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
4829
4831 CI->getOperandBundlesAsDefs(OpBundles);
4832
4834 Builder.setDefaultOperandBundles(OpBundles);
4835
4836 // First, check that this is a known library functions and that the prototype
4837 // is correct.
4838 LibFunc Func = TLI->getLibFunc(*Callee);
4839 if (Func == NotLibFunc)
4840 return nullptr;
4841
4842 // We never change the calling convention.
4843 if (!ignoreCallingConv(Func) && !IsCallingConvC)
4844 return nullptr;
4845
4846 switch (Func) {
4847 case LibFunc_memcpy_chk:
4848 return optimizeMemCpyChk(CI, Builder);
4849 case LibFunc_mempcpy_chk:
4850 return optimizeMemPCpyChk(CI, Builder);
4851 case LibFunc_memmove_chk:
4852 return optimizeMemMoveChk(CI, Builder);
4853 case LibFunc_memset_chk:
4854 return optimizeMemSetChk(CI, Builder);
4855 case LibFunc_stpcpy_chk:
4856 case LibFunc_strcpy_chk:
4857 return optimizeStrpCpyChk(CI, Builder, Func);
4858 case LibFunc_strlen_chk:
4859 return optimizeStrLenChk(CI, Builder);
4860 case LibFunc_stpncpy_chk:
4861 case LibFunc_strncpy_chk:
4862 return optimizeStrpNCpyChk(CI, Builder, Func);
4863 case LibFunc_memccpy_chk:
4864 return optimizeMemCCpyChk(CI, Builder);
4865 case LibFunc_snprintf_chk:
4866 return optimizeSNPrintfChk(CI, Builder);
4867 case LibFunc_sprintf_chk:
4868 return optimizeSPrintfChk(CI, Builder);
4869 case LibFunc_strcat_chk:
4870 return optimizeStrCatChk(CI, Builder);
4871 case LibFunc_strlcat_chk:
4872 return optimizeStrLCat(CI, Builder);
4873 case LibFunc_strncat_chk:
4874 return optimizeStrNCatChk(CI, Builder);
4875 case LibFunc_strlcpy_chk:
4876 return optimizeStrLCpyChk(CI, Builder);
4877 case LibFunc_vsnprintf_chk:
4878 return optimizeVSNPrintfChk(CI, Builder);
4879 case LibFunc_vsprintf_chk:
4880 return optimizeVSPrintfChk(CI, Builder);
4881 default:
4882 break;
4883 }
4884 return nullptr;
4885}
4886
4888 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
4889 : 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.