1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification.  If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 static cl::opt<bool>
41     ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42                    cl::desc("Treat error-reporting calls as cold"));
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 Func) {
56   return Func == LibFunc::abs || Func == LibFunc::labs ||
57          Func == LibFunc::llabs || Func == LibFunc::strlen;
58 }
59 
60 /// Return true if it only matters that the value is equal or not-equal to zero.
61 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
62   for (User *U : V->users()) {
63     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
64       if (IC->isEquality())
65         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
66           if (C->isNullValue())
67             continue;
68     // Unknown instruction.
69     return false;
70   }
71   return true;
72 }
73 
74 /// Return true if it is only used in equality comparisons with With.
75 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
76   for (User *U : V->users()) {
77     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
78       if (IC->isEquality() && IC->getOperand(1) == With)
79         continue;
80     // Unknown instruction.
81     return false;
82   }
83   return true;
84 }
85 
86 static bool callHasFloatingPointArgument(const CallInst *CI) {
87   return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
88     return OI->getType()->isFloatingPointTy();
89   });
90 }
91 
92 /// \brief Check whether the overloaded unary floating point function
93 /// corresponding to \a Ty is available.
94 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
95                             LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
96                             LibFunc::Func LongDoubleFn) {
97   switch (Ty->getTypeID()) {
98   case Type::FloatTyID:
99     return TLI->has(FloatFn);
100   case Type::DoubleTyID:
101     return TLI->has(DoubleFn);
102   default:
103     return TLI->has(LongDoubleFn);
104   }
105 }
106 
107 /// \brief Returns whether \p F matches the signature expected for the
108 /// string/memory copying library function \p Func.
109 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
110 /// Their fortified (_chk) counterparts are also accepted.
111 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
112   const DataLayout &DL = F->getParent()->getDataLayout();
113   FunctionType *FT = F->getFunctionType();
114   LLVMContext &Context = F->getContext();
115   Type *PCharTy = Type::getInt8PtrTy(Context);
116   Type *SizeTTy = DL.getIntPtrType(Context);
117   unsigned NumParams = FT->getNumParams();
118 
119   // All string libfuncs return the same type as the first parameter.
120   if (FT->getReturnType() != FT->getParamType(0))
121     return false;
122 
123   switch (Func) {
124   default:
125     llvm_unreachable("Can't check signature for non-string-copy libfunc.");
126   case LibFunc::stpncpy_chk:
127   case LibFunc::strncpy_chk:
128     --NumParams; // fallthrough
129   case LibFunc::stpncpy:
130   case LibFunc::strncpy: {
131     if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
132         FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
133       return false;
134     break;
135   }
136   case LibFunc::strcpy_chk:
137   case LibFunc::stpcpy_chk:
138     --NumParams; // fallthrough
139   case LibFunc::stpcpy:
140   case LibFunc::strcpy: {
141     if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
142         FT->getParamType(0) != PCharTy)
143       return false;
144     break;
145   }
146   case LibFunc::memmove_chk:
147   case LibFunc::memcpy_chk:
148     --NumParams; // fallthrough
149   case LibFunc::memmove:
150   case LibFunc::memcpy: {
151     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
152         !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
153       return false;
154     break;
155   }
156   case LibFunc::memset_chk:
157     --NumParams; // fallthrough
158   case LibFunc::memset: {
159     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
160         !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
161       return false;
162     break;
163   }
164   }
165   // If this is a fortified libcall, the last parameter is a size_t.
166   if (NumParams == FT->getNumParams() - 1)
167     return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
168   return true;
169 }
170 
171 //===----------------------------------------------------------------------===//
172 // String and Memory Library Call Optimizations
173 //===----------------------------------------------------------------------===//
174 
175 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
176   Function *Callee = CI->getCalledFunction();
177   // Verify the "strcat" function prototype.
178   FunctionType *FT = Callee->getFunctionType();
179   if (FT->getNumParams() != 2||
180       FT->getReturnType() != B.getInt8PtrTy() ||
181       FT->getParamType(0) != FT->getReturnType() ||
182       FT->getParamType(1) != FT->getReturnType())
183     return nullptr;
184 
185   // Extract some information from the instruction
186   Value *Dst = CI->getArgOperand(0);
187   Value *Src = CI->getArgOperand(1);
188 
189   // See if we can get the length of the input string.
190   uint64_t Len = GetStringLength(Src);
191   if (Len == 0)
192     return nullptr;
193   --Len; // Unbias length.
194 
195   // Handle the simple, do-nothing case: strcat(x, "") -> x
196   if (Len == 0)
197     return Dst;
198 
199   return emitStrLenMemCpy(Src, Dst, Len, B);
200 }
201 
202 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
203                                            IRBuilder<> &B) {
204   // We need to find the end of the destination string.  That's where the
205   // memory is to be moved to. We just generate a call to strlen.
206   Value *DstLen = emitStrLen(Dst, B, DL, TLI);
207   if (!DstLen)
208     return nullptr;
209 
210   // Now that we have the destination's length, we must index into the
211   // destination's pointer to get the actual memcpy destination (end of
212   // the string .. we're concatenating).
213   Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
214 
215   // We have enough information to now generate the memcpy call to do the
216   // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
217   B.CreateMemCpy(CpyDst, Src,
218                  ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
219                  1);
220   return Dst;
221 }
222 
223 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
224   Function *Callee = CI->getCalledFunction();
225   // Verify the "strncat" function prototype.
226   FunctionType *FT = Callee->getFunctionType();
227   if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
228       FT->getParamType(0) != FT->getReturnType() ||
229       FT->getParamType(1) != FT->getReturnType() ||
230       !FT->getParamType(2)->isIntegerTy())
231     return nullptr;
232 
233   // Extract some information from the instruction.
234   Value *Dst = CI->getArgOperand(0);
235   Value *Src = CI->getArgOperand(1);
236   uint64_t Len;
237 
238   // We don't do anything if length is not constant.
239   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
240     Len = LengthArg->getZExtValue();
241   else
242     return nullptr;
243 
244   // See if we can get the length of the input string.
245   uint64_t SrcLen = GetStringLength(Src);
246   if (SrcLen == 0)
247     return nullptr;
248   --SrcLen; // Unbias length.
249 
250   // Handle the simple, do-nothing cases:
251   // strncat(x, "", c) -> x
252   // strncat(x,  c, 0) -> x
253   if (SrcLen == 0 || Len == 0)
254     return Dst;
255 
256   // We don't optimize this case.
257   if (Len < SrcLen)
258     return nullptr;
259 
260   // strncat(x, s, c) -> strcat(x, s)
261   // s is constant so the strcat can be optimized further.
262   return emitStrLenMemCpy(Src, Dst, SrcLen, B);
263 }
264 
265 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
266   Function *Callee = CI->getCalledFunction();
267   // Verify the "strchr" function prototype.
268   FunctionType *FT = Callee->getFunctionType();
269   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
270       FT->getParamType(0) != FT->getReturnType() ||
271       !FT->getParamType(1)->isIntegerTy(32))
272     return nullptr;
273 
274   Value *SrcStr = CI->getArgOperand(0);
275 
276   // If the second operand is non-constant, see if we can compute the length
277   // of the input string and turn this into memchr.
278   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
279   if (!CharC) {
280     uint64_t Len = GetStringLength(SrcStr);
281     if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
282       return nullptr;
283 
284     return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
285                       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
286                       B, DL, TLI);
287   }
288 
289   // Otherwise, the character is a constant, see if the first argument is
290   // a string literal.  If so, we can constant fold.
291   StringRef Str;
292   if (!getConstantStringInfo(SrcStr, Str)) {
293     if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
294       return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
295                          "strchr");
296     return nullptr;
297   }
298 
299   // Compute the offset, make sure to handle the case when we're searching for
300   // zero (a weird way to spell strlen).
301   size_t I = (0xFF & CharC->getSExtValue()) == 0
302                  ? Str.size()
303                  : Str.find(CharC->getSExtValue());
304   if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
305     return Constant::getNullValue(CI->getType());
306 
307   // strchr(s+n,c)  -> gep(s+n+i,c)
308   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
309 }
310 
311 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
312   Function *Callee = CI->getCalledFunction();
313   // Verify the "strrchr" function prototype.
314   FunctionType *FT = Callee->getFunctionType();
315   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
316       FT->getParamType(0) != FT->getReturnType() ||
317       !FT->getParamType(1)->isIntegerTy(32))
318     return nullptr;
319 
320   Value *SrcStr = CI->getArgOperand(0);
321   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
322 
323   // Cannot fold anything if we're not looking for a constant.
324   if (!CharC)
325     return nullptr;
326 
327   StringRef Str;
328   if (!getConstantStringInfo(SrcStr, Str)) {
329     // strrchr(s, 0) -> strchr(s, 0)
330     if (CharC->isZero())
331       return emitStrChr(SrcStr, '\0', B, TLI);
332     return nullptr;
333   }
334 
335   // Compute the offset.
336   size_t I = (0xFF & CharC->getSExtValue()) == 0
337                  ? Str.size()
338                  : Str.rfind(CharC->getSExtValue());
339   if (I == StringRef::npos) // Didn't find the char. Return null.
340     return Constant::getNullValue(CI->getType());
341 
342   // strrchr(s+n,c) -> gep(s+n+i,c)
343   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
344 }
345 
346 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
347   Function *Callee = CI->getCalledFunction();
348   // Verify the "strcmp" function prototype.
349   FunctionType *FT = Callee->getFunctionType();
350   if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
351       FT->getParamType(0) != FT->getParamType(1) ||
352       FT->getParamType(0) != B.getInt8PtrTy())
353     return nullptr;
354 
355   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
356   if (Str1P == Str2P) // strcmp(x,x)  -> 0
357     return ConstantInt::get(CI->getType(), 0);
358 
359   StringRef Str1, Str2;
360   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
361   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
362 
363   // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
364   if (HasStr1 && HasStr2)
365     return ConstantInt::get(CI->getType(), Str1.compare(Str2));
366 
367   if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
368     return B.CreateNeg(
369         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
370 
371   if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
372     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
373 
374   // strcmp(P, "x") -> memcmp(P, "x", 2)
375   uint64_t Len1 = GetStringLength(Str1P);
376   uint64_t Len2 = GetStringLength(Str2P);
377   if (Len1 && Len2) {
378     return emitMemCmp(Str1P, Str2P,
379                       ConstantInt::get(DL.getIntPtrType(CI->getContext()),
380                                        std::min(Len1, Len2)),
381                       B, DL, TLI);
382   }
383 
384   return nullptr;
385 }
386 
387 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
388   Function *Callee = CI->getCalledFunction();
389   // Verify the "strncmp" function prototype.
390   FunctionType *FT = Callee->getFunctionType();
391   if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
392       FT->getParamType(0) != FT->getParamType(1) ||
393       FT->getParamType(0) != B.getInt8PtrTy() ||
394       !FT->getParamType(2)->isIntegerTy())
395     return nullptr;
396 
397   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
398   if (Str1P == Str2P) // strncmp(x,x,n)  -> 0
399     return ConstantInt::get(CI->getType(), 0);
400 
401   // Get the length argument if it is constant.
402   uint64_t Length;
403   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
404     Length = LengthArg->getZExtValue();
405   else
406     return nullptr;
407 
408   if (Length == 0) // strncmp(x,y,0)   -> 0
409     return ConstantInt::get(CI->getType(), 0);
410 
411   if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
412     return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
413 
414   StringRef Str1, Str2;
415   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
416   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
417 
418   // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
419   if (HasStr1 && HasStr2) {
420     StringRef SubStr1 = Str1.substr(0, Length);
421     StringRef SubStr2 = Str2.substr(0, Length);
422     return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
423   }
424 
425   if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
426     return B.CreateNeg(
427         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
428 
429   if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
430     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
431 
432   return nullptr;
433 }
434 
435 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
436   Function *Callee = CI->getCalledFunction();
437 
438   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
439     return nullptr;
440 
441   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442   if (Dst == Src) // strcpy(x,x)  -> x
443     return Src;
444 
445   // See if we can get the length of the input string.
446   uint64_t Len = GetStringLength(Src);
447   if (Len == 0)
448     return nullptr;
449 
450   // We have enough information to now generate the memcpy call to do the
451   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
452   B.CreateMemCpy(Dst, Src,
453                  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
454   return Dst;
455 }
456 
457 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
458   Function *Callee = CI->getCalledFunction();
459   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
460     return nullptr;
461 
462   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463   if (Dst == Src) { // stpcpy(x,x)  -> x+strlen(x)
464     Value *StrLen = emitStrLen(Src, B, DL, TLI);
465     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
466   }
467 
468   // See if we can get the length of the input string.
469   uint64_t Len = GetStringLength(Src);
470   if (Len == 0)
471     return nullptr;
472 
473   Type *PT = Callee->getFunctionType()->getParamType(0);
474   Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
475   Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
476                               ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
477 
478   // We have enough information to now generate the memcpy call to do the
479   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
480   B.CreateMemCpy(Dst, Src, LenV, 1);
481   return DstEnd;
482 }
483 
484 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
485   Function *Callee = CI->getCalledFunction();
486   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
487     return nullptr;
488 
489   Value *Dst = CI->getArgOperand(0);
490   Value *Src = CI->getArgOperand(1);
491   Value *LenOp = CI->getArgOperand(2);
492 
493   // See if we can get the length of the input string.
494   uint64_t SrcLen = GetStringLength(Src);
495   if (SrcLen == 0)
496     return nullptr;
497   --SrcLen;
498 
499   if (SrcLen == 0) {
500     // strncpy(x, "", y) -> memset(x, '\0', y, 1)
501     B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
502     return Dst;
503   }
504 
505   uint64_t Len;
506   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
507     Len = LengthArg->getZExtValue();
508   else
509     return nullptr;
510 
511   if (Len == 0)
512     return Dst; // strncpy(x, y, 0) -> x
513 
514   // Let strncpy handle the zero padding
515   if (Len > SrcLen + 1)
516     return nullptr;
517 
518   Type *PT = Callee->getFunctionType()->getParamType(0);
519   // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
520   B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
521 
522   return Dst;
523 }
524 
525 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
526   Function *Callee = CI->getCalledFunction();
527   FunctionType *FT = Callee->getFunctionType();
528   if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
529       !FT->getReturnType()->isIntegerTy())
530     return nullptr;
531 
532   Value *Src = CI->getArgOperand(0);
533 
534   // Constant folding: strlen("xyz") -> 3
535   if (uint64_t Len = GetStringLength(Src))
536     return ConstantInt::get(CI->getType(), Len - 1);
537 
538   // If s is a constant pointer pointing to a string literal, we can fold
539   // strlen(s + x) to strlen(s) - x, when x is known to be in the range
540   // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
541   // We only try to simplify strlen when the pointer s points to an array
542   // of i8. Otherwise, we would need to scale the offset x before doing the
543   // subtraction. This will make the optimization more complex, and it's not
544   // very useful because calling strlen for a pointer of other types is
545   // very uncommon.
546   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
547     if (!isGEPBasedOnPointerToString(GEP))
548       return nullptr;
549 
550     StringRef Str;
551     if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
552       size_t NullTermIdx = Str.find('\0');
553 
554       // If the string does not have '\0', leave it to strlen to compute
555       // its length.
556       if (NullTermIdx == StringRef::npos)
557         return nullptr;
558 
559       Value *Offset = GEP->getOperand(2);
560       unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
561       APInt KnownZero(BitWidth, 0);
562       APInt KnownOne(BitWidth, 0);
563       computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
564                        nullptr);
565       KnownZero.flipAllBits();
566       size_t ArrSize =
567              cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
568 
569       // KnownZero's bits are flipped, so zeros in KnownZero now represent
570       // bits known to be zeros in Offset, and ones in KnowZero represent
571       // bits unknown in Offset. Therefore, Offset is known to be in range
572       // [0, NullTermIdx] when the flipped KnownZero is non-negative and
573       // unsigned-less-than NullTermIdx.
574       //
575       // If Offset is not provably in the range [0, NullTermIdx], we can still
576       // optimize if we can prove that the program has undefined behavior when
577       // Offset is outside that range. That is the case when GEP->getOperand(0)
578       // is a pointer to an object whose memory extent is NullTermIdx+1.
579       if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
580           (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
581            NullTermIdx == ArrSize - 1))
582         return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
583                            Offset);
584     }
585 
586     return nullptr;
587   }
588 
589   // strlen(x?"foo":"bars") --> x ? 3 : 4
590   if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
591     uint64_t LenTrue = GetStringLength(SI->getTrueValue());
592     uint64_t LenFalse = GetStringLength(SI->getFalseValue());
593     if (LenTrue && LenFalse) {
594       Function *Caller = CI->getParent()->getParent();
595       emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
596                              SI->getDebugLoc(),
597                              "folded strlen(select) to select of constants");
598       return B.CreateSelect(SI->getCondition(),
599                             ConstantInt::get(CI->getType(), LenTrue - 1),
600                             ConstantInt::get(CI->getType(), LenFalse - 1));
601     }
602   }
603 
604   // strlen(x) != 0 --> *x != 0
605   // strlen(x) == 0 --> *x == 0
606   if (isOnlyUsedInZeroEqualityComparison(CI))
607     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
608 
609   return nullptr;
610 }
611 
612 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
613   Function *Callee = CI->getCalledFunction();
614   FunctionType *FT = Callee->getFunctionType();
615   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
616       FT->getParamType(1) != FT->getParamType(0) ||
617       FT->getReturnType() != FT->getParamType(0))
618     return nullptr;
619 
620   StringRef S1, S2;
621   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
622   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
623 
624   // strpbrk(s, "") -> nullptr
625   // strpbrk("", s) -> nullptr
626   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
627     return Constant::getNullValue(CI->getType());
628 
629   // Constant folding.
630   if (HasS1 && HasS2) {
631     size_t I = S1.find_first_of(S2);
632     if (I == StringRef::npos) // No match.
633       return Constant::getNullValue(CI->getType());
634 
635     return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
636                        "strpbrk");
637   }
638 
639   // strpbrk(s, "a") -> strchr(s, 'a')
640   if (HasS2 && S2.size() == 1)
641     return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
642 
643   return nullptr;
644 }
645 
646 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
647   Function *Callee = CI->getCalledFunction();
648   FunctionType *FT = Callee->getFunctionType();
649   if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
650       !FT->getParamType(0)->isPointerTy() ||
651       !FT->getParamType(1)->isPointerTy())
652     return nullptr;
653 
654   Value *EndPtr = CI->getArgOperand(1);
655   if (isa<ConstantPointerNull>(EndPtr)) {
656     // With a null EndPtr, this function won't capture the main argument.
657     // It would be readonly too, except that it still may write to errno.
658     CI->addAttribute(1, Attribute::NoCapture);
659   }
660 
661   return nullptr;
662 }
663 
664 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
665   Function *Callee = CI->getCalledFunction();
666   FunctionType *FT = Callee->getFunctionType();
667   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
668       FT->getParamType(1) != FT->getParamType(0) ||
669       !FT->getReturnType()->isIntegerTy())
670     return nullptr;
671 
672   StringRef S1, S2;
673   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
674   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
675 
676   // strspn(s, "") -> 0
677   // strspn("", s) -> 0
678   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
679     return Constant::getNullValue(CI->getType());
680 
681   // Constant folding.
682   if (HasS1 && HasS2) {
683     size_t Pos = S1.find_first_not_of(S2);
684     if (Pos == StringRef::npos)
685       Pos = S1.size();
686     return ConstantInt::get(CI->getType(), Pos);
687   }
688 
689   return nullptr;
690 }
691 
692 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
693   Function *Callee = CI->getCalledFunction();
694   FunctionType *FT = Callee->getFunctionType();
695   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
696       FT->getParamType(1) != FT->getParamType(0) ||
697       !FT->getReturnType()->isIntegerTy())
698     return nullptr;
699 
700   StringRef S1, S2;
701   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
702   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
703 
704   // strcspn("", s) -> 0
705   if (HasS1 && S1.empty())
706     return Constant::getNullValue(CI->getType());
707 
708   // Constant folding.
709   if (HasS1 && HasS2) {
710     size_t Pos = S1.find_first_of(S2);
711     if (Pos == StringRef::npos)
712       Pos = S1.size();
713     return ConstantInt::get(CI->getType(), Pos);
714   }
715 
716   // strcspn(s, "") -> strlen(s)
717   if (HasS2 && S2.empty())
718     return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
719 
720   return nullptr;
721 }
722 
723 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
724   Function *Callee = CI->getCalledFunction();
725   FunctionType *FT = Callee->getFunctionType();
726   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
727       !FT->getParamType(1)->isPointerTy() ||
728       !FT->getReturnType()->isPointerTy())
729     return nullptr;
730 
731   // fold strstr(x, x) -> x.
732   if (CI->getArgOperand(0) == CI->getArgOperand(1))
733     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
734 
735   // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
736   if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
737     Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
738     if (!StrLen)
739       return nullptr;
740     Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
741                                  StrLen, B, DL, TLI);
742     if (!StrNCmp)
743       return nullptr;
744     for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
745       ICmpInst *Old = cast<ICmpInst>(*UI++);
746       Value *Cmp =
747           B.CreateICmp(Old->getPredicate(), StrNCmp,
748                        ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
749       replaceAllUsesWith(Old, Cmp);
750     }
751     return CI;
752   }
753 
754   // See if either input string is a constant string.
755   StringRef SearchStr, ToFindStr;
756   bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
757   bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
758 
759   // fold strstr(x, "") -> x.
760   if (HasStr2 && ToFindStr.empty())
761     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
762 
763   // If both strings are known, constant fold it.
764   if (HasStr1 && HasStr2) {
765     size_t Offset = SearchStr.find(ToFindStr);
766 
767     if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
768       return Constant::getNullValue(CI->getType());
769 
770     // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
771     Value *Result = castToCStr(CI->getArgOperand(0), B);
772     Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
773     return B.CreateBitCast(Result, CI->getType());
774   }
775 
776   // fold strstr(x, "y") -> strchr(x, 'y').
777   if (HasStr2 && ToFindStr.size() == 1) {
778     Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
779     return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
780   }
781   return nullptr;
782 }
783 
784 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
785   Function *Callee = CI->getCalledFunction();
786   FunctionType *FT = Callee->getFunctionType();
787   if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
788       !FT->getParamType(1)->isIntegerTy(32) ||
789       !FT->getParamType(2)->isIntegerTy() ||
790       !FT->getReturnType()->isPointerTy())
791     return nullptr;
792 
793   Value *SrcStr = CI->getArgOperand(0);
794   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
795   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
796 
797   // memchr(x, y, 0) -> null
798   if (LenC && LenC->isNullValue())
799     return Constant::getNullValue(CI->getType());
800 
801   // From now on we need at least constant length and string.
802   StringRef Str;
803   if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
804     return nullptr;
805 
806   // Truncate the string to LenC. If Str is smaller than LenC we will still only
807   // scan the string, as reading past the end of it is undefined and we can just
808   // return null if we don't find the char.
809   Str = Str.substr(0, LenC->getZExtValue());
810 
811   // If the char is variable but the input str and length are not we can turn
812   // this memchr call into a simple bit field test. Of course this only works
813   // when the return value is only checked against null.
814   //
815   // It would be really nice to reuse switch lowering here but we can't change
816   // the CFG at this point.
817   //
818   // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
819   //   after bounds check.
820   if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
821     unsigned char Max =
822         *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
823                           reinterpret_cast<const unsigned char *>(Str.end()));
824 
825     // Make sure the bit field we're about to create fits in a register on the
826     // target.
827     // FIXME: On a 64 bit architecture this prevents us from using the
828     // interesting range of alpha ascii chars. We could do better by emitting
829     // two bitfields or shifting the range by 64 if no lower chars are used.
830     if (!DL.fitsInLegalInteger(Max + 1))
831       return nullptr;
832 
833     // For the bit field use a power-of-2 type with at least 8 bits to avoid
834     // creating unnecessary illegal types.
835     unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
836 
837     // Now build the bit field.
838     APInt Bitfield(Width, 0);
839     for (char C : Str)
840       Bitfield.setBit((unsigned char)C);
841     Value *BitfieldC = B.getInt(Bitfield);
842 
843     // First check that the bit field access is within bounds.
844     Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
845     Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
846                                  "memchr.bounds");
847 
848     // Create code that checks if the given bit is set in the field.
849     Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
850     Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
851 
852     // Finally merge both checks and cast to pointer type. The inttoptr
853     // implicitly zexts the i1 to intptr type.
854     return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
855   }
856 
857   // Check if all arguments are constants.  If so, we can constant fold.
858   if (!CharC)
859     return nullptr;
860 
861   // Compute the offset.
862   size_t I = Str.find(CharC->getSExtValue() & 0xFF);
863   if (I == StringRef::npos) // Didn't find the char.  memchr returns null.
864     return Constant::getNullValue(CI->getType());
865 
866   // memchr(s+n,c,l) -> gep(s+n+i,c)
867   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
868 }
869 
870 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
871   Function *Callee = CI->getCalledFunction();
872   FunctionType *FT = Callee->getFunctionType();
873   if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
874       !FT->getParamType(1)->isPointerTy() ||
875       !FT->getReturnType()->isIntegerTy(32))
876     return nullptr;
877 
878   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
879 
880   if (LHS == RHS) // memcmp(s,s,x) -> 0
881     return Constant::getNullValue(CI->getType());
882 
883   // Make sure we have a constant length.
884   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
885   if (!LenC)
886     return nullptr;
887   uint64_t Len = LenC->getZExtValue();
888 
889   if (Len == 0) // memcmp(s1,s2,0) -> 0
890     return Constant::getNullValue(CI->getType());
891 
892   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
893   if (Len == 1) {
894     Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
895                                CI->getType(), "lhsv");
896     Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
897                                CI->getType(), "rhsv");
898     return B.CreateSub(LHSV, RHSV, "chardiff");
899   }
900 
901   // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
902   if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
903 
904     IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
905     unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
906 
907     if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
908         getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
909 
910       Type *LHSPtrTy =
911           IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
912       Type *RHSPtrTy =
913           IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
914 
915       Value *LHSV =
916           B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
917       Value *RHSV =
918           B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
919 
920       return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
921     }
922   }
923 
924   // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
925   StringRef LHSStr, RHSStr;
926   if (getConstantStringInfo(LHS, LHSStr) &&
927       getConstantStringInfo(RHS, RHSStr)) {
928     // Make sure we're not reading out-of-bounds memory.
929     if (Len > LHSStr.size() || Len > RHSStr.size())
930       return nullptr;
931     // Fold the memcmp and normalize the result.  This way we get consistent
932     // results across multiple platforms.
933     uint64_t Ret = 0;
934     int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
935     if (Cmp < 0)
936       Ret = -1;
937     else if (Cmp > 0)
938       Ret = 1;
939     return ConstantInt::get(CI->getType(), Ret);
940   }
941 
942   return nullptr;
943 }
944 
945 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
946   Function *Callee = CI->getCalledFunction();
947 
948   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
949     return nullptr;
950 
951   // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
952   B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
953                  CI->getArgOperand(2), 1);
954   return CI->getArgOperand(0);
955 }
956 
957 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
958   Function *Callee = CI->getCalledFunction();
959 
960   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
961     return nullptr;
962 
963   // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
964   B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
965                   CI->getArgOperand(2), 1);
966   return CI->getArgOperand(0);
967 }
968 
969 // TODO: Does this belong in BuildLibCalls or should all of those similar
970 // functions be moved here?
971 static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
972                          IRBuilder<> &B, const TargetLibraryInfo &TLI) {
973   LibFunc::Func Func;
974   if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
975     return nullptr;
976 
977   Module *M = B.GetInsertBlock()->getModule();
978   const DataLayout &DL = M->getDataLayout();
979   IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
980   Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
981                                          PtrType, PtrType, nullptr);
982   CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
983 
984   if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
985     CI->setCallingConv(F->getCallingConv());
986 
987   return CI;
988 }
989 
990 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
991 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
992                                const TargetLibraryInfo &TLI) {
993   // This has to be a memset of zeros (bzero).
994   auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
995   if (!FillValue || FillValue->getZExtValue() != 0)
996     return nullptr;
997 
998   // TODO: We should handle the case where the malloc has more than one use.
999   // This is necessary to optimize common patterns such as when the result of
1000   // the malloc is checked against null or when a memset intrinsic is used in
1001   // place of a memset library call.
1002   auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1003   if (!Malloc || !Malloc->hasOneUse())
1004     return nullptr;
1005 
1006   // Is the inner call really malloc()?
1007   Function *InnerCallee = Malloc->getCalledFunction();
1008   LibFunc::Func Func;
1009   if (!TLI.getLibFunc(InnerCallee->getName(), Func) || !TLI.has(Func) ||
1010       Func != LibFunc::malloc)
1011     return nullptr;
1012 
1013   // Matching the name is not good enough. Make sure the parameter and return
1014   // type match the standard library signature.
1015   FunctionType *FT = InnerCallee->getFunctionType();
1016   if (FT->getNumParams() != 1 || !FT->getParamType(0)->isIntegerTy())
1017     return nullptr;
1018 
1019   auto *RetType = dyn_cast<PointerType>(FT->getReturnType());
1020   if (!RetType || !RetType->getPointerElementType()->isIntegerTy(8))
1021     return nullptr;
1022 
1023   // The memset must cover the same number of bytes that are malloc'd.
1024   if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1025     return nullptr;
1026 
1027   // Replace the malloc with a calloc. We need the data layout to know what the
1028   // actual size of a 'size_t' parameter is.
1029   B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1030   const DataLayout &DL = Malloc->getModule()->getDataLayout();
1031   IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
1032   Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1033                              Malloc->getArgOperand(0), Malloc->getAttributes(),
1034                              B, TLI);
1035   if (!Calloc)
1036     return nullptr;
1037 
1038   Malloc->replaceAllUsesWith(Calloc);
1039   Malloc->eraseFromParent();
1040 
1041   return Calloc;
1042 }
1043 
1044 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1045   Function *Callee = CI->getCalledFunction();
1046 
1047   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
1048     return nullptr;
1049 
1050   if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
1051     return Calloc;
1052 
1053   // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1054   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1055   B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1056   return CI->getArgOperand(0);
1057 }
1058 
1059 //===----------------------------------------------------------------------===//
1060 // Math Library Optimizations
1061 //===----------------------------------------------------------------------===//
1062 
1063 /// Return a variant of Val with float type.
1064 /// Currently this works in two cases: If Val is an FPExtension of a float
1065 /// value to something bigger, simply return the operand.
1066 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1067 /// loss of precision do so.
1068 static Value *valueHasFloatPrecision(Value *Val) {
1069   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1070     Value *Op = Cast->getOperand(0);
1071     if (Op->getType()->isFloatTy())
1072       return Op;
1073   }
1074   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1075     APFloat F = Const->getValueAPF();
1076     bool losesInfo;
1077     (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1078                     &losesInfo);
1079     if (!losesInfo)
1080       return ConstantFP::get(Const->getContext(), F);
1081   }
1082   return nullptr;
1083 }
1084 
1085 /// Any floating-point library function that we're trying to simplify will have
1086 /// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
1087 /// CheckDoubleTy indicates that 'fptype' must be 'double'.
1088 static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
1089                                           bool CheckDoubleTy) {
1090   FunctionType *FT = F->getFunctionType();
1091   if (FT->getNumParams() != NumParams)
1092     return false;
1093 
1094   // The return type must match what we're looking for.
1095   Type *RetTy = FT->getReturnType();
1096   if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
1097     return false;
1098 
1099   // Each parameter must match the return type, and therefore, match every other
1100   // parameter too.
1101   for (const Type *ParamTy : FT->params())
1102     if (ParamTy != RetTy)
1103       return false;
1104 
1105   return true;
1106 }
1107 
1108 /// Shrink double -> float for unary functions like 'floor'.
1109 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1110                                     bool CheckRetType) {
1111   Function *Callee = CI->getCalledFunction();
1112   if (!matchesFPLibFunctionSignature(Callee, 1, true))
1113     return nullptr;
1114 
1115   if (CheckRetType) {
1116     // Check if all the uses for function like 'sin' are converted to float.
1117     for (User *U : CI->users()) {
1118       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1119       if (!Cast || !Cast->getType()->isFloatTy())
1120         return nullptr;
1121     }
1122   }
1123 
1124   // If this is something like 'floor((double)floatval)', convert to floorf.
1125   Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1126   if (V == nullptr)
1127     return nullptr;
1128 
1129   // Propagate fast-math flags from the existing call to the new call.
1130   IRBuilder<>::FastMathFlagGuard Guard(B);
1131   B.setFastMathFlags(CI->getFastMathFlags());
1132 
1133   // floor((double)floatval) -> (double)floorf(floatval)
1134   if (Callee->isIntrinsic()) {
1135     Module *M = CI->getModule();
1136     Intrinsic::ID IID = Callee->getIntrinsicID();
1137     Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1138     V = B.CreateCall(F, V);
1139   } else {
1140     // The call is a library call rather than an intrinsic.
1141     V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1142   }
1143 
1144   return B.CreateFPExt(V, B.getDoubleTy());
1145 }
1146 
1147 /// Shrink double -> float for binary functions like 'fmin/fmax'.
1148 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1149   Function *Callee = CI->getCalledFunction();
1150   if (!matchesFPLibFunctionSignature(Callee, 2, true))
1151     return nullptr;
1152 
1153   // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1154   // or fmin(1.0, (double)floatval), then we convert it to fminf.
1155   Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1156   if (V1 == nullptr)
1157     return nullptr;
1158   Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1159   if (V2 == nullptr)
1160     return nullptr;
1161 
1162   // Propagate fast-math flags from the existing call to the new call.
1163   IRBuilder<>::FastMathFlagGuard Guard(B);
1164   B.setFastMathFlags(CI->getFastMathFlags());
1165 
1166   // fmin((double)floatval1, (double)floatval2)
1167   //                      -> (double)fminf(floatval1, floatval2)
1168   // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1169   Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1170                                    Callee->getAttributes());
1171   return B.CreateFPExt(V, B.getDoubleTy());
1172 }
1173 
1174 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1175   Function *Callee = CI->getCalledFunction();
1176   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1177     return nullptr;
1178 
1179   Value *Ret = nullptr;
1180   StringRef Name = Callee->getName();
1181   if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1182     Ret = optimizeUnaryDoubleFP(CI, B, true);
1183 
1184   // cos(-x) -> cos(x)
1185   Value *Op1 = CI->getArgOperand(0);
1186   if (BinaryOperator::isFNeg(Op1)) {
1187     BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1188     return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1189   }
1190   return Ret;
1191 }
1192 
1193 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1194   // Multiplications calculated using Addition Chains.
1195   // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1196 
1197   assert(Exp != 0 && "Incorrect exponent 0 not handled");
1198 
1199   if (InnerChain[Exp])
1200     return InnerChain[Exp];
1201 
1202   static const unsigned AddChain[33][2] = {
1203       {0, 0}, // Unused.
1204       {0, 0}, // Unused (base case = pow1).
1205       {1, 1}, // Unused (pre-computed).
1206       {1, 2},  {2, 2},   {2, 3},  {3, 3},   {2, 5},  {4, 4},
1207       {1, 8},  {5, 5},   {1, 10}, {6, 6},   {4, 9},  {7, 7},
1208       {3, 12}, {8, 8},   {8, 9},  {2, 16},  {1, 18}, {10, 10},
1209       {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1210       {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1211   };
1212 
1213   InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1214                                  getPow(InnerChain, AddChain[Exp][1], B));
1215   return InnerChain[Exp];
1216 }
1217 
1218 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1219   Function *Callee = CI->getCalledFunction();
1220   if (!matchesFPLibFunctionSignature(Callee, 2, false))
1221     return nullptr;
1222 
1223   Value *Ret = nullptr;
1224   StringRef Name = Callee->getName();
1225   if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1226     Ret = optimizeUnaryDoubleFP(CI, B, true);
1227 
1228   Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1229   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1230     // pow(1.0, x) -> 1.0
1231     if (Op1C->isExactlyValue(1.0))
1232       return Op1C;
1233     // pow(2.0, x) -> exp2(x)
1234     if (Op1C->isExactlyValue(2.0) &&
1235         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1236                         LibFunc::exp2l))
1237       return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1238                                   Callee->getAttributes());
1239     // pow(10.0, x) -> exp10(x)
1240     if (Op1C->isExactlyValue(10.0) &&
1241         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1242                         LibFunc::exp10l))
1243       return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1244                                   Callee->getAttributes());
1245   }
1246 
1247   // pow(exp(x), y) -> exp(x * y)
1248   // pow(exp2(x), y) -> exp2(x * y)
1249   // We enable these only with fast-math. Besides rounding differences, the
1250   // transformation changes overflow and underflow behavior quite dramatically.
1251   // Example: x = 1000, y = 0.001.
1252   // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1253   auto *OpC = dyn_cast<CallInst>(Op1);
1254   if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1255     LibFunc::Func Func;
1256     Function *OpCCallee = OpC->getCalledFunction();
1257     if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1258         TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
1259       IRBuilder<>::FastMathFlagGuard Guard(B);
1260       B.setFastMathFlags(CI->getFastMathFlags());
1261       Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1262       return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1263                                   OpCCallee->getAttributes());
1264     }
1265   }
1266 
1267   ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1268   if (!Op2C)
1269     return Ret;
1270 
1271   if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1272     return ConstantFP::get(CI->getType(), 1.0);
1273 
1274   if (Op2C->isExactlyValue(0.5) &&
1275       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1276                       LibFunc::sqrtl) &&
1277       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1278                       LibFunc::fabsl)) {
1279 
1280     // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1281     if (CI->hasUnsafeAlgebra()) {
1282       IRBuilder<>::FastMathFlagGuard Guard(B);
1283       B.setFastMathFlags(CI->getFastMathFlags());
1284       return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1285                                   Callee->getAttributes());
1286     }
1287 
1288     // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1289     // This is faster than calling pow, and still handles negative zero
1290     // and negative infinity correctly.
1291     // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1292     Value *Inf = ConstantFP::getInfinity(CI->getType());
1293     Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1294     Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1295     Value *FAbs =
1296         emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1297     Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1298     Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1299     return Sel;
1300   }
1301 
1302   if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1303     return Op1;
1304   if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1305     return B.CreateFMul(Op1, Op1, "pow2");
1306   if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1307     return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1308 
1309   // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1310   if (CI->hasUnsafeAlgebra()) {
1311     APFloat V = abs(Op2C->getValueAPF());
1312     // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1313     // This transformation applies to integer exponents only.
1314     if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1315         !V.isInteger())
1316       return nullptr;
1317 
1318     // We will memoize intermediate products of the Addition Chain.
1319     Value *InnerChain[33] = {nullptr};
1320     InnerChain[1] = Op1;
1321     InnerChain[2] = B.CreateFMul(Op1, Op1);
1322 
1323     // We cannot readily convert a non-double type (like float) to a double.
1324     // So we first convert V to something which could be converted to double.
1325     bool ignored;
1326     V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
1327 
1328     // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
1329     Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1330     // For negative exponents simply compute the reciprocal.
1331     if (Op2C->isNegative())
1332       FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1333     return FMul;
1334   }
1335 
1336   return nullptr;
1337 }
1338 
1339 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1340   Function *Callee = CI->getCalledFunction();
1341   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1342     return nullptr;
1343 
1344   Value *Ret = nullptr;
1345   StringRef Name = Callee->getName();
1346   if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1347     Ret = optimizeUnaryDoubleFP(CI, B, true);
1348 
1349   Value *Op = CI->getArgOperand(0);
1350   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1351   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1352   LibFunc::Func LdExp = LibFunc::ldexpl;
1353   if (Op->getType()->isFloatTy())
1354     LdExp = LibFunc::ldexpf;
1355   else if (Op->getType()->isDoubleTy())
1356     LdExp = LibFunc::ldexp;
1357 
1358   if (TLI->has(LdExp)) {
1359     Value *LdExpArg = nullptr;
1360     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1361       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1362         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1363     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1364       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1365         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1366     }
1367 
1368     if (LdExpArg) {
1369       Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1370       if (!Op->getType()->isFloatTy())
1371         One = ConstantExpr::getFPExtend(One, Op->getType());
1372 
1373       Module *M = CI->getModule();
1374       Value *NewCallee =
1375           M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1376                                  Op->getType(), B.getInt32Ty(), nullptr);
1377       CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1378       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1379         CI->setCallingConv(F->getCallingConv());
1380 
1381       return CI;
1382     }
1383   }
1384   return Ret;
1385 }
1386 
1387 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1388   Function *Callee = CI->getCalledFunction();
1389   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1390     return nullptr;
1391 
1392   Value *Ret = nullptr;
1393   StringRef Name = Callee->getName();
1394   if (Name == "fabs" && hasFloatVersion(Name))
1395     Ret = optimizeUnaryDoubleFP(CI, B, false);
1396 
1397   Value *Op = CI->getArgOperand(0);
1398   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1399     // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1400     if (I->getOpcode() == Instruction::FMul)
1401       if (I->getOperand(0) == I->getOperand(1))
1402         return Op;
1403   }
1404   return Ret;
1405 }
1406 
1407 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1408   Function *Callee = CI->getCalledFunction();
1409   if (!matchesFPLibFunctionSignature(Callee, 2, false))
1410     return nullptr;
1411 
1412   // If we can shrink the call to a float function rather than a double
1413   // function, do that first.
1414   StringRef Name = Callee->getName();
1415   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1416     if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1417       return Ret;
1418 
1419   IRBuilder<>::FastMathFlagGuard Guard(B);
1420   FastMathFlags FMF;
1421   if (CI->hasUnsafeAlgebra()) {
1422     // Unsafe algebra sets all fast-math-flags to true.
1423     FMF.setUnsafeAlgebra();
1424   } else {
1425     // At a minimum, no-nans-fp-math must be true.
1426     if (!CI->hasNoNaNs())
1427       return nullptr;
1428     // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1429     // "Ideally, fmax would be sensitive to the sign of zero, for example
1430     // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1431     // might be impractical."
1432     FMF.setNoSignedZeros();
1433     FMF.setNoNaNs();
1434   }
1435   B.setFastMathFlags(FMF);
1436 
1437   // We have a relaxed floating-point environment. We can ignore NaN-handling
1438   // and transform to a compare and select. We do not have to consider errno or
1439   // exceptions, because fmin/fmax do not have those.
1440   Value *Op0 = CI->getArgOperand(0);
1441   Value *Op1 = CI->getArgOperand(1);
1442   Value *Cmp = Callee->getName().startswith("fmin") ?
1443     B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1444   return B.CreateSelect(Cmp, Op0, Op1);
1445 }
1446 
1447 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1448   Function *Callee = CI->getCalledFunction();
1449   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1450     return nullptr;
1451 
1452   Value *Ret = nullptr;
1453   StringRef Name = Callee->getName();
1454   if (UnsafeFPShrink && hasFloatVersion(Name))
1455     Ret = optimizeUnaryDoubleFP(CI, B, true);
1456 
1457   if (!CI->hasUnsafeAlgebra())
1458     return Ret;
1459   Value *Op1 = CI->getArgOperand(0);
1460   auto *OpC = dyn_cast<CallInst>(Op1);
1461 
1462   // The earlier call must also be unsafe in order to do these transforms.
1463   if (!OpC || !OpC->hasUnsafeAlgebra())
1464     return Ret;
1465 
1466   // log(pow(x,y)) -> y*log(x)
1467   // This is only applicable to log, log2, log10.
1468   if (Name != "log" && Name != "log2" && Name != "log10")
1469     return Ret;
1470 
1471   IRBuilder<>::FastMathFlagGuard Guard(B);
1472   FastMathFlags FMF;
1473   FMF.setUnsafeAlgebra();
1474   B.setFastMathFlags(FMF);
1475 
1476   LibFunc::Func Func;
1477   Function *F = OpC->getCalledFunction();
1478   if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1479       Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
1480     return B.CreateFMul(OpC->getArgOperand(1),
1481       emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1482                            Callee->getAttributes()), "mul");
1483 
1484   // log(exp2(y)) -> y*log(2)
1485   if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1486       TLI->has(Func) && Func == LibFunc::exp2)
1487     return B.CreateFMul(
1488         OpC->getArgOperand(0),
1489         emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1490                              Callee->getName(), B, Callee->getAttributes()),
1491         "logmul");
1492   return Ret;
1493 }
1494 
1495 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1496   Function *Callee = CI->getCalledFunction();
1497   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1498     return nullptr;
1499 
1500   Value *Ret = nullptr;
1501   if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1502                                    Callee->getIntrinsicID() == Intrinsic::sqrt))
1503     Ret = optimizeUnaryDoubleFP(CI, B, true);
1504 
1505   if (!CI->hasUnsafeAlgebra())
1506     return Ret;
1507 
1508   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1509   if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1510     return Ret;
1511 
1512   // We're looking for a repeated factor in a multiplication tree,
1513   // so we can do this fold: sqrt(x * x) -> fabs(x);
1514   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1515   Value *Op0 = I->getOperand(0);
1516   Value *Op1 = I->getOperand(1);
1517   Value *RepeatOp = nullptr;
1518   Value *OtherOp = nullptr;
1519   if (Op0 == Op1) {
1520     // Simple match: the operands of the multiply are identical.
1521     RepeatOp = Op0;
1522   } else {
1523     // Look for a more complicated pattern: one of the operands is itself
1524     // a multiply, so search for a common factor in that multiply.
1525     // Note: We don't bother looking any deeper than this first level or for
1526     // variations of this pattern because instcombine's visitFMUL and/or the
1527     // reassociation pass should give us this form.
1528     Value *OtherMul0, *OtherMul1;
1529     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1530       // Pattern: sqrt((x * y) * z)
1531       if (OtherMul0 == OtherMul1 &&
1532           cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
1533         // Matched: sqrt((x * x) * z)
1534         RepeatOp = OtherMul0;
1535         OtherOp = Op1;
1536       }
1537     }
1538   }
1539   if (!RepeatOp)
1540     return Ret;
1541 
1542   // Fast math flags for any created instructions should match the sqrt
1543   // and multiply.
1544   IRBuilder<>::FastMathFlagGuard Guard(B);
1545   B.setFastMathFlags(I->getFastMathFlags());
1546 
1547   // If we found a repeated factor, hoist it out of the square root and
1548   // replace it with the fabs of that factor.
1549   Module *M = Callee->getParent();
1550   Type *ArgType = I->getType();
1551   Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1552   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1553   if (OtherOp) {
1554     // If we found a non-repeated factor, we still need to get its square
1555     // root. We then multiply that by the value that was simplified out
1556     // of the square root calculation.
1557     Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1558     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1559     return B.CreateFMul(FabsCall, SqrtCall);
1560   }
1561   return FabsCall;
1562 }
1563 
1564 // TODO: Generalize to handle any trig function and its inverse.
1565 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1566   Function *Callee = CI->getCalledFunction();
1567   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1568     return nullptr;
1569 
1570   Value *Ret = nullptr;
1571   StringRef Name = Callee->getName();
1572   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1573     Ret = optimizeUnaryDoubleFP(CI, B, true);
1574 
1575   Value *Op1 = CI->getArgOperand(0);
1576   auto *OpC = dyn_cast<CallInst>(Op1);
1577   if (!OpC)
1578     return Ret;
1579 
1580   // Both calls must allow unsafe optimizations in order to remove them.
1581   if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1582     return Ret;
1583 
1584   // tan(atan(x)) -> x
1585   // tanf(atanf(x)) -> x
1586   // tanl(atanl(x)) -> x
1587   LibFunc::Func Func;
1588   Function *F = OpC->getCalledFunction();
1589   if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1590       ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1591        (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1592        (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1593     Ret = OpC->getArgOperand(0);
1594   return Ret;
1595 }
1596 
1597 static bool isTrigLibCall(CallInst *CI) {
1598   Function *Callee = CI->getCalledFunction();
1599   FunctionType *FT = Callee->getFunctionType();
1600 
1601   // We can only hope to do anything useful if we can ignore things like errno
1602   // and floating-point exceptions.
1603   bool AttributesSafe =
1604   CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1605 
1606   // Other than that we need float(float) or double(double)
1607   return AttributesSafe && FT->getNumParams() == 1 &&
1608   FT->getReturnType() == FT->getParamType(0) &&
1609   (FT->getParamType(0)->isFloatTy() ||
1610    FT->getParamType(0)->isDoubleTy());
1611 }
1612 
1613 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1614                              bool UseFloat, Value *&Sin, Value *&Cos,
1615                              Value *&SinCos) {
1616   Type *ArgTy = Arg->getType();
1617   Type *ResTy;
1618   StringRef Name;
1619 
1620   Triple T(OrigCallee->getParent()->getTargetTriple());
1621   if (UseFloat) {
1622     Name = "__sincospif_stret";
1623 
1624     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1625     // x86_64 can't use {float, float} since that would be returned in both
1626     // xmm0 and xmm1, which isn't what a real struct would do.
1627     ResTy = T.getArch() == Triple::x86_64
1628     ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1629     : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1630   } else {
1631     Name = "__sincospi_stret";
1632     ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1633   }
1634 
1635   Module *M = OrigCallee->getParent();
1636   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1637                                          ResTy, ArgTy, nullptr);
1638 
1639   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1640     // If the argument is an instruction, it must dominate all uses so put our
1641     // sincos call there.
1642     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1643   } else {
1644     // Otherwise (e.g. for a constant) the beginning of the function is as
1645     // good a place as any.
1646     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1647     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1648   }
1649 
1650   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1651 
1652   if (SinCos->getType()->isStructTy()) {
1653     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1654     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1655   } else {
1656     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1657                                  "sinpi");
1658     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1659                                  "cospi");
1660   }
1661 }
1662 
1663 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1664   // Make sure the prototype is as expected, otherwise the rest of the
1665   // function is probably invalid and likely to abort.
1666   if (!isTrigLibCall(CI))
1667     return nullptr;
1668 
1669   Value *Arg = CI->getArgOperand(0);
1670   SmallVector<CallInst *, 1> SinCalls;
1671   SmallVector<CallInst *, 1> CosCalls;
1672   SmallVector<CallInst *, 1> SinCosCalls;
1673 
1674   bool IsFloat = Arg->getType()->isFloatTy();
1675 
1676   // Look for all compatible sinpi, cospi and sincospi calls with the same
1677   // argument. If there are enough (in some sense) we can make the
1678   // substitution.
1679   Function *F = CI->getFunction();
1680   for (User *U : Arg->users())
1681     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1682 
1683   // It's only worthwhile if both sinpi and cospi are actually used.
1684   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1685     return nullptr;
1686 
1687   Value *Sin, *Cos, *SinCos;
1688   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1689 
1690   replaceTrigInsts(SinCalls, Sin);
1691   replaceTrigInsts(CosCalls, Cos);
1692   replaceTrigInsts(SinCosCalls, SinCos);
1693 
1694   return nullptr;
1695 }
1696 
1697 void LibCallSimplifier::classifyArgUse(
1698     Value *Val, Function *F, bool IsFloat,
1699     SmallVectorImpl<CallInst *> &SinCalls,
1700     SmallVectorImpl<CallInst *> &CosCalls,
1701     SmallVectorImpl<CallInst *> &SinCosCalls) {
1702   CallInst *CI = dyn_cast<CallInst>(Val);
1703 
1704   if (!CI)
1705     return;
1706 
1707   // Don't consider calls in other functions.
1708   if (CI->getFunction() != F)
1709     return;
1710 
1711   Function *Callee = CI->getCalledFunction();
1712   LibFunc::Func Func;
1713   if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1714       !isTrigLibCall(CI))
1715     return;
1716 
1717   if (IsFloat) {
1718     if (Func == LibFunc::sinpif)
1719       SinCalls.push_back(CI);
1720     else if (Func == LibFunc::cospif)
1721       CosCalls.push_back(CI);
1722     else if (Func == LibFunc::sincospif_stret)
1723       SinCosCalls.push_back(CI);
1724   } else {
1725     if (Func == LibFunc::sinpi)
1726       SinCalls.push_back(CI);
1727     else if (Func == LibFunc::cospi)
1728       CosCalls.push_back(CI);
1729     else if (Func == LibFunc::sincospi_stret)
1730       SinCosCalls.push_back(CI);
1731   }
1732 }
1733 
1734 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1735                                          Value *Res) {
1736   for (CallInst *C : Calls)
1737     replaceAllUsesWith(C, Res);
1738 }
1739 
1740 //===----------------------------------------------------------------------===//
1741 // Integer Library Call Optimizations
1742 //===----------------------------------------------------------------------===//
1743 
1744 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1745   FunctionType *FT = Callee->getFunctionType();
1746   return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1747     FT->getParamType(0)->isIntegerTy();
1748 }
1749 
1750 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1751   Function *Callee = CI->getCalledFunction();
1752   if (!checkIntUnaryReturnAndParam(Callee))
1753     return nullptr;
1754   Value *Op = CI->getArgOperand(0);
1755 
1756   // Constant fold.
1757   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1758     if (CI->isZero()) // ffs(0) -> 0.
1759       return B.getInt32(0);
1760     // ffs(c) -> cttz(c)+1
1761     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1762   }
1763 
1764   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1765   Type *ArgType = Op->getType();
1766   Value *F =
1767       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1768   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1769   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1770   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1771 
1772   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1773   return B.CreateSelect(Cond, V, B.getInt32(0));
1774 }
1775 
1776 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1777   Function *Callee = CI->getCalledFunction();
1778   FunctionType *FT = Callee->getFunctionType();
1779   // We require integer(integer) where the types agree.
1780   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1781       FT->getParamType(0) != FT->getReturnType())
1782     return nullptr;
1783 
1784   // abs(x) -> x >s -1 ? x : -x
1785   Value *Op = CI->getArgOperand(0);
1786   Value *Pos =
1787       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1788   Value *Neg = B.CreateNeg(Op, "neg");
1789   return B.CreateSelect(Pos, Op, Neg);
1790 }
1791 
1792 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1793   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1794     return nullptr;
1795 
1796   // isdigit(c) -> (c-'0') <u 10
1797   Value *Op = CI->getArgOperand(0);
1798   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1799   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1800   return B.CreateZExt(Op, CI->getType());
1801 }
1802 
1803 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1804   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1805     return nullptr;
1806 
1807   // isascii(c) -> c <u 128
1808   Value *Op = CI->getArgOperand(0);
1809   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1810   return B.CreateZExt(Op, CI->getType());
1811 }
1812 
1813 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1814   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1815     return nullptr;
1816 
1817   // toascii(c) -> c & 0x7f
1818   return B.CreateAnd(CI->getArgOperand(0),
1819                      ConstantInt::get(CI->getType(), 0x7F));
1820 }
1821 
1822 //===----------------------------------------------------------------------===//
1823 // Formatting and IO Library Call Optimizations
1824 //===----------------------------------------------------------------------===//
1825 
1826 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1827 
1828 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1829                                                  int StreamArg) {
1830   // Error reporting calls should be cold, mark them as such.
1831   // This applies even to non-builtin calls: it is only a hint and applies to
1832   // functions that the frontend might not understand as builtins.
1833 
1834   // This heuristic was suggested in:
1835   // Improving Static Branch Prediction in a Compiler
1836   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1837   // Proceedings of PACT'98, Oct. 1998, IEEE
1838   Function *Callee = CI->getCalledFunction();
1839 
1840   if (!CI->hasFnAttr(Attribute::Cold) &&
1841       isReportingError(Callee, CI, StreamArg)) {
1842     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1843   }
1844 
1845   return nullptr;
1846 }
1847 
1848 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1849   if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1850     return false;
1851 
1852   if (StreamArg < 0)
1853     return true;
1854 
1855   // These functions might be considered cold, but only if their stream
1856   // argument is stderr.
1857 
1858   if (StreamArg >= (int)CI->getNumArgOperands())
1859     return false;
1860   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1861   if (!LI)
1862     return false;
1863   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1864   if (!GV || !GV->isDeclaration())
1865     return false;
1866   return GV->getName() == "stderr";
1867 }
1868 
1869 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1870   // Check for a fixed format string.
1871   StringRef FormatStr;
1872   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1873     return nullptr;
1874 
1875   // Empty format string -> noop.
1876   if (FormatStr.empty()) // Tolerate printf's declared void.
1877     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1878 
1879   // Do not do any of the following transformations if the printf return value
1880   // is used, in general the printf return value is not compatible with either
1881   // putchar() or puts().
1882   if (!CI->use_empty())
1883     return nullptr;
1884 
1885   // printf("x") -> putchar('x'), even for '%'.
1886   if (FormatStr.size() == 1)
1887     return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1888 
1889   // printf("%s", "a") --> putchar('a')
1890   if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1891     StringRef ChrStr;
1892     if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1893       return nullptr;
1894     if (ChrStr.size() != 1)
1895       return nullptr;
1896     return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1897   }
1898 
1899   // printf("foo\n") --> puts("foo")
1900   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1901       FormatStr.find('%') == StringRef::npos) { // No format characters.
1902     // Create a string literal with no \n on it.  We expect the constant merge
1903     // pass to be run after this pass, to merge duplicate strings.
1904     FormatStr = FormatStr.drop_back();
1905     Value *GV = B.CreateGlobalString(FormatStr, "str");
1906     return emitPutS(GV, B, TLI);
1907   }
1908 
1909   // Optimize specific format strings.
1910   // printf("%c", chr) --> putchar(chr)
1911   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1912       CI->getArgOperand(1)->getType()->isIntegerTy())
1913     return emitPutChar(CI->getArgOperand(1), B, TLI);
1914 
1915   // printf("%s\n", str) --> puts(str)
1916   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1917       CI->getArgOperand(1)->getType()->isPointerTy())
1918     return emitPutS(CI->getArgOperand(1), B, TLI);
1919   return nullptr;
1920 }
1921 
1922 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1923 
1924   Function *Callee = CI->getCalledFunction();
1925   // Require one fixed pointer argument and an integer/void result.
1926   FunctionType *FT = Callee->getFunctionType();
1927   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1928       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1929     return nullptr;
1930 
1931   if (Value *V = optimizePrintFString(CI, B)) {
1932     return V;
1933   }
1934 
1935   // printf(format, ...) -> iprintf(format, ...) if no floating point
1936   // arguments.
1937   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1938     Module *M = B.GetInsertBlock()->getParent()->getParent();
1939     Constant *IPrintFFn =
1940         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1941     CallInst *New = cast<CallInst>(CI->clone());
1942     New->setCalledFunction(IPrintFFn);
1943     B.Insert(New);
1944     return New;
1945   }
1946   return nullptr;
1947 }
1948 
1949 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1950   // Check for a fixed format string.
1951   StringRef FormatStr;
1952   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1953     return nullptr;
1954 
1955   // If we just have a format string (nothing else crazy) transform it.
1956   if (CI->getNumArgOperands() == 2) {
1957     // Make sure there's no % in the constant array.  We could try to handle
1958     // %% -> % in the future if we cared.
1959     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1960       if (FormatStr[i] == '%')
1961         return nullptr; // we found a format specifier, bail out.
1962 
1963     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1964     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1965                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1966                                     FormatStr.size() + 1),
1967                    1); // Copy the null byte.
1968     return ConstantInt::get(CI->getType(), FormatStr.size());
1969   }
1970 
1971   // The remaining optimizations require the format string to be "%s" or "%c"
1972   // and have an extra operand.
1973   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1974       CI->getNumArgOperands() < 3)
1975     return nullptr;
1976 
1977   // Decode the second character of the format string.
1978   if (FormatStr[1] == 'c') {
1979     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1980     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1981       return nullptr;
1982     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1983     Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1984     B.CreateStore(V, Ptr);
1985     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1986     B.CreateStore(B.getInt8(0), Ptr);
1987 
1988     return ConstantInt::get(CI->getType(), 1);
1989   }
1990 
1991   if (FormatStr[1] == 's') {
1992     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1993     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1994       return nullptr;
1995 
1996     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1997     if (!Len)
1998       return nullptr;
1999     Value *IncLen =
2000         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2001     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
2002 
2003     // The sprintf result is the unincremented number of bytes in the string.
2004     return B.CreateIntCast(Len, CI->getType(), false);
2005   }
2006   return nullptr;
2007 }
2008 
2009 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2010   Function *Callee = CI->getCalledFunction();
2011   // Require two fixed pointer arguments and an integer result.
2012   FunctionType *FT = Callee->getFunctionType();
2013   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2014       !FT->getParamType(1)->isPointerTy() ||
2015       !FT->getReturnType()->isIntegerTy())
2016     return nullptr;
2017 
2018   if (Value *V = optimizeSPrintFString(CI, B)) {
2019     return V;
2020   }
2021 
2022   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2023   // point arguments.
2024   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
2025     Module *M = B.GetInsertBlock()->getParent()->getParent();
2026     Constant *SIPrintFFn =
2027         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2028     CallInst *New = cast<CallInst>(CI->clone());
2029     New->setCalledFunction(SIPrintFFn);
2030     B.Insert(New);
2031     return New;
2032   }
2033   return nullptr;
2034 }
2035 
2036 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2037   optimizeErrorReporting(CI, B, 0);
2038 
2039   // All the optimizations depend on the format string.
2040   StringRef FormatStr;
2041   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2042     return nullptr;
2043 
2044   // Do not do any of the following transformations if the fprintf return
2045   // value is used, in general the fprintf return value is not compatible
2046   // with fwrite(), fputc() or fputs().
2047   if (!CI->use_empty())
2048     return nullptr;
2049 
2050   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2051   if (CI->getNumArgOperands() == 2) {
2052     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
2053       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
2054         return nullptr;        // We found a format specifier.
2055 
2056     return emitFWrite(
2057         CI->getArgOperand(1),
2058         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2059         CI->getArgOperand(0), B, DL, TLI);
2060   }
2061 
2062   // The remaining optimizations require the format string to be "%s" or "%c"
2063   // and have an extra operand.
2064   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2065       CI->getNumArgOperands() < 3)
2066     return nullptr;
2067 
2068   // Decode the second character of the format string.
2069   if (FormatStr[1] == 'c') {
2070     // fprintf(F, "%c", chr) --> fputc(chr, F)
2071     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2072       return nullptr;
2073     return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2074   }
2075 
2076   if (FormatStr[1] == 's') {
2077     // fprintf(F, "%s", str) --> fputs(str, F)
2078     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2079       return nullptr;
2080     return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2081   }
2082   return nullptr;
2083 }
2084 
2085 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2086   Function *Callee = CI->getCalledFunction();
2087   // Require two fixed paramters as pointers and integer result.
2088   FunctionType *FT = Callee->getFunctionType();
2089   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2090       !FT->getParamType(1)->isPointerTy() ||
2091       !FT->getReturnType()->isIntegerTy())
2092     return nullptr;
2093 
2094   if (Value *V = optimizeFPrintFString(CI, B)) {
2095     return V;
2096   }
2097 
2098   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2099   // floating point arguments.
2100   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2101     Module *M = B.GetInsertBlock()->getParent()->getParent();
2102     Constant *FIPrintFFn =
2103         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2104     CallInst *New = cast<CallInst>(CI->clone());
2105     New->setCalledFunction(FIPrintFFn);
2106     B.Insert(New);
2107     return New;
2108   }
2109   return nullptr;
2110 }
2111 
2112 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2113   optimizeErrorReporting(CI, B, 3);
2114 
2115   Function *Callee = CI->getCalledFunction();
2116   // Require a pointer, an integer, an integer, a pointer, returning integer.
2117   FunctionType *FT = Callee->getFunctionType();
2118   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2119       !FT->getParamType(1)->isIntegerTy() ||
2120       !FT->getParamType(2)->isIntegerTy() ||
2121       !FT->getParamType(3)->isPointerTy() ||
2122       !FT->getReturnType()->isIntegerTy())
2123     return nullptr;
2124 
2125   // Get the element size and count.
2126   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2127   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2128   if (!SizeC || !CountC)
2129     return nullptr;
2130   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2131 
2132   // If this is writing zero records, remove the call (it's a noop).
2133   if (Bytes == 0)
2134     return ConstantInt::get(CI->getType(), 0);
2135 
2136   // If this is writing one byte, turn it into fputc.
2137   // This optimisation is only valid, if the return value is unused.
2138   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2139     Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2140     Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2141     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2142   }
2143 
2144   return nullptr;
2145 }
2146 
2147 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2148   optimizeErrorReporting(CI, B, 1);
2149 
2150   Function *Callee = CI->getCalledFunction();
2151 
2152   // Require two pointers.  Also, we can't optimize if return value is used.
2153   FunctionType *FT = Callee->getFunctionType();
2154   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2155       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2156     return nullptr;
2157 
2158   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2159   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2160   if (!Len)
2161     return nullptr;
2162 
2163   // Known to have no uses (see above).
2164   return emitFWrite(
2165       CI->getArgOperand(0),
2166       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2167       CI->getArgOperand(1), B, DL, TLI);
2168 }
2169 
2170 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2171   Function *Callee = CI->getCalledFunction();
2172   // Require one fixed pointer argument and an integer/void result.
2173   FunctionType *FT = Callee->getFunctionType();
2174   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2175       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2176     return nullptr;
2177 
2178   // Check for a constant string.
2179   StringRef Str;
2180   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2181     return nullptr;
2182 
2183   if (Str.empty() && CI->use_empty()) {
2184     // puts("") -> putchar('\n')
2185     Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2186     if (CI->use_empty() || !Res)
2187       return Res;
2188     return B.CreateIntCast(Res, CI->getType(), true);
2189   }
2190 
2191   return nullptr;
2192 }
2193 
2194 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2195   LibFunc::Func Func;
2196   SmallString<20> FloatFuncName = FuncName;
2197   FloatFuncName += 'f';
2198   if (TLI->getLibFunc(FloatFuncName, Func))
2199     return TLI->has(Func);
2200   return false;
2201 }
2202 
2203 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2204                                                       IRBuilder<> &Builder) {
2205   LibFunc::Func Func;
2206   Function *Callee = CI->getCalledFunction();
2207   StringRef FuncName = Callee->getName();
2208 
2209   // Check for string/memory library functions.
2210   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2211     // Make sure we never change the calling convention.
2212     assert((ignoreCallingConv(Func) ||
2213             CI->getCallingConv() == llvm::CallingConv::C) &&
2214       "Optimizing string/memory libcall would change the calling convention");
2215     switch (Func) {
2216     case LibFunc::strcat:
2217       return optimizeStrCat(CI, Builder);
2218     case LibFunc::strncat:
2219       return optimizeStrNCat(CI, Builder);
2220     case LibFunc::strchr:
2221       return optimizeStrChr(CI, Builder);
2222     case LibFunc::strrchr:
2223       return optimizeStrRChr(CI, Builder);
2224     case LibFunc::strcmp:
2225       return optimizeStrCmp(CI, Builder);
2226     case LibFunc::strncmp:
2227       return optimizeStrNCmp(CI, Builder);
2228     case LibFunc::strcpy:
2229       return optimizeStrCpy(CI, Builder);
2230     case LibFunc::stpcpy:
2231       return optimizeStpCpy(CI, Builder);
2232     case LibFunc::strncpy:
2233       return optimizeStrNCpy(CI, Builder);
2234     case LibFunc::strlen:
2235       return optimizeStrLen(CI, Builder);
2236     case LibFunc::strpbrk:
2237       return optimizeStrPBrk(CI, Builder);
2238     case LibFunc::strtol:
2239     case LibFunc::strtod:
2240     case LibFunc::strtof:
2241     case LibFunc::strtoul:
2242     case LibFunc::strtoll:
2243     case LibFunc::strtold:
2244     case LibFunc::strtoull:
2245       return optimizeStrTo(CI, Builder);
2246     case LibFunc::strspn:
2247       return optimizeStrSpn(CI, Builder);
2248     case LibFunc::strcspn:
2249       return optimizeStrCSpn(CI, Builder);
2250     case LibFunc::strstr:
2251       return optimizeStrStr(CI, Builder);
2252     case LibFunc::memchr:
2253       return optimizeMemChr(CI, Builder);
2254     case LibFunc::memcmp:
2255       return optimizeMemCmp(CI, Builder);
2256     case LibFunc::memcpy:
2257       return optimizeMemCpy(CI, Builder);
2258     case LibFunc::memmove:
2259       return optimizeMemMove(CI, Builder);
2260     case LibFunc::memset:
2261       return optimizeMemSet(CI, Builder);
2262     default:
2263       break;
2264     }
2265   }
2266   return nullptr;
2267 }
2268 
2269 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2270   if (CI->isNoBuiltin())
2271     return nullptr;
2272 
2273   LibFunc::Func Func;
2274   Function *Callee = CI->getCalledFunction();
2275   StringRef FuncName = Callee->getName();
2276 
2277   SmallVector<OperandBundleDef, 2> OpBundles;
2278   CI->getOperandBundlesAsDefs(OpBundles);
2279   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2280   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2281 
2282   // Command-line parameter overrides instruction attribute.
2283   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2284     UnsafeFPShrink = EnableUnsafeFPShrink;
2285   else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
2286     UnsafeFPShrink = true;
2287 
2288   // First, check for intrinsics.
2289   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2290     if (!isCallingConvC)
2291       return nullptr;
2292     switch (II->getIntrinsicID()) {
2293     case Intrinsic::pow:
2294       return optimizePow(CI, Builder);
2295     case Intrinsic::exp2:
2296       return optimizeExp2(CI, Builder);
2297     case Intrinsic::fabs:
2298       return optimizeFabs(CI, Builder);
2299     case Intrinsic::log:
2300       return optimizeLog(CI, Builder);
2301     case Intrinsic::sqrt:
2302       return optimizeSqrt(CI, Builder);
2303     // TODO: Use foldMallocMemset() with memset intrinsic.
2304     default:
2305       return nullptr;
2306     }
2307   }
2308 
2309   // Also try to simplify calls to fortified library functions.
2310   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2311     // Try to further simplify the result.
2312     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2313     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2314       // Use an IR Builder from SimplifiedCI if available instead of CI
2315       // to guarantee we reach all uses we might replace later on.
2316       IRBuilder<> TmpBuilder(SimplifiedCI);
2317       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2318         // If we were able to further simplify, remove the now redundant call.
2319         SimplifiedCI->replaceAllUsesWith(V);
2320         SimplifiedCI->eraseFromParent();
2321         return V;
2322       }
2323     }
2324     return SimplifiedFortifiedCI;
2325   }
2326 
2327   // Then check for known library functions.
2328   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2329     // We never change the calling convention.
2330     if (!ignoreCallingConv(Func) && !isCallingConvC)
2331       return nullptr;
2332     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2333       return V;
2334     switch (Func) {
2335     case LibFunc::cosf:
2336     case LibFunc::cos:
2337     case LibFunc::cosl:
2338       return optimizeCos(CI, Builder);
2339     case LibFunc::sinpif:
2340     case LibFunc::sinpi:
2341     case LibFunc::cospif:
2342     case LibFunc::cospi:
2343       return optimizeSinCosPi(CI, Builder);
2344     case LibFunc::powf:
2345     case LibFunc::pow:
2346     case LibFunc::powl:
2347       return optimizePow(CI, Builder);
2348     case LibFunc::exp2l:
2349     case LibFunc::exp2:
2350     case LibFunc::exp2f:
2351       return optimizeExp2(CI, Builder);
2352     case LibFunc::fabsf:
2353     case LibFunc::fabs:
2354     case LibFunc::fabsl:
2355       return optimizeFabs(CI, Builder);
2356     case LibFunc::sqrtf:
2357     case LibFunc::sqrt:
2358     case LibFunc::sqrtl:
2359       return optimizeSqrt(CI, Builder);
2360     case LibFunc::ffs:
2361     case LibFunc::ffsl:
2362     case LibFunc::ffsll:
2363       return optimizeFFS(CI, Builder);
2364     case LibFunc::abs:
2365     case LibFunc::labs:
2366     case LibFunc::llabs:
2367       return optimizeAbs(CI, Builder);
2368     case LibFunc::isdigit:
2369       return optimizeIsDigit(CI, Builder);
2370     case LibFunc::isascii:
2371       return optimizeIsAscii(CI, Builder);
2372     case LibFunc::toascii:
2373       return optimizeToAscii(CI, Builder);
2374     case LibFunc::printf:
2375       return optimizePrintF(CI, Builder);
2376     case LibFunc::sprintf:
2377       return optimizeSPrintF(CI, Builder);
2378     case LibFunc::fprintf:
2379       return optimizeFPrintF(CI, Builder);
2380     case LibFunc::fwrite:
2381       return optimizeFWrite(CI, Builder);
2382     case LibFunc::fputs:
2383       return optimizeFPuts(CI, Builder);
2384     case LibFunc::log:
2385     case LibFunc::log10:
2386     case LibFunc::log1p:
2387     case LibFunc::log2:
2388     case LibFunc::logb:
2389       return optimizeLog(CI, Builder);
2390     case LibFunc::puts:
2391       return optimizePuts(CI, Builder);
2392     case LibFunc::tan:
2393     case LibFunc::tanf:
2394     case LibFunc::tanl:
2395       return optimizeTan(CI, Builder);
2396     case LibFunc::perror:
2397       return optimizeErrorReporting(CI, Builder);
2398     case LibFunc::vfprintf:
2399     case LibFunc::fiprintf:
2400       return optimizeErrorReporting(CI, Builder, 0);
2401     case LibFunc::fputc:
2402       return optimizeErrorReporting(CI, Builder, 1);
2403     case LibFunc::ceil:
2404     case LibFunc::floor:
2405     case LibFunc::rint:
2406     case LibFunc::round:
2407     case LibFunc::nearbyint:
2408     case LibFunc::trunc:
2409       if (hasFloatVersion(FuncName))
2410         return optimizeUnaryDoubleFP(CI, Builder, false);
2411       return nullptr;
2412     case LibFunc::acos:
2413     case LibFunc::acosh:
2414     case LibFunc::asin:
2415     case LibFunc::asinh:
2416     case LibFunc::atan:
2417     case LibFunc::atanh:
2418     case LibFunc::cbrt:
2419     case LibFunc::cosh:
2420     case LibFunc::exp:
2421     case LibFunc::exp10:
2422     case LibFunc::expm1:
2423     case LibFunc::sin:
2424     case LibFunc::sinh:
2425     case LibFunc::tanh:
2426       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2427         return optimizeUnaryDoubleFP(CI, Builder, true);
2428       return nullptr;
2429     case LibFunc::copysign:
2430       if (hasFloatVersion(FuncName))
2431         return optimizeBinaryDoubleFP(CI, Builder);
2432       return nullptr;
2433     case LibFunc::fminf:
2434     case LibFunc::fmin:
2435     case LibFunc::fminl:
2436     case LibFunc::fmaxf:
2437     case LibFunc::fmax:
2438     case LibFunc::fmaxl:
2439       return optimizeFMinFMax(CI, Builder);
2440     default:
2441       return nullptr;
2442     }
2443   }
2444   return nullptr;
2445 }
2446 
2447 LibCallSimplifier::LibCallSimplifier(
2448     const DataLayout &DL, const TargetLibraryInfo *TLI,
2449     function_ref<void(Instruction *, Value *)> Replacer)
2450     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2451       Replacer(Replacer) {}
2452 
2453 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2454   // Indirect through the replacer used in this instance.
2455   Replacer(I, With);
2456 }
2457 
2458 // TODO:
2459 //   Additional cases that we need to add to this file:
2460 //
2461 // cbrt:
2462 //   * cbrt(expN(X))  -> expN(x/3)
2463 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2464 //   * cbrt(cbrt(x))  -> pow(x,1/9)
2465 //
2466 // exp, expf, expl:
2467 //   * exp(log(x))  -> x
2468 //
2469 // log, logf, logl:
2470 //   * log(exp(x))   -> x
2471 //   * log(exp(y))   -> y*log(e)
2472 //   * log(exp10(y)) -> y*log(10)
2473 //   * log(sqrt(x))  -> 0.5*log(x)
2474 //
2475 // lround, lroundf, lroundl:
2476 //   * lround(cnst) -> cnst'
2477 //
2478 // pow, powf, powl:
2479 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2480 //   * pow(pow(x,y),z)-> pow(x,y*z)
2481 //
2482 // round, roundf, roundl:
2483 //   * round(cnst) -> cnst'
2484 //
2485 // signbit:
2486 //   * signbit(cnst) -> cnst'
2487 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2488 //
2489 // sqrt, sqrtf, sqrtl:
2490 //   * sqrt(expN(x))  -> expN(x*0.5)
2491 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2492 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2493 //
2494 // trunc, truncf, truncl:
2495 //   * trunc(cnst) -> cnst'
2496 //
2497 //
2498 
2499 //===----------------------------------------------------------------------===//
2500 // Fortified Library Call Optimizations
2501 //===----------------------------------------------------------------------===//
2502 
2503 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2504                                                          unsigned ObjSizeOp,
2505                                                          unsigned SizeOp,
2506                                                          bool isString) {
2507   if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2508     return true;
2509   if (ConstantInt *ObjSizeCI =
2510           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2511     if (ObjSizeCI->isAllOnesValue())
2512       return true;
2513     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2514     if (OnlyLowerUnknownSize)
2515       return false;
2516     if (isString) {
2517       uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2518       // If the length is 0 we don't know how long it is and so we can't
2519       // remove the check.
2520       if (Len == 0)
2521         return false;
2522       return ObjSizeCI->getZExtValue() >= Len;
2523     }
2524     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2525       return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2526   }
2527   return false;
2528 }
2529 
2530 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2531                                                      IRBuilder<> &B) {
2532   Function *Callee = CI->getCalledFunction();
2533 
2534   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2535     return nullptr;
2536 
2537   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2538     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2539                    CI->getArgOperand(2), 1);
2540     return CI->getArgOperand(0);
2541   }
2542   return nullptr;
2543 }
2544 
2545 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2546                                                       IRBuilder<> &B) {
2547   Function *Callee = CI->getCalledFunction();
2548 
2549   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2550     return nullptr;
2551 
2552   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2553     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2554                     CI->getArgOperand(2), 1);
2555     return CI->getArgOperand(0);
2556   }
2557   return nullptr;
2558 }
2559 
2560 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2561                                                      IRBuilder<> &B) {
2562   Function *Callee = CI->getCalledFunction();
2563 
2564   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2565     return nullptr;
2566 
2567   // TODO: Try foldMallocMemset() here.
2568 
2569   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2570     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2571     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2572     return CI->getArgOperand(0);
2573   }
2574   return nullptr;
2575 }
2576 
2577 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2578                                                       IRBuilder<> &B,
2579                                                       LibFunc::Func Func) {
2580   Function *Callee = CI->getCalledFunction();
2581   StringRef Name = Callee->getName();
2582   const DataLayout &DL = CI->getModule()->getDataLayout();
2583 
2584   if (!checkStringCopyLibFuncSignature(Callee, Func))
2585     return nullptr;
2586 
2587   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2588         *ObjSize = CI->getArgOperand(2);
2589 
2590   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
2591   if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2592     Value *StrLen = emitStrLen(Src, B, DL, TLI);
2593     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2594   }
2595 
2596   // If a) we don't have any length information, or b) we know this will
2597   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2598   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2599   // TODO: It might be nice to get a maximum length out of the possible
2600   // string lengths for varying.
2601   if (isFortifiedCallFoldable(CI, 2, 1, true))
2602     return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2603 
2604   if (OnlyLowerUnknownSize)
2605     return nullptr;
2606 
2607   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2608   uint64_t Len = GetStringLength(Src);
2609   if (Len == 0)
2610     return nullptr;
2611 
2612   Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2613   Value *LenV = ConstantInt::get(SizeTTy, Len);
2614   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2615   // If the function was an __stpcpy_chk, and we were able to fold it into
2616   // a __memcpy_chk, we still need to return the correct end pointer.
2617   if (Ret && Func == LibFunc::stpcpy_chk)
2618     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2619   return Ret;
2620 }
2621 
2622 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2623                                                        IRBuilder<> &B,
2624                                                        LibFunc::Func Func) {
2625   Function *Callee = CI->getCalledFunction();
2626   StringRef Name = Callee->getName();
2627 
2628   if (!checkStringCopyLibFuncSignature(Callee, Func))
2629     return nullptr;
2630   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2631     Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2632                              CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2633     return Ret;
2634   }
2635   return nullptr;
2636 }
2637 
2638 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2639   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2640   // Some clang users checked for _chk libcall availability using:
2641   //   __has_builtin(__builtin___memcpy_chk)
2642   // When compiling with -fno-builtin, this is always true.
2643   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2644   // end up with fortified libcalls, which isn't acceptable in a freestanding
2645   // environment which only provides their non-fortified counterparts.
2646   //
2647   // Until we change clang and/or teach external users to check for availability
2648   // differently, disregard the "nobuiltin" attribute and TLI::has.
2649   //
2650   // PR23093.
2651 
2652   LibFunc::Func Func;
2653   Function *Callee = CI->getCalledFunction();
2654   StringRef FuncName = Callee->getName();
2655 
2656   SmallVector<OperandBundleDef, 2> OpBundles;
2657   CI->getOperandBundlesAsDefs(OpBundles);
2658   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2659   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2660 
2661   // First, check that this is a known library functions.
2662   if (!TLI->getLibFunc(FuncName, Func))
2663     return nullptr;
2664 
2665   // We never change the calling convention.
2666   if (!ignoreCallingConv(Func) && !isCallingConvC)
2667     return nullptr;
2668 
2669   switch (Func) {
2670   case LibFunc::memcpy_chk:
2671     return optimizeMemCpyChk(CI, Builder);
2672   case LibFunc::memmove_chk:
2673     return optimizeMemMoveChk(CI, Builder);
2674   case LibFunc::memset_chk:
2675     return optimizeMemSetChk(CI, Builder);
2676   case LibFunc::stpcpy_chk:
2677   case LibFunc::strcpy_chk:
2678     return optimizeStrpCpyChk(CI, Builder, Func);
2679   case LibFunc::stpncpy_chk:
2680   case LibFunc::strncpy_chk:
2681     return optimizeStrpNCpyChk(CI, Builder, Func);
2682   default:
2683     break;
2684   }
2685   return nullptr;
2686 }
2687 
2688 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2689     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2690     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
2691