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