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