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