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