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