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::optimizeMemPCpy(CallInst *CI, IRBuilder<> &B) {
1002   Value *Dst = CI->getArgOperand(0);
1003   Value *N = CI->getArgOperand(2);
1004   // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1005   CallInst *NewCI = B.CreateMemCpy(Dst, 1, CI->getArgOperand(1), 1, N);
1006   NewCI->setAttributes(CI->getAttributes());
1007   return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1008 }
1009 
1010 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B, bool isIntrinsic) {
1011   Value *Size = CI->getArgOperand(2);
1012   if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size))
1013     annotateDereferenceableBytes(CI, {0, 1}, LenC->getZExtValue());
1014 
1015   if (isIntrinsic)
1016     return nullptr;
1017 
1018   // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1019   B.CreateMemMove( CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size);
1020   return  CI->getArgOperand(0);
1021 }
1022 
1023 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
1024 Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
1025   // This has to be a memset of zeros (bzero).
1026   auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
1027   if (!FillValue || FillValue->getZExtValue() != 0)
1028     return nullptr;
1029 
1030   // TODO: We should handle the case where the malloc has more than one use.
1031   // This is necessary to optimize common patterns such as when the result of
1032   // the malloc is checked against null or when a memset intrinsic is used in
1033   // place of a memset library call.
1034   auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1035   if (!Malloc || !Malloc->hasOneUse())
1036     return nullptr;
1037 
1038   // Is the inner call really malloc()?
1039   Function *InnerCallee = Malloc->getCalledFunction();
1040   if (!InnerCallee)
1041     return nullptr;
1042 
1043   LibFunc Func;
1044   if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
1045       Func != LibFunc_malloc)
1046     return nullptr;
1047 
1048   // The memset must cover the same number of bytes that are malloc'd.
1049   if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1050     return nullptr;
1051 
1052   // Replace the malloc with a calloc. We need the data layout to know what the
1053   // actual size of a 'size_t' parameter is.
1054   B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1055   const DataLayout &DL = Malloc->getModule()->getDataLayout();
1056   IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
1057   if (Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1058                                  Malloc->getArgOperand(0),
1059                                  Malloc->getAttributes(), B, *TLI)) {
1060     substituteInParent(Malloc, Calloc);
1061     return Calloc;
1062   }
1063 
1064   return nullptr;
1065 }
1066 
1067 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B,
1068                                          bool isIntrinsic) {
1069   Value *Size = CI->getArgOperand(2);
1070   if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size))
1071     annotateDereferenceableBytes(CI, {0}, LenC->getZExtValue());
1072 
1073   if (isIntrinsic)
1074     return nullptr;
1075 
1076   if (auto *Calloc = foldMallocMemset(CI, B))
1077     return Calloc;
1078 
1079   // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1080   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1081   B.CreateMemSet(CI->getArgOperand(0), Val, Size, 1);
1082   return CI->getArgOperand(0);
1083 }
1084 
1085 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1086   if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1087     return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1088 
1089   return nullptr;
1090 }
1091 
1092 //===----------------------------------------------------------------------===//
1093 // Math Library Optimizations
1094 //===----------------------------------------------------------------------===//
1095 
1096 // Replace a libcall \p CI with a call to intrinsic \p IID
1097 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1098   // Propagate fast-math flags from the existing call to the new call.
1099   IRBuilder<>::FastMathFlagGuard Guard(B);
1100   B.setFastMathFlags(CI->getFastMathFlags());
1101 
1102   Module *M = CI->getModule();
1103   Value *V = CI->getArgOperand(0);
1104   Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1105   CallInst *NewCall = B.CreateCall(F, V);
1106   NewCall->takeName(CI);
1107   return NewCall;
1108 }
1109 
1110 /// Return a variant of Val with float type.
1111 /// Currently this works in two cases: If Val is an FPExtension of a float
1112 /// value to something bigger, simply return the operand.
1113 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1114 /// loss of precision do so.
1115 static Value *valueHasFloatPrecision(Value *Val) {
1116   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1117     Value *Op = Cast->getOperand(0);
1118     if (Op->getType()->isFloatTy())
1119       return Op;
1120   }
1121   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1122     APFloat F = Const->getValueAPF();
1123     bool losesInfo;
1124     (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
1125                     &losesInfo);
1126     if (!losesInfo)
1127       return ConstantFP::get(Const->getContext(), F);
1128   }
1129   return nullptr;
1130 }
1131 
1132 /// Shrink double -> float functions.
1133 static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
1134                                bool isBinary, bool isPrecise = false) {
1135   Function *CalleeFn = CI->getCalledFunction();
1136   if (!CI->getType()->isDoubleTy() || !CalleeFn)
1137     return nullptr;
1138 
1139   // If not all the uses of the function are converted to float, then bail out.
1140   // This matters if the precision of the result is more important than the
1141   // precision of the arguments.
1142   if (isPrecise)
1143     for (User *U : CI->users()) {
1144       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1145       if (!Cast || !Cast->getType()->isFloatTy())
1146         return nullptr;
1147     }
1148 
1149   // If this is something like 'g((double) float)', convert to 'gf(float)'.
1150   Value *V[2];
1151   V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1152   V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1153   if (!V[0] || (isBinary && !V[1]))
1154     return nullptr;
1155 
1156   StringRef CalleeNm = CalleeFn->getName();
1157   AttributeList CalleeAt = CalleeFn->getAttributes();
1158   bool CalleeIn = CalleeFn->isIntrinsic();
1159 
1160   // If call isn't an intrinsic, check that it isn't within a function with the
1161   // same name as the float version of this call, otherwise the result is an
1162   // infinite loop.  For example, from MinGW-w64:
1163   //
1164   // float expf(float val) { return (float) exp((double) val); }
1165   if (!CalleeIn) {
1166     const Function *Fn = CI->getFunction();
1167     StringRef FnName = Fn->getName();
1168     if (FnName.back() == 'f' &&
1169         FnName.size() == (CalleeNm.size() + 1) &&
1170         FnName.startswith(CalleeNm))
1171       return nullptr;
1172   }
1173 
1174   // Propagate the math semantics from the current function to the new function.
1175   IRBuilder<>::FastMathFlagGuard Guard(B);
1176   B.setFastMathFlags(CI->getFastMathFlags());
1177 
1178   // g((double) float) -> (double) gf(float)
1179   Value *R;
1180   if (CalleeIn) {
1181     Module *M = CI->getModule();
1182     Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1183     Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1184     R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
1185   }
1186   else
1187     R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1188                  : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
1189 
1190   return B.CreateFPExt(R, B.getDoubleTy());
1191 }
1192 
1193 /// Shrink double -> float for unary functions.
1194 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1195                                     bool isPrecise = false) {
1196   return optimizeDoubleFP(CI, B, false, isPrecise);
1197 }
1198 
1199 /// Shrink double -> float for binary functions.
1200 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1201                                      bool isPrecise = false) {
1202   return optimizeDoubleFP(CI, B, true, isPrecise);
1203 }
1204 
1205 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1206 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1207   if (!CI->isFast())
1208     return nullptr;
1209 
1210   // Propagate fast-math flags from the existing call to new instructions.
1211   IRBuilder<>::FastMathFlagGuard Guard(B);
1212   B.setFastMathFlags(CI->getFastMathFlags());
1213 
1214   Value *Real, *Imag;
1215   if (CI->getNumArgOperands() == 1) {
1216     Value *Op = CI->getArgOperand(0);
1217     assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1218     Real = B.CreateExtractValue(Op, 0, "real");
1219     Imag = B.CreateExtractValue(Op, 1, "imag");
1220   } else {
1221     assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1222     Real = CI->getArgOperand(0);
1223     Imag = CI->getArgOperand(1);
1224   }
1225 
1226   Value *RealReal = B.CreateFMul(Real, Real);
1227   Value *ImagImag = B.CreateFMul(Imag, Imag);
1228 
1229   Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1230                                               CI->getType());
1231   return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1232 }
1233 
1234 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1235                                       IRBuilder<> &B) {
1236   if (!isa<FPMathOperator>(Call))
1237     return nullptr;
1238 
1239   IRBuilder<>::FastMathFlagGuard Guard(B);
1240   B.setFastMathFlags(Call->getFastMathFlags());
1241 
1242   // TODO: Can this be shared to also handle LLVM intrinsics?
1243   Value *X;
1244   switch (Func) {
1245   case LibFunc_sin:
1246   case LibFunc_sinf:
1247   case LibFunc_sinl:
1248   case LibFunc_tan:
1249   case LibFunc_tanf:
1250   case LibFunc_tanl:
1251     // sin(-X) --> -sin(X)
1252     // tan(-X) --> -tan(X)
1253     if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
1254       return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
1255     break;
1256   case LibFunc_cos:
1257   case LibFunc_cosf:
1258   case LibFunc_cosl:
1259     // cos(-X) --> cos(X)
1260     if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1261       return B.CreateCall(Call->getCalledFunction(), X, "cos");
1262     break;
1263   default:
1264     break;
1265   }
1266   return nullptr;
1267 }
1268 
1269 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1270   // Multiplications calculated using Addition Chains.
1271   // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1272 
1273   assert(Exp != 0 && "Incorrect exponent 0 not handled");
1274 
1275   if (InnerChain[Exp])
1276     return InnerChain[Exp];
1277 
1278   static const unsigned AddChain[33][2] = {
1279       {0, 0}, // Unused.
1280       {0, 0}, // Unused (base case = pow1).
1281       {1, 1}, // Unused (pre-computed).
1282       {1, 2},  {2, 2},   {2, 3},  {3, 3},   {2, 5},  {4, 4},
1283       {1, 8},  {5, 5},   {1, 10}, {6, 6},   {4, 9},  {7, 7},
1284       {3, 12}, {8, 8},   {8, 9},  {2, 16},  {1, 18}, {10, 10},
1285       {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1286       {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1287   };
1288 
1289   InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1290                                  getPow(InnerChain, AddChain[Exp][1], B));
1291   return InnerChain[Exp];
1292 }
1293 
1294 // Return a properly extended 32-bit integer if the operation is an itofp.
1295 static Value *getIntToFPVal(Value *I2F, IRBuilder<> &B) {
1296   if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
1297     Value *Op = cast<Instruction>(I2F)->getOperand(0);
1298     // Make sure that the exponent fits inside an int32_t,
1299     // thus avoiding any range issues that FP has not.
1300     unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
1301     if (BitWidth < 32 ||
1302         (BitWidth == 32 && isa<SIToFPInst>(I2F)))
1303       return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getInt32Ty())
1304                                   : B.CreateZExt(Op, B.getInt32Ty());
1305   }
1306 
1307   return nullptr;
1308 }
1309 
1310 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
1311 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
1312 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
1313 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1314   Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1315   AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1316   Module *Mod = Pow->getModule();
1317   Type *Ty = Pow->getType();
1318   bool Ignored;
1319 
1320   // Evaluate special cases related to a nested function as the base.
1321 
1322   // pow(exp(x), y) -> exp(x * y)
1323   // pow(exp2(x), y) -> exp2(x * y)
1324   // If exp{,2}() is used only once, it is better to fold two transcendental
1325   // math functions into one.  If used again, exp{,2}() would still have to be
1326   // called with the original argument, then keep both original transcendental
1327   // functions.  However, this transformation is only safe with fully relaxed
1328   // math semantics, since, besides rounding differences, it changes overflow
1329   // and underflow behavior quite dramatically.  For example:
1330   //   pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1331   // Whereas:
1332   //   exp(1000 * 0.001) = exp(1)
1333   // TODO: Loosen the requirement for fully relaxed math semantics.
1334   // TODO: Handle exp10() when more targets have it available.
1335   CallInst *BaseFn = dyn_cast<CallInst>(Base);
1336   if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
1337     LibFunc LibFn;
1338 
1339     Function *CalleeFn = BaseFn->getCalledFunction();
1340     if (CalleeFn &&
1341         TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1342       StringRef ExpName;
1343       Intrinsic::ID ID;
1344       Value *ExpFn;
1345       LibFunc LibFnFloat;
1346       LibFunc LibFnDouble;
1347       LibFunc LibFnLongDouble;
1348 
1349       switch (LibFn) {
1350       default:
1351         return nullptr;
1352       case LibFunc_expf:  case LibFunc_exp:  case LibFunc_expl:
1353         ExpName = TLI->getName(LibFunc_exp);
1354         ID = Intrinsic::exp;
1355         LibFnFloat = LibFunc_expf;
1356         LibFnDouble = LibFunc_exp;
1357         LibFnLongDouble = LibFunc_expl;
1358         break;
1359       case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
1360         ExpName = TLI->getName(LibFunc_exp2);
1361         ID = Intrinsic::exp2;
1362         LibFnFloat = LibFunc_exp2f;
1363         LibFnDouble = LibFunc_exp2;
1364         LibFnLongDouble = LibFunc_exp2l;
1365         break;
1366       }
1367 
1368       // Create new exp{,2}() with the product as its argument.
1369       Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1370       ExpFn = BaseFn->doesNotAccessMemory()
1371               ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1372                              FMul, ExpName)
1373               : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1374                                      LibFnLongDouble, B,
1375                                      BaseFn->getAttributes());
1376 
1377       // Since the new exp{,2}() is different from the original one, dead code
1378       // elimination cannot be trusted to remove it, since it may have side
1379       // effects (e.g., errno).  When the only consumer for the original
1380       // exp{,2}() is pow(), then it has to be explicitly erased.
1381       substituteInParent(BaseFn, ExpFn);
1382       return ExpFn;
1383     }
1384   }
1385 
1386   // Evaluate special cases related to a constant base.
1387 
1388   const APFloat *BaseF;
1389   if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1390     return nullptr;
1391 
1392   // pow(2.0, itofp(x)) -> ldexp(1.0, x)
1393   if (match(Base, m_SpecificFP(2.0)) &&
1394       (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
1395       hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1396     if (Value *ExpoI = getIntToFPVal(Expo, B))
1397       return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, TLI,
1398                                    LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1399                                    B, Attrs);
1400   }
1401 
1402   // pow(2.0 ** n, x) -> exp2(n * x)
1403   if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1404     APFloat BaseR = APFloat(1.0);
1405     BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1406     BaseR = BaseR / *BaseF;
1407     bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
1408     const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1409     APSInt NI(64, false);
1410     if ((IsInteger || IsReciprocal) &&
1411         NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1412             APFloat::opOK &&
1413         NI > 1 && NI.isPowerOf2()) {
1414       double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1415       Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1416       if (Pow->doesNotAccessMemory())
1417         return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1418                             FMul, "exp2");
1419       else
1420         return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1421                                     LibFunc_exp2l, B, Attrs);
1422     }
1423   }
1424 
1425   // pow(10.0, x) -> exp10(x)
1426   // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1427   if (match(Base, m_SpecificFP(10.0)) &&
1428       hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1429     return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1430                                 LibFunc_exp10l, B, Attrs);
1431 
1432   // pow(n, x) -> exp2(log2(n) * x)
1433   if (Pow->hasOneUse() && Pow->hasApproxFunc() && Pow->hasNoNaNs() &&
1434       Pow->hasNoInfs() && BaseF->isNormal() && !BaseF->isNegative()) {
1435     Value *Log = nullptr;
1436     if (Ty->isFloatTy())
1437       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1438     else if (Ty->isDoubleTy())
1439       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1440 
1441     if (Log) {
1442       Value *FMul = B.CreateFMul(Log, Expo, "mul");
1443       if (Pow->doesNotAccessMemory())
1444         return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1445                             FMul, "exp2");
1446       else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l))
1447         return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1448                                     LibFunc_exp2l, B, Attrs);
1449     }
1450   }
1451 
1452   return nullptr;
1453 }
1454 
1455 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1456                           Module *M, IRBuilder<> &B,
1457                           const TargetLibraryInfo *TLI) {
1458   // If errno is never set, then use the intrinsic for sqrt().
1459   if (NoErrno) {
1460     Function *SqrtFn =
1461         Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1462     return B.CreateCall(SqrtFn, V, "sqrt");
1463   }
1464 
1465   // Otherwise, use the libcall for sqrt().
1466   if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
1467     // TODO: We also should check that the target can in fact lower the sqrt()
1468     // libcall. We currently have no way to ask this question, so we ask if
1469     // the target has a sqrt() libcall, which is not exactly the same.
1470     return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1471                                 LibFunc_sqrtl, B, Attrs);
1472 
1473   return nullptr;
1474 }
1475 
1476 /// Use square root in place of pow(x, +/-0.5).
1477 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1478   Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1479   AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1480   Module *Mod = Pow->getModule();
1481   Type *Ty = Pow->getType();
1482 
1483   const APFloat *ExpoF;
1484   if (!match(Expo, m_APFloat(ExpoF)) ||
1485       (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1486     return nullptr;
1487 
1488   Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1489   if (!Sqrt)
1490     return nullptr;
1491 
1492   // Handle signed zero base by expanding to fabs(sqrt(x)).
1493   if (!Pow->hasNoSignedZeros()) {
1494     Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1495     Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1496   }
1497 
1498   // Handle non finite base by expanding to
1499   // (x == -infinity ? +infinity : sqrt(x)).
1500   if (!Pow->hasNoInfs()) {
1501     Value *PosInf = ConstantFP::getInfinity(Ty),
1502           *NegInf = ConstantFP::getInfinity(Ty, true);
1503     Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1504     Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1505   }
1506 
1507   // If the exponent is negative, then get the reciprocal.
1508   if (ExpoF->isNegative())
1509     Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1510 
1511   return Sqrt;
1512 }
1513 
1514 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1515                                            IRBuilder<> &B) {
1516   Value *Args[] = {Base, Expo};
1517   Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType());
1518   return B.CreateCall(F, Args);
1519 }
1520 
1521 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1522   Value *Base = Pow->getArgOperand(0);
1523   Value *Expo = Pow->getArgOperand(1);
1524   Function *Callee = Pow->getCalledFunction();
1525   StringRef Name = Callee->getName();
1526   Type *Ty = Pow->getType();
1527   Module *M = Pow->getModule();
1528   Value *Shrunk = nullptr;
1529   bool AllowApprox = Pow->hasApproxFunc();
1530   bool Ignored;
1531 
1532   // Bail out if simplifying libcalls to pow() is disabled.
1533   if (!hasFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1534     return nullptr;
1535 
1536   // Propagate the math semantics from the call to any created instructions.
1537   IRBuilder<>::FastMathFlagGuard Guard(B);
1538   B.setFastMathFlags(Pow->getFastMathFlags());
1539 
1540   // Shrink pow() to powf() if the arguments are single precision,
1541   // unless the result is expected to be double precision.
1542   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
1543       hasFloatVersion(Name))
1544     Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1545 
1546   // Evaluate special cases related to the base.
1547 
1548   // pow(1.0, x) -> 1.0
1549   if (match(Base, m_FPOne()))
1550     return Base;
1551 
1552   if (Value *Exp = replacePowWithExp(Pow, B))
1553     return Exp;
1554 
1555   // Evaluate special cases related to the exponent.
1556 
1557   // pow(x, -1.0) -> 1.0 / x
1558   if (match(Expo, m_SpecificFP(-1.0)))
1559     return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1560 
1561   // pow(x, +/-0.0) -> 1.0
1562   if (match(Expo, m_AnyZeroFP()))
1563     return ConstantFP::get(Ty, 1.0);
1564 
1565   // pow(x, 1.0) -> x
1566   if (match(Expo, m_FPOne()))
1567     return Base;
1568 
1569   // pow(x, 2.0) -> x * x
1570   if (match(Expo, m_SpecificFP(2.0)))
1571     return B.CreateFMul(Base, Base, "square");
1572 
1573   if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1574     return Sqrt;
1575 
1576   // pow(x, n) -> x * x * x * ...
1577   const APFloat *ExpoF;
1578   if (AllowApprox && match(Expo, m_APFloat(ExpoF))) {
1579     // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
1580     // If the exponent is an integer+0.5 we generate a call to sqrt and an
1581     // additional fmul.
1582     // TODO: This whole transformation should be backend specific (e.g. some
1583     //       backends might prefer libcalls or the limit for the exponent might
1584     //       be different) and it should also consider optimizing for size.
1585     APFloat LimF(ExpoF->getSemantics(), 33.0),
1586             ExpoA(abs(*ExpoF));
1587     if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1588       // This transformation applies to integer or integer+0.5 exponents only.
1589       // For integer+0.5, we create a sqrt(Base) call.
1590       Value *Sqrt = nullptr;
1591       if (!ExpoA.isInteger()) {
1592         APFloat Expo2 = ExpoA;
1593         // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1594         // is no floating point exception and the result is an integer, then
1595         // ExpoA == integer + 0.5
1596         if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1597           return nullptr;
1598 
1599         if (!Expo2.isInteger())
1600           return nullptr;
1601 
1602         Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1603                            Pow->doesNotAccessMemory(), M, B, TLI);
1604       }
1605 
1606       // We will memoize intermediate products of the Addition Chain.
1607       Value *InnerChain[33] = {nullptr};
1608       InnerChain[1] = Base;
1609       InnerChain[2] = B.CreateFMul(Base, Base, "square");
1610 
1611       // We cannot readily convert a non-double type (like float) to a double.
1612       // So we first convert it to something which could be converted to double.
1613       ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1614       Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
1615 
1616       // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1617       if (Sqrt)
1618         FMul = B.CreateFMul(FMul, Sqrt);
1619 
1620       // If the exponent is negative, then get the reciprocal.
1621       if (ExpoF->isNegative())
1622         FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
1623 
1624       return FMul;
1625     }
1626 
1627     APSInt IntExpo(32, /*isUnsigned=*/false);
1628     // powf(x, n) -> powi(x, n) if n is a constant signed integer value
1629     if (ExpoF->isInteger() &&
1630         ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1631             APFloat::opOK) {
1632       return createPowWithIntegerExponent(
1633           Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B);
1634     }
1635   }
1636 
1637   // powf(x, itofp(y)) -> powi(x, y)
1638   if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
1639     if (Value *ExpoI = getIntToFPVal(Expo, B))
1640       return createPowWithIntegerExponent(Base, ExpoI, M, B);
1641   }
1642 
1643   return Shrunk;
1644 }
1645 
1646 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1647   Function *Callee = CI->getCalledFunction();
1648   StringRef Name = Callee->getName();
1649   Value *Ret = nullptr;
1650   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
1651       hasFloatVersion(Name))
1652     Ret = optimizeUnaryDoubleFP(CI, B, true);
1653 
1654   Type *Ty = CI->getType();
1655   Value *Op = CI->getArgOperand(0);
1656 
1657   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1658   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1659   if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
1660       hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1661     if (Value *Exp = getIntToFPVal(Op, B))
1662       return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
1663                                    LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1664                                    B, CI->getCalledFunction()->getAttributes());
1665   }
1666 
1667   return Ret;
1668 }
1669 
1670 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1671   // If we can shrink the call to a float function rather than a double
1672   // function, do that first.
1673   Function *Callee = CI->getCalledFunction();
1674   StringRef Name = Callee->getName();
1675   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1676     if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1677       return Ret;
1678 
1679   // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
1680   // the intrinsics for improved optimization (for example, vectorization).
1681   // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
1682   // From the C standard draft WG14/N1256:
1683   // "Ideally, fmax would be sensitive to the sign of zero, for example
1684   // fmax(-0.0, +0.0) would return +0; however, implementation in software
1685   // might be impractical."
1686   IRBuilder<>::FastMathFlagGuard Guard(B);
1687   FastMathFlags FMF = CI->getFastMathFlags();
1688   FMF.setNoSignedZeros();
1689   B.setFastMathFlags(FMF);
1690 
1691   Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
1692                                                            : Intrinsic::maxnum;
1693   Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
1694   return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) });
1695 }
1696 
1697 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1698   Function *Callee = CI->getCalledFunction();
1699   Value *Ret = nullptr;
1700   StringRef Name = Callee->getName();
1701   if (UnsafeFPShrink && hasFloatVersion(Name))
1702     Ret = optimizeUnaryDoubleFP(CI, B, true);
1703 
1704   if (!CI->isFast())
1705     return Ret;
1706   Value *Op1 = CI->getArgOperand(0);
1707   auto *OpC = dyn_cast<CallInst>(Op1);
1708 
1709   // The earlier call must also be 'fast' in order to do these transforms.
1710   if (!OpC || !OpC->isFast())
1711     return Ret;
1712 
1713   // log(pow(x,y)) -> y*log(x)
1714   // This is only applicable to log, log2, log10.
1715   if (Name != "log" && Name != "log2" && Name != "log10")
1716     return Ret;
1717 
1718   IRBuilder<>::FastMathFlagGuard Guard(B);
1719   FastMathFlags FMF;
1720   FMF.setFast();
1721   B.setFastMathFlags(FMF);
1722 
1723   LibFunc Func;
1724   Function *F = OpC->getCalledFunction();
1725   if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1726       Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1727     return B.CreateFMul(OpC->getArgOperand(1),
1728       emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1729                            Callee->getAttributes()), "mul");
1730 
1731   // log(exp2(y)) -> y*log(2)
1732   if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1733       TLI->has(Func) && Func == LibFunc_exp2)
1734     return B.CreateFMul(
1735         OpC->getArgOperand(0),
1736         emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1737                              Callee->getName(), B, Callee->getAttributes()),
1738         "logmul");
1739   return Ret;
1740 }
1741 
1742 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1743   Function *Callee = CI->getCalledFunction();
1744   Value *Ret = nullptr;
1745   // TODO: Once we have a way (other than checking for the existince of the
1746   // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1747   // condition below.
1748   if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1749                                   Callee->getIntrinsicID() == Intrinsic::sqrt))
1750     Ret = optimizeUnaryDoubleFP(CI, B, true);
1751 
1752   if (!CI->isFast())
1753     return Ret;
1754 
1755   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1756   if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
1757     return Ret;
1758 
1759   // We're looking for a repeated factor in a multiplication tree,
1760   // so we can do this fold: sqrt(x * x) -> fabs(x);
1761   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1762   Value *Op0 = I->getOperand(0);
1763   Value *Op1 = I->getOperand(1);
1764   Value *RepeatOp = nullptr;
1765   Value *OtherOp = nullptr;
1766   if (Op0 == Op1) {
1767     // Simple match: the operands of the multiply are identical.
1768     RepeatOp = Op0;
1769   } else {
1770     // Look for a more complicated pattern: one of the operands is itself
1771     // a multiply, so search for a common factor in that multiply.
1772     // Note: We don't bother looking any deeper than this first level or for
1773     // variations of this pattern because instcombine's visitFMUL and/or the
1774     // reassociation pass should give us this form.
1775     Value *OtherMul0, *OtherMul1;
1776     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1777       // Pattern: sqrt((x * y) * z)
1778       if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
1779         // Matched: sqrt((x * x) * z)
1780         RepeatOp = OtherMul0;
1781         OtherOp = Op1;
1782       }
1783     }
1784   }
1785   if (!RepeatOp)
1786     return Ret;
1787 
1788   // Fast math flags for any created instructions should match the sqrt
1789   // and multiply.
1790   IRBuilder<>::FastMathFlagGuard Guard(B);
1791   B.setFastMathFlags(I->getFastMathFlags());
1792 
1793   // If we found a repeated factor, hoist it out of the square root and
1794   // replace it with the fabs of that factor.
1795   Module *M = Callee->getParent();
1796   Type *ArgType = I->getType();
1797   Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1798   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1799   if (OtherOp) {
1800     // If we found a non-repeated factor, we still need to get its square
1801     // root. We then multiply that by the value that was simplified out
1802     // of the square root calculation.
1803     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1804     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1805     return B.CreateFMul(FabsCall, SqrtCall);
1806   }
1807   return FabsCall;
1808 }
1809 
1810 // TODO: Generalize to handle any trig function and its inverse.
1811 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1812   Function *Callee = CI->getCalledFunction();
1813   Value *Ret = nullptr;
1814   StringRef Name = Callee->getName();
1815   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1816     Ret = optimizeUnaryDoubleFP(CI, B, true);
1817 
1818   Value *Op1 = CI->getArgOperand(0);
1819   auto *OpC = dyn_cast<CallInst>(Op1);
1820   if (!OpC)
1821     return Ret;
1822 
1823   // Both calls must be 'fast' in order to remove them.
1824   if (!CI->isFast() || !OpC->isFast())
1825     return Ret;
1826 
1827   // tan(atan(x)) -> x
1828   // tanf(atanf(x)) -> x
1829   // tanl(atanl(x)) -> x
1830   LibFunc Func;
1831   Function *F = OpC->getCalledFunction();
1832   if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1833       ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1834        (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1835        (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1836     Ret = OpC->getArgOperand(0);
1837   return Ret;
1838 }
1839 
1840 static bool isTrigLibCall(CallInst *CI) {
1841   // We can only hope to do anything useful if we can ignore things like errno
1842   // and floating-point exceptions.
1843   // We already checked the prototype.
1844   return CI->hasFnAttr(Attribute::NoUnwind) &&
1845          CI->hasFnAttr(Attribute::ReadNone);
1846 }
1847 
1848 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1849                              bool UseFloat, Value *&Sin, Value *&Cos,
1850                              Value *&SinCos) {
1851   Type *ArgTy = Arg->getType();
1852   Type *ResTy;
1853   StringRef Name;
1854 
1855   Triple T(OrigCallee->getParent()->getTargetTriple());
1856   if (UseFloat) {
1857     Name = "__sincospif_stret";
1858 
1859     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1860     // x86_64 can't use {float, float} since that would be returned in both
1861     // xmm0 and xmm1, which isn't what a real struct would do.
1862     ResTy = T.getArch() == Triple::x86_64
1863                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1864                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1865   } else {
1866     Name = "__sincospi_stret";
1867     ResTy = StructType::get(ArgTy, ArgTy);
1868   }
1869 
1870   Module *M = OrigCallee->getParent();
1871   FunctionCallee Callee =
1872       M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
1873 
1874   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1875     // If the argument is an instruction, it must dominate all uses so put our
1876     // sincos call there.
1877     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1878   } else {
1879     // Otherwise (e.g. for a constant) the beginning of the function is as
1880     // good a place as any.
1881     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1882     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1883   }
1884 
1885   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1886 
1887   if (SinCos->getType()->isStructTy()) {
1888     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1889     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1890   } else {
1891     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1892                                  "sinpi");
1893     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1894                                  "cospi");
1895   }
1896 }
1897 
1898 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1899   // Make sure the prototype is as expected, otherwise the rest of the
1900   // function is probably invalid and likely to abort.
1901   if (!isTrigLibCall(CI))
1902     return nullptr;
1903 
1904   Value *Arg = CI->getArgOperand(0);
1905   SmallVector<CallInst *, 1> SinCalls;
1906   SmallVector<CallInst *, 1> CosCalls;
1907   SmallVector<CallInst *, 1> SinCosCalls;
1908 
1909   bool IsFloat = Arg->getType()->isFloatTy();
1910 
1911   // Look for all compatible sinpi, cospi and sincospi calls with the same
1912   // argument. If there are enough (in some sense) we can make the
1913   // substitution.
1914   Function *F = CI->getFunction();
1915   for (User *U : Arg->users())
1916     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1917 
1918   // It's only worthwhile if both sinpi and cospi are actually used.
1919   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1920     return nullptr;
1921 
1922   Value *Sin, *Cos, *SinCos;
1923   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1924 
1925   auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1926                                  Value *Res) {
1927     for (CallInst *C : Calls)
1928       replaceAllUsesWith(C, Res);
1929   };
1930 
1931   replaceTrigInsts(SinCalls, Sin);
1932   replaceTrigInsts(CosCalls, Cos);
1933   replaceTrigInsts(SinCosCalls, SinCos);
1934 
1935   return nullptr;
1936 }
1937 
1938 void LibCallSimplifier::classifyArgUse(
1939     Value *Val, Function *F, bool IsFloat,
1940     SmallVectorImpl<CallInst *> &SinCalls,
1941     SmallVectorImpl<CallInst *> &CosCalls,
1942     SmallVectorImpl<CallInst *> &SinCosCalls) {
1943   CallInst *CI = dyn_cast<CallInst>(Val);
1944 
1945   if (!CI)
1946     return;
1947 
1948   // Don't consider calls in other functions.
1949   if (CI->getFunction() != F)
1950     return;
1951 
1952   Function *Callee = CI->getCalledFunction();
1953   LibFunc Func;
1954   if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1955       !isTrigLibCall(CI))
1956     return;
1957 
1958   if (IsFloat) {
1959     if (Func == LibFunc_sinpif)
1960       SinCalls.push_back(CI);
1961     else if (Func == LibFunc_cospif)
1962       CosCalls.push_back(CI);
1963     else if (Func == LibFunc_sincospif_stret)
1964       SinCosCalls.push_back(CI);
1965   } else {
1966     if (Func == LibFunc_sinpi)
1967       SinCalls.push_back(CI);
1968     else if (Func == LibFunc_cospi)
1969       CosCalls.push_back(CI);
1970     else if (Func == LibFunc_sincospi_stret)
1971       SinCosCalls.push_back(CI);
1972   }
1973 }
1974 
1975 //===----------------------------------------------------------------------===//
1976 // Integer Library Call Optimizations
1977 //===----------------------------------------------------------------------===//
1978 
1979 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1980   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1981   Value *Op = CI->getArgOperand(0);
1982   Type *ArgType = Op->getType();
1983   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1984                                           Intrinsic::cttz, ArgType);
1985   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1986   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1987   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1988 
1989   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1990   return B.CreateSelect(Cond, V, B.getInt32(0));
1991 }
1992 
1993 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1994   // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1995   Value *Op = CI->getArgOperand(0);
1996   Type *ArgType = Op->getType();
1997   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1998                                           Intrinsic::ctlz, ArgType);
1999   Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2000   V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2001                   V);
2002   return B.CreateIntCast(V, CI->getType(), false);
2003 }
2004 
2005 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
2006   // abs(x) -> x <s 0 ? -x : x
2007   // The negation has 'nsw' because abs of INT_MIN is undefined.
2008   Value *X = CI->getArgOperand(0);
2009   Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
2010   Value *NegX = B.CreateNSWNeg(X, "neg");
2011   return B.CreateSelect(IsNeg, NegX, X);
2012 }
2013 
2014 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
2015   // isdigit(c) -> (c-'0') <u 10
2016   Value *Op = CI->getArgOperand(0);
2017   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2018   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2019   return B.CreateZExt(Op, CI->getType());
2020 }
2021 
2022 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
2023   // isascii(c) -> c <u 128
2024   Value *Op = CI->getArgOperand(0);
2025   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2026   return B.CreateZExt(Op, CI->getType());
2027 }
2028 
2029 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
2030   // toascii(c) -> c & 0x7f
2031   return B.CreateAnd(CI->getArgOperand(0),
2032                      ConstantInt::get(CI->getType(), 0x7F));
2033 }
2034 
2035 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
2036   StringRef Str;
2037   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2038     return nullptr;
2039 
2040   return convertStrToNumber(CI, Str, 10);
2041 }
2042 
2043 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
2044   StringRef Str;
2045   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2046     return nullptr;
2047 
2048   if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
2049     return nullptr;
2050 
2051   if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2052     return convertStrToNumber(CI, Str, CInt->getSExtValue());
2053   }
2054 
2055   return nullptr;
2056 }
2057 
2058 //===----------------------------------------------------------------------===//
2059 // Formatting and IO Library Call Optimizations
2060 //===----------------------------------------------------------------------===//
2061 
2062 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
2063 
2064 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
2065                                                  int StreamArg) {
2066   Function *Callee = CI->getCalledFunction();
2067   // Error reporting calls should be cold, mark them as such.
2068   // This applies even to non-builtin calls: it is only a hint and applies to
2069   // functions that the frontend might not understand as builtins.
2070 
2071   // This heuristic was suggested in:
2072   // Improving Static Branch Prediction in a Compiler
2073   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2074   // Proceedings of PACT'98, Oct. 1998, IEEE
2075   if (!CI->hasFnAttr(Attribute::Cold) &&
2076       isReportingError(Callee, CI, StreamArg)) {
2077     CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
2078   }
2079 
2080   return nullptr;
2081 }
2082 
2083 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
2084   if (!Callee || !Callee->isDeclaration())
2085     return false;
2086 
2087   if (StreamArg < 0)
2088     return true;
2089 
2090   // These functions might be considered cold, but only if their stream
2091   // argument is stderr.
2092 
2093   if (StreamArg >= (int)CI->getNumArgOperands())
2094     return false;
2095   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2096   if (!LI)
2097     return false;
2098   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2099   if (!GV || !GV->isDeclaration())
2100     return false;
2101   return GV->getName() == "stderr";
2102 }
2103 
2104 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
2105   // Check for a fixed format string.
2106   StringRef FormatStr;
2107   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
2108     return nullptr;
2109 
2110   // Empty format string -> noop.
2111   if (FormatStr.empty()) // Tolerate printf's declared void.
2112     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
2113 
2114   // Do not do any of the following transformations if the printf return value
2115   // is used, in general the printf return value is not compatible with either
2116   // putchar() or puts().
2117   if (!CI->use_empty())
2118     return nullptr;
2119 
2120   // printf("x") -> putchar('x'), even for "%" and "%%".
2121   if (FormatStr.size() == 1 || FormatStr == "%%")
2122     return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
2123 
2124   // printf("%s", "a") --> putchar('a')
2125   if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2126     StringRef ChrStr;
2127     if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2128       return nullptr;
2129     if (ChrStr.size() != 1)
2130       return nullptr;
2131     return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
2132   }
2133 
2134   // printf("foo\n") --> puts("foo")
2135   if (FormatStr[FormatStr.size() - 1] == '\n' &&
2136       FormatStr.find('%') == StringRef::npos) { // No format characters.
2137     // Create a string literal with no \n on it.  We expect the constant merge
2138     // pass to be run after this pass, to merge duplicate strings.
2139     FormatStr = FormatStr.drop_back();
2140     Value *GV = B.CreateGlobalString(FormatStr, "str");
2141     return emitPutS(GV, B, TLI);
2142   }
2143 
2144   // Optimize specific format strings.
2145   // printf("%c", chr) --> putchar(chr)
2146   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
2147       CI->getArgOperand(1)->getType()->isIntegerTy())
2148     return emitPutChar(CI->getArgOperand(1), B, TLI);
2149 
2150   // printf("%s\n", str) --> puts(str)
2151   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
2152       CI->getArgOperand(1)->getType()->isPointerTy())
2153     return emitPutS(CI->getArgOperand(1), B, TLI);
2154   return nullptr;
2155 }
2156 
2157 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2158 
2159   Function *Callee = CI->getCalledFunction();
2160   FunctionType *FT = Callee->getFunctionType();
2161   if (Value *V = optimizePrintFString(CI, B)) {
2162     return V;
2163   }
2164 
2165   // printf(format, ...) -> iprintf(format, ...) if no floating point
2166   // arguments.
2167   if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
2168     Module *M = B.GetInsertBlock()->getParent()->getParent();
2169     FunctionCallee IPrintFFn =
2170         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
2171     CallInst *New = cast<CallInst>(CI->clone());
2172     New->setCalledFunction(IPrintFFn);
2173     B.Insert(New);
2174     return New;
2175   }
2176 
2177   // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2178   // arguments.
2179   if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
2180     Module *M = B.GetInsertBlock()->getParent()->getParent();
2181     auto SmallPrintFFn =
2182         M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
2183                                FT, Callee->getAttributes());
2184     CallInst *New = cast<CallInst>(CI->clone());
2185     New->setCalledFunction(SmallPrintFFn);
2186     B.Insert(New);
2187     return New;
2188   }
2189 
2190   return nullptr;
2191 }
2192 
2193 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2194   // Check for a fixed format string.
2195   StringRef FormatStr;
2196   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2197     return nullptr;
2198 
2199   // If we just have a format string (nothing else crazy) transform it.
2200   if (CI->getNumArgOperands() == 2) {
2201     // Make sure there's no % in the constant array.  We could try to handle
2202     // %% -> % in the future if we cared.
2203     if (FormatStr.find('%') != StringRef::npos)
2204       return nullptr; // we found a format specifier, bail out.
2205 
2206     // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2207     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2208                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2209                                     FormatStr.size() + 1)); // Copy the null byte.
2210     return ConstantInt::get(CI->getType(), FormatStr.size());
2211   }
2212 
2213   // The remaining optimizations require the format string to be "%s" or "%c"
2214   // and have an extra operand.
2215   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2216       CI->getNumArgOperands() < 3)
2217     return nullptr;
2218 
2219   // Decode the second character of the format string.
2220   if (FormatStr[1] == 'c') {
2221     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2222     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2223       return nullptr;
2224     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2225     Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2226     B.CreateStore(V, Ptr);
2227     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2228     B.CreateStore(B.getInt8(0), Ptr);
2229 
2230     return ConstantInt::get(CI->getType(), 1);
2231   }
2232 
2233   if (FormatStr[1] == 's') {
2234     // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2235     // strlen(str)+1)
2236     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2237       return nullptr;
2238 
2239     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
2240     if (!Len)
2241       return nullptr;
2242     Value *IncLen =
2243         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2244     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
2245 
2246     // The sprintf result is the unincremented number of bytes in the string.
2247     return B.CreateIntCast(Len, CI->getType(), false);
2248   }
2249   return nullptr;
2250 }
2251 
2252 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2253   Function *Callee = CI->getCalledFunction();
2254   FunctionType *FT = Callee->getFunctionType();
2255   if (Value *V = optimizeSPrintFString(CI, B)) {
2256     return V;
2257   }
2258 
2259   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2260   // point arguments.
2261   if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
2262     Module *M = B.GetInsertBlock()->getParent()->getParent();
2263     FunctionCallee SIPrintFFn =
2264         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2265     CallInst *New = cast<CallInst>(CI->clone());
2266     New->setCalledFunction(SIPrintFFn);
2267     B.Insert(New);
2268     return New;
2269   }
2270 
2271   // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2272   // floating point arguments.
2273   if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
2274     Module *M = B.GetInsertBlock()->getParent()->getParent();
2275     auto SmallSPrintFFn =
2276         M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
2277                                FT, Callee->getAttributes());
2278     CallInst *New = cast<CallInst>(CI->clone());
2279     New->setCalledFunction(SmallSPrintFFn);
2280     B.Insert(New);
2281     return New;
2282   }
2283 
2284   return nullptr;
2285 }
2286 
2287 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2288   // Check for a fixed format string.
2289   StringRef FormatStr;
2290   if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2291     return nullptr;
2292 
2293   // Check for size
2294   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2295   if (!Size)
2296     return nullptr;
2297 
2298   uint64_t N = Size->getZExtValue();
2299 
2300   // If we just have a format string (nothing else crazy) transform it.
2301   if (CI->getNumArgOperands() == 3) {
2302     // Make sure there's no % in the constant array.  We could try to handle
2303     // %% -> % in the future if we cared.
2304     if (FormatStr.find('%') != StringRef::npos)
2305       return nullptr; // we found a format specifier, bail out.
2306 
2307     if (N == 0)
2308       return ConstantInt::get(CI->getType(), FormatStr.size());
2309     else if (N < FormatStr.size() + 1)
2310       return nullptr;
2311 
2312     // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
2313     // strlen(fmt)+1)
2314     B.CreateMemCpy(
2315         CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2316         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2317                          FormatStr.size() + 1)); // Copy the null byte.
2318     return ConstantInt::get(CI->getType(), FormatStr.size());
2319   }
2320 
2321   // The remaining optimizations require the format string to be "%s" or "%c"
2322   // and have an extra operand.
2323   if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2324       CI->getNumArgOperands() == 4) {
2325 
2326     // Decode the second character of the format string.
2327     if (FormatStr[1] == 'c') {
2328       if (N == 0)
2329         return ConstantInt::get(CI->getType(), 1);
2330       else if (N == 1)
2331         return nullptr;
2332 
2333       // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2334       if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2335         return nullptr;
2336       Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2337       Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2338       B.CreateStore(V, Ptr);
2339       Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2340       B.CreateStore(B.getInt8(0), Ptr);
2341 
2342       return ConstantInt::get(CI->getType(), 1);
2343     }
2344 
2345     if (FormatStr[1] == 's') {
2346       // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2347       StringRef Str;
2348       if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2349         return nullptr;
2350 
2351       if (N == 0)
2352         return ConstantInt::get(CI->getType(), Str.size());
2353       else if (N < Str.size() + 1)
2354         return nullptr;
2355 
2356       B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2357                      ConstantInt::get(CI->getType(), Str.size() + 1));
2358 
2359       // The snprintf result is the unincremented number of bytes in the string.
2360       return ConstantInt::get(CI->getType(), Str.size());
2361     }
2362   }
2363   return nullptr;
2364 }
2365 
2366 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2367   if (Value *V = optimizeSnPrintFString(CI, B)) {
2368     return V;
2369   }
2370 
2371   return nullptr;
2372 }
2373 
2374 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2375   optimizeErrorReporting(CI, B, 0);
2376 
2377   // All the optimizations depend on the format string.
2378   StringRef FormatStr;
2379   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2380     return nullptr;
2381 
2382   // Do not do any of the following transformations if the fprintf return
2383   // value is used, in general the fprintf return value is not compatible
2384   // with fwrite(), fputc() or fputs().
2385   if (!CI->use_empty())
2386     return nullptr;
2387 
2388   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2389   if (CI->getNumArgOperands() == 2) {
2390     // Could handle %% -> % if we cared.
2391     if (FormatStr.find('%') != StringRef::npos)
2392       return nullptr; // We found a format specifier.
2393 
2394     return emitFWrite(
2395         CI->getArgOperand(1),
2396         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2397         CI->getArgOperand(0), B, DL, TLI);
2398   }
2399 
2400   // The remaining optimizations require the format string to be "%s" or "%c"
2401   // and have an extra operand.
2402   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2403       CI->getNumArgOperands() < 3)
2404     return nullptr;
2405 
2406   // Decode the second character of the format string.
2407   if (FormatStr[1] == 'c') {
2408     // fprintf(F, "%c", chr) --> fputc(chr, F)
2409     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2410       return nullptr;
2411     return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2412   }
2413 
2414   if (FormatStr[1] == 's') {
2415     // fprintf(F, "%s", str) --> fputs(str, F)
2416     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2417       return nullptr;
2418     return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2419   }
2420   return nullptr;
2421 }
2422 
2423 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2424   Function *Callee = CI->getCalledFunction();
2425   FunctionType *FT = Callee->getFunctionType();
2426   if (Value *V = optimizeFPrintFString(CI, B)) {
2427     return V;
2428   }
2429 
2430   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2431   // floating point arguments.
2432   if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
2433     Module *M = B.GetInsertBlock()->getParent()->getParent();
2434     FunctionCallee FIPrintFFn =
2435         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2436     CallInst *New = cast<CallInst>(CI->clone());
2437     New->setCalledFunction(FIPrintFFn);
2438     B.Insert(New);
2439     return New;
2440   }
2441 
2442   // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2443   // 128-bit floating point arguments.
2444   if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
2445     Module *M = B.GetInsertBlock()->getParent()->getParent();
2446     auto SmallFPrintFFn =
2447         M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
2448                                FT, Callee->getAttributes());
2449     CallInst *New = cast<CallInst>(CI->clone());
2450     New->setCalledFunction(SmallFPrintFFn);
2451     B.Insert(New);
2452     return New;
2453   }
2454 
2455   return nullptr;
2456 }
2457 
2458 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2459   optimizeErrorReporting(CI, B, 3);
2460 
2461   // Get the element size and count.
2462   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2463   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2464   if (SizeC && CountC) {
2465     uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2466 
2467     // If this is writing zero records, remove the call (it's a noop).
2468     if (Bytes == 0)
2469       return ConstantInt::get(CI->getType(), 0);
2470 
2471     // If this is writing one byte, turn it into fputc.
2472     // This optimisation is only valid, if the return value is unused.
2473     if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2474       Value *Char = B.CreateLoad(B.getInt8Ty(),
2475                                  castToCStr(CI->getArgOperand(0), B), "char");
2476       Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2477       return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2478     }
2479   }
2480 
2481   if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2482     return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2483                               CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2484                               TLI);
2485 
2486   return nullptr;
2487 }
2488 
2489 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2490   optimizeErrorReporting(CI, B, 1);
2491 
2492   // Don't rewrite fputs to fwrite when optimising for size because fwrite
2493   // requires more arguments and thus extra MOVs are required.
2494   bool OptForSize = CI->getFunction()->hasOptSize() ||
2495                     llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
2496   if (OptForSize)
2497     return nullptr;
2498 
2499   // Check if has any use
2500   if (!CI->use_empty()) {
2501     if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2502       return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2503                                TLI);
2504     else
2505       // We can't optimize if return value is used.
2506       return nullptr;
2507   }
2508 
2509   // fputs(s,F) --> fwrite(s,strlen(s),1,F)
2510   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2511   if (!Len)
2512     return nullptr;
2513 
2514   // Known to have no uses (see above).
2515   return emitFWrite(
2516       CI->getArgOperand(0),
2517       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2518       CI->getArgOperand(1), B, DL, TLI);
2519 }
2520 
2521 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2522   optimizeErrorReporting(CI, B, 1);
2523 
2524   if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2525     return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2526                              TLI);
2527 
2528   return nullptr;
2529 }
2530 
2531 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2532   if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2533     return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2534 
2535   return nullptr;
2536 }
2537 
2538 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2539   if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2540     return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2541                              CI->getArgOperand(2), B, TLI);
2542 
2543   return nullptr;
2544 }
2545 
2546 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2547   if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2548     return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2549                              CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2550                              TLI);
2551 
2552   return nullptr;
2553 }
2554 
2555 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2556   if (!CI->use_empty())
2557     return nullptr;
2558 
2559   // Check for a constant string.
2560   // puts("") -> putchar('\n')
2561   StringRef Str;
2562   if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2563     return emitPutChar(B.getInt32('\n'), B, TLI);
2564 
2565   return nullptr;
2566 }
2567 
2568 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2569   LibFunc Func;
2570   SmallString<20> FloatFuncName = FuncName;
2571   FloatFuncName += 'f';
2572   if (TLI->getLibFunc(FloatFuncName, Func))
2573     return TLI->has(Func);
2574   return false;
2575 }
2576 
2577 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2578                                                       IRBuilder<> &Builder) {
2579   LibFunc Func;
2580   Function *Callee = CI->getCalledFunction();
2581   // Check for string/memory library functions.
2582   if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2583     // Make sure we never change the calling convention.
2584     assert((ignoreCallingConv(Func) ||
2585             isCallingConvCCompatible(CI)) &&
2586       "Optimizing string/memory libcall would change the calling convention");
2587     switch (Func) {
2588     case LibFunc_strcat:
2589       return optimizeStrCat(CI, Builder);
2590     case LibFunc_strncat:
2591       return optimizeStrNCat(CI, Builder);
2592     case LibFunc_strchr:
2593       return optimizeStrChr(CI, Builder);
2594     case LibFunc_strrchr:
2595       return optimizeStrRChr(CI, Builder);
2596     case LibFunc_strcmp:
2597       return optimizeStrCmp(CI, Builder);
2598     case LibFunc_strncmp:
2599       return optimizeStrNCmp(CI, Builder);
2600     case LibFunc_strcpy:
2601       return optimizeStrCpy(CI, Builder);
2602     case LibFunc_stpcpy:
2603       return optimizeStpCpy(CI, Builder);
2604     case LibFunc_strncpy:
2605       return optimizeStrNCpy(CI, Builder);
2606     case LibFunc_strlen:
2607       return optimizeStrLen(CI, Builder);
2608     case LibFunc_strpbrk:
2609       return optimizeStrPBrk(CI, Builder);
2610     case LibFunc_strtol:
2611     case LibFunc_strtod:
2612     case LibFunc_strtof:
2613     case LibFunc_strtoul:
2614     case LibFunc_strtoll:
2615     case LibFunc_strtold:
2616     case LibFunc_strtoull:
2617       return optimizeStrTo(CI, Builder);
2618     case LibFunc_strspn:
2619       return optimizeStrSpn(CI, Builder);
2620     case LibFunc_strcspn:
2621       return optimizeStrCSpn(CI, Builder);
2622     case LibFunc_strstr:
2623       return optimizeStrStr(CI, Builder);
2624     case LibFunc_memchr:
2625       return optimizeMemChr(CI, Builder);
2626     case LibFunc_bcmp:
2627       return optimizeBCmp(CI, Builder);
2628     case LibFunc_memcmp:
2629       return optimizeMemCmp(CI, Builder);
2630     case LibFunc_memcpy:
2631       return optimizeMemCpy(CI, Builder);
2632     case LibFunc_mempcpy:
2633       return optimizeMemPCpy(CI, Builder);
2634     case LibFunc_memmove:
2635       return optimizeMemMove(CI, Builder);
2636     case LibFunc_memset:
2637       return optimizeMemSet(CI, Builder);
2638     case LibFunc_realloc:
2639       return optimizeRealloc(CI, Builder);
2640     case LibFunc_wcslen:
2641       return optimizeWcslen(CI, Builder);
2642     default:
2643       break;
2644     }
2645   }
2646   return nullptr;
2647 }
2648 
2649 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2650                                                        LibFunc Func,
2651                                                        IRBuilder<> &Builder) {
2652   // Don't optimize calls that require strict floating point semantics.
2653   if (CI->isStrictFP())
2654     return nullptr;
2655 
2656   if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2657     return V;
2658 
2659   switch (Func) {
2660   case LibFunc_sinpif:
2661   case LibFunc_sinpi:
2662   case LibFunc_cospif:
2663   case LibFunc_cospi:
2664     return optimizeSinCosPi(CI, Builder);
2665   case LibFunc_powf:
2666   case LibFunc_pow:
2667   case LibFunc_powl:
2668     return optimizePow(CI, Builder);
2669   case LibFunc_exp2l:
2670   case LibFunc_exp2:
2671   case LibFunc_exp2f:
2672     return optimizeExp2(CI, Builder);
2673   case LibFunc_fabsf:
2674   case LibFunc_fabs:
2675   case LibFunc_fabsl:
2676     return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2677   case LibFunc_sqrtf:
2678   case LibFunc_sqrt:
2679   case LibFunc_sqrtl:
2680     return optimizeSqrt(CI, Builder);
2681   case LibFunc_log:
2682   case LibFunc_log10:
2683   case LibFunc_log1p:
2684   case LibFunc_log2:
2685   case LibFunc_logb:
2686     return optimizeLog(CI, Builder);
2687   case LibFunc_tan:
2688   case LibFunc_tanf:
2689   case LibFunc_tanl:
2690     return optimizeTan(CI, Builder);
2691   case LibFunc_ceil:
2692     return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2693   case LibFunc_floor:
2694     return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2695   case LibFunc_round:
2696     return replaceUnaryCall(CI, Builder, Intrinsic::round);
2697   case LibFunc_nearbyint:
2698     return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2699   case LibFunc_rint:
2700     return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2701   case LibFunc_trunc:
2702     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2703   case LibFunc_acos:
2704   case LibFunc_acosh:
2705   case LibFunc_asin:
2706   case LibFunc_asinh:
2707   case LibFunc_atan:
2708   case LibFunc_atanh:
2709   case LibFunc_cbrt:
2710   case LibFunc_cosh:
2711   case LibFunc_exp:
2712   case LibFunc_exp10:
2713   case LibFunc_expm1:
2714   case LibFunc_cos:
2715   case LibFunc_sin:
2716   case LibFunc_sinh:
2717   case LibFunc_tanh:
2718     if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2719       return optimizeUnaryDoubleFP(CI, Builder, true);
2720     return nullptr;
2721   case LibFunc_copysign:
2722     if (hasFloatVersion(CI->getCalledFunction()->getName()))
2723       return optimizeBinaryDoubleFP(CI, Builder);
2724     return nullptr;
2725   case LibFunc_fminf:
2726   case LibFunc_fmin:
2727   case LibFunc_fminl:
2728   case LibFunc_fmaxf:
2729   case LibFunc_fmax:
2730   case LibFunc_fmaxl:
2731     return optimizeFMinFMax(CI, Builder);
2732   case LibFunc_cabs:
2733   case LibFunc_cabsf:
2734   case LibFunc_cabsl:
2735     return optimizeCAbs(CI, Builder);
2736   default:
2737     return nullptr;
2738   }
2739 }
2740 
2741 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2742   // TODO: Split out the code below that operates on FP calls so that
2743   //       we can all non-FP calls with the StrictFP attribute to be
2744   //       optimized.
2745   if (CI->isNoBuiltin())
2746     return nullptr;
2747 
2748   LibFunc Func;
2749   Function *Callee = CI->getCalledFunction();
2750 
2751   SmallVector<OperandBundleDef, 2> OpBundles;
2752   CI->getOperandBundlesAsDefs(OpBundles);
2753   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2754   bool isCallingConvC = isCallingConvCCompatible(CI);
2755 
2756   // Command-line parameter overrides instruction attribute.
2757   // This can't be moved to optimizeFloatingPointLibCall() because it may be
2758   // used by the intrinsic optimizations.
2759   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2760     UnsafeFPShrink = EnableUnsafeFPShrink;
2761   else if (isa<FPMathOperator>(CI) && CI->isFast())
2762     UnsafeFPShrink = true;
2763 
2764   // First, check for intrinsics.
2765   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2766     if (!isCallingConvC)
2767       return nullptr;
2768     // The FP intrinsics have corresponding constrained versions so we don't
2769     // need to check for the StrictFP attribute here.
2770     switch (II->getIntrinsicID()) {
2771     case Intrinsic::pow:
2772       return optimizePow(CI, Builder);
2773     case Intrinsic::exp2:
2774       return optimizeExp2(CI, Builder);
2775     case Intrinsic::log:
2776       return optimizeLog(CI, Builder);
2777     case Intrinsic::sqrt:
2778       return optimizeSqrt(CI, Builder);
2779     // TODO: Use foldMallocMemset() with memset intrinsic.
2780     case Intrinsic::memset:
2781       return optimizeMemSet(CI, Builder, true);
2782     case Intrinsic::memcpy:
2783       return optimizeMemCpy(CI, Builder, true);
2784     case Intrinsic::memmove:
2785       return optimizeMemMove(CI, Builder, true);
2786     default:
2787       return nullptr;
2788     }
2789   }
2790 
2791   // Also try to simplify calls to fortified library functions.
2792   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2793     // Try to further simplify the result.
2794     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2795     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2796       // Use an IR Builder from SimplifiedCI if available instead of CI
2797       // to guarantee we reach all uses we might replace later on.
2798       IRBuilder<> TmpBuilder(SimplifiedCI);
2799       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2800         // If we were able to further simplify, remove the now redundant call.
2801         substituteInParent(SimplifiedCI, V);
2802         return V;
2803       }
2804     }
2805     return SimplifiedFortifiedCI;
2806   }
2807 
2808   // Then check for known library functions.
2809   if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2810     // We never change the calling convention.
2811     if (!ignoreCallingConv(Func) && !isCallingConvC)
2812       return nullptr;
2813     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2814       return V;
2815     if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2816       return V;
2817     switch (Func) {
2818     case LibFunc_ffs:
2819     case LibFunc_ffsl:
2820     case LibFunc_ffsll:
2821       return optimizeFFS(CI, Builder);
2822     case LibFunc_fls:
2823     case LibFunc_flsl:
2824     case LibFunc_flsll:
2825       return optimizeFls(CI, Builder);
2826     case LibFunc_abs:
2827     case LibFunc_labs:
2828     case LibFunc_llabs:
2829       return optimizeAbs(CI, Builder);
2830     case LibFunc_isdigit:
2831       return optimizeIsDigit(CI, Builder);
2832     case LibFunc_isascii:
2833       return optimizeIsAscii(CI, Builder);
2834     case LibFunc_toascii:
2835       return optimizeToAscii(CI, Builder);
2836     case LibFunc_atoi:
2837     case LibFunc_atol:
2838     case LibFunc_atoll:
2839       return optimizeAtoi(CI, Builder);
2840     case LibFunc_strtol:
2841     case LibFunc_strtoll:
2842       return optimizeStrtol(CI, Builder);
2843     case LibFunc_printf:
2844       return optimizePrintF(CI, Builder);
2845     case LibFunc_sprintf:
2846       return optimizeSPrintF(CI, Builder);
2847     case LibFunc_snprintf:
2848       return optimizeSnPrintF(CI, Builder);
2849     case LibFunc_fprintf:
2850       return optimizeFPrintF(CI, Builder);
2851     case LibFunc_fwrite:
2852       return optimizeFWrite(CI, Builder);
2853     case LibFunc_fread:
2854       return optimizeFRead(CI, Builder);
2855     case LibFunc_fputs:
2856       return optimizeFPuts(CI, Builder);
2857     case LibFunc_fgets:
2858       return optimizeFGets(CI, Builder);
2859     case LibFunc_fputc:
2860       return optimizeFPutc(CI, Builder);
2861     case LibFunc_fgetc:
2862       return optimizeFGetc(CI, Builder);
2863     case LibFunc_puts:
2864       return optimizePuts(CI, Builder);
2865     case LibFunc_perror:
2866       return optimizeErrorReporting(CI, Builder);
2867     case LibFunc_vfprintf:
2868     case LibFunc_fiprintf:
2869       return optimizeErrorReporting(CI, Builder, 0);
2870     default:
2871       return nullptr;
2872     }
2873   }
2874   return nullptr;
2875 }
2876 
2877 LibCallSimplifier::LibCallSimplifier(
2878     const DataLayout &DL, const TargetLibraryInfo *TLI,
2879     OptimizationRemarkEmitter &ORE,
2880     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
2881     function_ref<void(Instruction *, Value *)> Replacer,
2882     function_ref<void(Instruction *)> Eraser)
2883     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
2884       UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
2885 
2886 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2887   // Indirect through the replacer used in this instance.
2888   Replacer(I, With);
2889 }
2890 
2891 void LibCallSimplifier::eraseFromParent(Instruction *I) {
2892   Eraser(I);
2893 }
2894 
2895 // TODO:
2896 //   Additional cases that we need to add to this file:
2897 //
2898 // cbrt:
2899 //   * cbrt(expN(X))  -> expN(x/3)
2900 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2901 //   * cbrt(cbrt(x))  -> pow(x,1/9)
2902 //
2903 // exp, expf, expl:
2904 //   * exp(log(x))  -> x
2905 //
2906 // log, logf, logl:
2907 //   * log(exp(x))   -> x
2908 //   * log(exp(y))   -> y*log(e)
2909 //   * log(exp10(y)) -> y*log(10)
2910 //   * log(sqrt(x))  -> 0.5*log(x)
2911 //
2912 // pow, powf, powl:
2913 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2914 //   * pow(pow(x,y),z)-> pow(x,y*z)
2915 //
2916 // signbit:
2917 //   * signbit(cnst) -> cnst'
2918 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2919 //
2920 // sqrt, sqrtf, sqrtl:
2921 //   * sqrt(expN(x))  -> expN(x*0.5)
2922 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2923 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2924 //
2925 
2926 //===----------------------------------------------------------------------===//
2927 // Fortified Library Call Optimizations
2928 //===----------------------------------------------------------------------===//
2929 
2930 bool
2931 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2932                                                     unsigned ObjSizeOp,
2933                                                     Optional<unsigned> SizeOp,
2934                                                     Optional<unsigned> StrOp,
2935                                                     Optional<unsigned> FlagOp) {
2936   // If this function takes a flag argument, the implementation may use it to
2937   // perform extra checks. Don't fold into the non-checking variant.
2938   if (FlagOp) {
2939     ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
2940     if (!Flag || !Flag->isZero())
2941       return false;
2942   }
2943 
2944   if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
2945     return true;
2946 
2947   if (ConstantInt *ObjSizeCI =
2948           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2949     if (ObjSizeCI->isMinusOne())
2950       return true;
2951     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2952     if (OnlyLowerUnknownSize)
2953       return false;
2954     if (StrOp) {
2955       uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
2956       // If the length is 0 we don't know how long it is and so we can't
2957       // remove the check.
2958       if (Len == 0)
2959         return false;
2960       return ObjSizeCI->getZExtValue() >= Len;
2961     }
2962 
2963     if (SizeOp) {
2964       if (ConstantInt *SizeCI =
2965               dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
2966         return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2967     }
2968   }
2969   return false;
2970 }
2971 
2972 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2973                                                      IRBuilder<> &B) {
2974   if (isFortifiedCallFoldable(CI, 3, 2)) {
2975     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2976                    CI->getArgOperand(2));
2977     return CI->getArgOperand(0);
2978   }
2979   return nullptr;
2980 }
2981 
2982 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2983                                                       IRBuilder<> &B) {
2984   if (isFortifiedCallFoldable(CI, 3, 2)) {
2985     B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2986                     CI->getArgOperand(2));
2987     return CI->getArgOperand(0);
2988   }
2989   return nullptr;
2990 }
2991 
2992 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2993                                                      IRBuilder<> &B) {
2994   // TODO: Try foldMallocMemset() here.
2995 
2996   if (isFortifiedCallFoldable(CI, 3, 2)) {
2997     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2998     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2999     return CI->getArgOperand(0);
3000   }
3001   return nullptr;
3002 }
3003 
3004 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3005                                                       IRBuilder<> &B,
3006                                                       LibFunc Func) {
3007   const DataLayout &DL = CI->getModule()->getDataLayout();
3008   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3009         *ObjSize = CI->getArgOperand(2);
3010 
3011   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
3012   if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
3013     Value *StrLen = emitStrLen(Src, B, DL, TLI);
3014     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
3015   }
3016 
3017   // If a) we don't have any length information, or b) we know this will
3018   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3019   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3020   // TODO: It might be nice to get a maximum length out of the possible
3021   // string lengths for varying.
3022   if (isFortifiedCallFoldable(CI, 2, None, 1)) {
3023     if (Func == LibFunc_strcpy_chk)
3024       return emitStrCpy(Dst, Src, B, TLI);
3025     else
3026       return emitStpCpy(Dst, Src, B, TLI);
3027   }
3028 
3029   if (OnlyLowerUnknownSize)
3030     return nullptr;
3031 
3032   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
3033   uint64_t Len = GetStringLength(Src);
3034   if (Len == 0)
3035     return nullptr;
3036 
3037   Type *SizeTTy = DL.getIntPtrType(CI->getContext());
3038   Value *LenV = ConstantInt::get(SizeTTy, Len);
3039   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
3040   // If the function was an __stpcpy_chk, and we were able to fold it into
3041   // a __memcpy_chk, we still need to return the correct end pointer.
3042   if (Ret && Func == LibFunc_stpcpy_chk)
3043     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
3044   return Ret;
3045 }
3046 
3047 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3048                                                        IRBuilder<> &B,
3049                                                        LibFunc Func) {
3050   if (isFortifiedCallFoldable(CI, 3, 2)) {
3051     if (Func == LibFunc_strncpy_chk)
3052       return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3053                                CI->getArgOperand(2), B, TLI);
3054     else
3055       return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3056                          CI->getArgOperand(2), B, TLI);
3057   }
3058 
3059   return nullptr;
3060 }
3061 
3062 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3063                                                       IRBuilder<> &B) {
3064   if (isFortifiedCallFoldable(CI, 4, 3))
3065     return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3066                        CI->getArgOperand(2), CI->getArgOperand(3), B, TLI);
3067 
3068   return nullptr;
3069 }
3070 
3071 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3072                                                        IRBuilder<> &B) {
3073   if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3074     SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end());
3075     return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3076                         CI->getArgOperand(4), VariadicArgs, B, TLI);
3077   }
3078 
3079   return nullptr;
3080 }
3081 
3082 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3083                                                       IRBuilder<> &B) {
3084   if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3085     SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end());
3086     return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs,
3087                        B, TLI);
3088   }
3089 
3090   return nullptr;
3091 }
3092 
3093 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3094                                                      IRBuilder<> &B) {
3095   if (isFortifiedCallFoldable(CI, 2))
3096     return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI);
3097 
3098   return nullptr;
3099 }
3100 
3101 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3102                                                    IRBuilder<> &B) {
3103   if (isFortifiedCallFoldable(CI, 3))
3104     return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3105                        CI->getArgOperand(2), B, TLI);
3106 
3107   return nullptr;
3108 }
3109 
3110 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3111                                                       IRBuilder<> &B) {
3112   if (isFortifiedCallFoldable(CI, 3))
3113     return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3114                        CI->getArgOperand(2), B, TLI);
3115 
3116   return nullptr;
3117 }
3118 
3119 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3120                                                       IRBuilder<> &B) {
3121   if (isFortifiedCallFoldable(CI, 3))
3122     return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3123                        CI->getArgOperand(2), B, TLI);
3124 
3125   return nullptr;
3126 }
3127 
3128 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3129                                                         IRBuilder<> &B) {
3130   if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3131     return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3132                          CI->getArgOperand(4), CI->getArgOperand(5), B, TLI);
3133 
3134   return nullptr;
3135 }
3136 
3137 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3138                                                        IRBuilder<> &B) {
3139   if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3140     return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3141                         CI->getArgOperand(4), B, TLI);
3142 
3143   return nullptr;
3144 }
3145 
3146 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
3147   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3148   // Some clang users checked for _chk libcall availability using:
3149   //   __has_builtin(__builtin___memcpy_chk)
3150   // When compiling with -fno-builtin, this is always true.
3151   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3152   // end up with fortified libcalls, which isn't acceptable in a freestanding
3153   // environment which only provides their non-fortified counterparts.
3154   //
3155   // Until we change clang and/or teach external users to check for availability
3156   // differently, disregard the "nobuiltin" attribute and TLI::has.
3157   //
3158   // PR23093.
3159 
3160   LibFunc Func;
3161   Function *Callee = CI->getCalledFunction();
3162 
3163   SmallVector<OperandBundleDef, 2> OpBundles;
3164   CI->getOperandBundlesAsDefs(OpBundles);
3165   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
3166   bool isCallingConvC = isCallingConvCCompatible(CI);
3167 
3168   // First, check that this is a known library functions and that the prototype
3169   // is correct.
3170   if (!TLI->getLibFunc(*Callee, Func))
3171     return nullptr;
3172 
3173   // We never change the calling convention.
3174   if (!ignoreCallingConv(Func) && !isCallingConvC)
3175     return nullptr;
3176 
3177   switch (Func) {
3178   case LibFunc_memcpy_chk:
3179     return optimizeMemCpyChk(CI, Builder);
3180   case LibFunc_memmove_chk:
3181     return optimizeMemMoveChk(CI, Builder);
3182   case LibFunc_memset_chk:
3183     return optimizeMemSetChk(CI, Builder);
3184   case LibFunc_stpcpy_chk:
3185   case LibFunc_strcpy_chk:
3186     return optimizeStrpCpyChk(CI, Builder, Func);
3187   case LibFunc_stpncpy_chk:
3188   case LibFunc_strncpy_chk:
3189     return optimizeStrpNCpyChk(CI, Builder, Func);
3190   case LibFunc_memccpy_chk:
3191     return optimizeMemCCpyChk(CI, Builder);
3192   case LibFunc_snprintf_chk:
3193     return optimizeSNPrintfChk(CI, Builder);
3194   case LibFunc_sprintf_chk:
3195     return optimizeSPrintfChk(CI, Builder);
3196   case LibFunc_strcat_chk:
3197     return optimizeStrCatChk(CI, Builder);
3198   case LibFunc_strlcat_chk:
3199     return optimizeStrLCat(CI, Builder);
3200   case LibFunc_strncat_chk:
3201     return optimizeStrNCatChk(CI, Builder);
3202   case LibFunc_strlcpy_chk:
3203     return optimizeStrLCpyChk(CI, Builder);
3204   case LibFunc_vsnprintf_chk:
3205     return optimizeVSNPrintfChk(CI, Builder);
3206   case LibFunc_vsprintf_chk:
3207     return optimizeVSPrintfChk(CI, Builder);
3208   default:
3209     break;
3210   }
3211   return nullptr;
3212 }
3213 
3214 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3215     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
3216     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
3217