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 isPrecise = false) {
969   if (!CI->getType()->isDoubleTy())
970     return nullptr;
971 
972   // If not all the uses of the function are converted to float, then bail out.
973   // This matters if the precision of the result is more important than the
974   // precision of the arguments.
975   if (isPrecise)
976     for (User *U : CI->users()) {
977       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
978       if (!Cast || !Cast->getType()->isFloatTy())
979         return nullptr;
980     }
981 
982   // If this is something like 'g((double) float)', convert to 'gf(float)'.
983   Value *V[2];
984   V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
985   V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
986   if (!V[0] || (isBinary && !V[1]))
987     return nullptr;
988 
989   // If call isn't an intrinsic, check that it isn't within a function with the
990   // same name as the float version of this call, otherwise the result is an
991   // infinite loop.  For example, from MinGW-w64:
992   //
993   // float expf(float val) { return (float) exp((double) val); }
994   Function *CalleeFn = CI->getCalledFunction();
995   StringRef CalleeNm = CalleeFn->getName();
996   AttributeList CalleeAt = CalleeFn->getAttributes();
997   if (CalleeFn && !CalleeFn->isIntrinsic()) {
998     const Function *Fn = CI->getFunction();
999     StringRef FnName = Fn->getName();
1000     if (FnName.back() == 'f' &&
1001         FnName.size() == (CalleeNm.size() + 1) &&
1002         FnName.startswith(CalleeNm))
1003       return nullptr;
1004   }
1005 
1006   // Propagate the math semantics from the current function to the new function.
1007   IRBuilder<>::FastMathFlagGuard Guard(B);
1008   B.setFastMathFlags(CI->getFastMathFlags());
1009 
1010   // g((double) float) -> (double) gf(float)
1011   Value *R;
1012   if (CalleeFn->isIntrinsic()) {
1013     Module *M = CI->getModule();
1014     Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1015     Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1016     R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
1017   }
1018   else
1019     R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1020                  : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
1021 
1022   return B.CreateFPExt(R, B.getDoubleTy());
1023 }
1024 
1025 /// Shrink double -> float for unary functions.
1026 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1027                                     bool isPrecise = false) {
1028   return optimizeDoubleFP(CI, B, false, isPrecise);
1029 }
1030 
1031 /// Shrink double -> float for binary functions.
1032 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1033                                      bool isPrecise = false) {
1034   return optimizeDoubleFP(CI, B, true, isPrecise);
1035 }
1036 
1037 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1038 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1039   if (!CI->isFast())
1040     return nullptr;
1041 
1042   // Propagate fast-math flags from the existing call to new instructions.
1043   IRBuilder<>::FastMathFlagGuard Guard(B);
1044   B.setFastMathFlags(CI->getFastMathFlags());
1045 
1046   Value *Real, *Imag;
1047   if (CI->getNumArgOperands() == 1) {
1048     Value *Op = CI->getArgOperand(0);
1049     assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1050     Real = B.CreateExtractValue(Op, 0, "real");
1051     Imag = B.CreateExtractValue(Op, 1, "imag");
1052   } else {
1053     assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1054     Real = CI->getArgOperand(0);
1055     Imag = CI->getArgOperand(1);
1056   }
1057 
1058   Value *RealReal = B.CreateFMul(Real, Real);
1059   Value *ImagImag = B.CreateFMul(Imag, Imag);
1060 
1061   Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1062                                               CI->getType());
1063   return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1064 }
1065 
1066 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1067   Function *Callee = CI->getCalledFunction();
1068   Value *Ret = nullptr;
1069   StringRef Name = Callee->getName();
1070   if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1071     Ret = optimizeUnaryDoubleFP(CI, B, true);
1072 
1073   // cos(-x) -> cos(x)
1074   Value *Op1 = CI->getArgOperand(0);
1075   if (BinaryOperator::isFNeg(Op1)) {
1076     BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1077     return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1078   }
1079   return Ret;
1080 }
1081 
1082 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1083   // Multiplications calculated using Addition Chains.
1084   // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1085 
1086   assert(Exp != 0 && "Incorrect exponent 0 not handled");
1087 
1088   if (InnerChain[Exp])
1089     return InnerChain[Exp];
1090 
1091   static const unsigned AddChain[33][2] = {
1092       {0, 0}, // Unused.
1093       {0, 0}, // Unused (base case = pow1).
1094       {1, 1}, // Unused (pre-computed).
1095       {1, 2},  {2, 2},   {2, 3},  {3, 3},   {2, 5},  {4, 4},
1096       {1, 8},  {5, 5},   {1, 10}, {6, 6},   {4, 9},  {7, 7},
1097       {3, 12}, {8, 8},   {8, 9},  {2, 16},  {1, 18}, {10, 10},
1098       {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1099       {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1100   };
1101 
1102   InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1103                                  getPow(InnerChain, AddChain[Exp][1], B));
1104   return InnerChain[Exp];
1105 }
1106 
1107 /// Use square root in place of pow(x, +/-0.5).
1108 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1109   // TODO: There is some subset of 'fast' under which these transforms should
1110   // be allowed.
1111   if (!Pow->isFast())
1112     return nullptr;
1113 
1114   Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1115   Type *Ty = Pow->getType();
1116 
1117   const APFloat *ExpoF;
1118   if (!match(Expo, m_APFloat(ExpoF)) ||
1119       (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1120     return nullptr;
1121 
1122   // If errno is never set, then use the intrinsic for sqrt().
1123   if (Pow->hasFnAttr(Attribute::ReadNone)) {
1124     Function *SqrtFn = Intrinsic::getDeclaration(Pow->getModule(),
1125                                                  Intrinsic::sqrt, Ty);
1126     Sqrt = B.CreateCall(SqrtFn, Base);
1127   }
1128   // Otherwise, use the libcall for sqrt().
1129   else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
1130     // TODO: We also should check that the target can in fact lower the sqrt()
1131     // libcall. We currently have no way to ask this question, so we ask if
1132     // the target has a sqrt() libcall, which is not exactly the same.
1133     Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt), B,
1134                                 Pow->getCalledFunction()->getAttributes());
1135   else
1136     return nullptr;
1137 
1138   // If the exponent is negative, then get the reciprocal.
1139   if (ExpoF->isNegative())
1140     Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1141 
1142   return Sqrt;
1143 }
1144 
1145 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1146   Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1147   Function *Callee = Pow->getCalledFunction();
1148   AttributeList Attrs = Callee->getAttributes();
1149   StringRef Name = Callee->getName();
1150   Module *Module = Pow->getModule();
1151   Type *Ty = Pow->getType();
1152   Value *Shrunk = nullptr;
1153   bool Ignored;
1154 
1155   // Propagate the math semantics from the call to any created instructions.
1156   IRBuilder<>::FastMathFlagGuard Guard(B);
1157   B.setFastMathFlags(Pow->getFastMathFlags());
1158 
1159   // Shrink pow() to powf() if the arguments are single precision,
1160   // unless the result is expected to be double precision.
1161   if (UnsafeFPShrink &&
1162       Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1163     Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1164 
1165   // Evaluate special cases related to the base.
1166 
1167   // pow(1.0, x) -> 1.0
1168   if (match(Base, m_FPOne()))
1169     return Base;
1170 
1171   // pow(2.0, x) -> exp2(x)
1172   if (match(Base, m_SpecificFP(2.0))) {
1173     Value *Exp2 = Intrinsic::getDeclaration(Module, Intrinsic::exp2, Ty);
1174     return B.CreateCall(Exp2, Expo, "exp2");
1175   }
1176 
1177   // pow(10.0, x) -> exp10(x)
1178   if (ConstantFP *BaseC = dyn_cast<ConstantFP>(Base))
1179     // There's no exp10 intrinsic yet, but, maybe, some day there shall be one.
1180     if (BaseC->isExactlyValue(10.0) &&
1181         hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1182       return emitUnaryFloatFnCall(Expo, TLI->getName(LibFunc_exp10), B, Attrs);
1183 
1184   // pow(exp(x), y) -> exp(x * y)
1185   // pow(exp2(x), y) -> exp2(x * y)
1186   // We enable these only with fast-math. Besides rounding differences, the
1187   // transformation changes overflow and underflow behavior quite dramatically.
1188   // Example: x = 1000, y = 0.001.
1189   // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1190   auto *BaseFn = dyn_cast<CallInst>(Base);
1191   if (BaseFn && BaseFn->isFast() && Pow->isFast()) {
1192     LibFunc LibFn;
1193     Function *CalleeFn = BaseFn->getCalledFunction();
1194     if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
1195         (LibFn == LibFunc_exp || LibFn == LibFunc_exp2) && TLI->has(LibFn)) {
1196       IRBuilder<>::FastMathFlagGuard Guard(B);
1197       B.setFastMathFlags(Pow->getFastMathFlags());
1198 
1199       Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1200       return emitUnaryFloatFnCall(FMul, CalleeFn->getName(), B,
1201                                   CalleeFn->getAttributes());
1202     }
1203   }
1204 
1205   // Evaluate special cases related to the exponent.
1206 
1207   if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1208     return Sqrt;
1209 
1210   ConstantFP *ExpoC = dyn_cast<ConstantFP>(Expo);
1211   if (!ExpoC)
1212     return Shrunk;
1213 
1214   // pow(x, -1.0) -> 1.0 / x
1215   if (ExpoC->isExactlyValue(-1.0))
1216     return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1217 
1218   // pow(x, 0.0) -> 1.0
1219   if (ExpoC->getValueAPF().isZero())
1220     return ConstantFP::get(Ty, 1.0);
1221 
1222   // pow(x, 1.0) -> x
1223   if (ExpoC->isExactlyValue(1.0))
1224     return Base;
1225 
1226   // pow(x, 2.0) -> x * x
1227   if (ExpoC->isExactlyValue(2.0))
1228     return B.CreateFMul(Base, Base, "square");
1229 
1230   // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
1231   if (ExpoC->isExactlyValue(0.5) &&
1232       hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) {
1233     // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1234     // This is faster than calling pow(), and still handles -0.0 and
1235     // negative infinity correctly.
1236     // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1237     Value *PosInf = ConstantFP::getInfinity(Ty);
1238     Value *NegInf = ConstantFP::getInfinity(Ty, true);
1239 
1240     // TODO: As above, we should lower to the sqrt() intrinsic if the pow() is
1241     // an intrinsic, to match errno semantics.
1242     Value *Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt),
1243                                        B, Attrs);
1244     Function *FAbsFn = Intrinsic::getDeclaration(Module, Intrinsic::fabs, Ty);
1245     Value *FAbs = B.CreateCall(FAbsFn, Sqrt, "abs");
1246     Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1247     Sqrt = B.CreateSelect(FCmp, PosInf, FAbs);
1248     return Sqrt;
1249   }
1250 
1251   // pow(x, n) -> x * x * x * ....
1252   if (Pow->isFast()) {
1253     APFloat ExpoA = abs(ExpoC->getValueAPF());
1254     // We limit to a max of 7 fmul(s). Thus the maximum exponent is 32.
1255     // This transformation applies to integer exponents only.
1256     if (!ExpoA.isInteger() ||
1257         ExpoA.compare
1258             (APFloat(ExpoA.getSemantics(), 32.0)) == APFloat::cmpGreaterThan)
1259       return Shrunk;
1260 
1261     // We will memoize intermediate products of the Addition Chain.
1262     Value *InnerChain[33] = {nullptr};
1263     InnerChain[1] = Base;
1264     InnerChain[2] = B.CreateFMul(Base, Base, "square");
1265 
1266     // We cannot readily convert a non-double type (like float) to a double.
1267     // So we first convert it to something which could be converted to double.
1268     ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1269     Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
1270 
1271     // If the exponent is negative, then get the reciprocal.
1272     if (ExpoC->isNegative())
1273       FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
1274     return FMul;
1275   }
1276 
1277   return Shrunk;
1278 }
1279 
1280 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1281   Function *Callee = CI->getCalledFunction();
1282   Value *Ret = nullptr;
1283   StringRef Name = Callee->getName();
1284   if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1285     Ret = optimizeUnaryDoubleFP(CI, B, true);
1286 
1287   Value *Op = CI->getArgOperand(0);
1288   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1289   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1290   LibFunc LdExp = LibFunc_ldexpl;
1291   if (Op->getType()->isFloatTy())
1292     LdExp = LibFunc_ldexpf;
1293   else if (Op->getType()->isDoubleTy())
1294     LdExp = LibFunc_ldexp;
1295 
1296   if (TLI->has(LdExp)) {
1297     Value *LdExpArg = nullptr;
1298     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1299       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1300         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1301     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1302       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1303         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1304     }
1305 
1306     if (LdExpArg) {
1307       Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1308       if (!Op->getType()->isFloatTy())
1309         One = ConstantExpr::getFPExtend(One, Op->getType());
1310 
1311       Module *M = CI->getModule();
1312       Value *NewCallee =
1313           M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1314                                  Op->getType(), B.getInt32Ty());
1315       CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1316       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1317         CI->setCallingConv(F->getCallingConv());
1318 
1319       return CI;
1320     }
1321   }
1322   return Ret;
1323 }
1324 
1325 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1326   Function *Callee = CI->getCalledFunction();
1327   // If we can shrink the call to a float function rather than a double
1328   // function, do that first.
1329   StringRef Name = Callee->getName();
1330   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1331     if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1332       return Ret;
1333 
1334   IRBuilder<>::FastMathFlagGuard Guard(B);
1335   FastMathFlags FMF;
1336   if (CI->isFast()) {
1337     // If the call is 'fast', then anything we create here will also be 'fast'.
1338     FMF.setFast();
1339   } else {
1340     // At a minimum, no-nans-fp-math must be true.
1341     if (!CI->hasNoNaNs())
1342       return nullptr;
1343     // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1344     // "Ideally, fmax would be sensitive to the sign of zero, for example
1345     // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1346     // might be impractical."
1347     FMF.setNoSignedZeros();
1348     FMF.setNoNaNs();
1349   }
1350   B.setFastMathFlags(FMF);
1351 
1352   // We have a relaxed floating-point environment. We can ignore NaN-handling
1353   // and transform to a compare and select. We do not have to consider errno or
1354   // exceptions, because fmin/fmax do not have those.
1355   Value *Op0 = CI->getArgOperand(0);
1356   Value *Op1 = CI->getArgOperand(1);
1357   Value *Cmp = Callee->getName().startswith("fmin") ?
1358     B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1359   return B.CreateSelect(Cmp, Op0, Op1);
1360 }
1361 
1362 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1363   Function *Callee = CI->getCalledFunction();
1364   Value *Ret = nullptr;
1365   StringRef Name = Callee->getName();
1366   if (UnsafeFPShrink && hasFloatVersion(Name))
1367     Ret = optimizeUnaryDoubleFP(CI, B, true);
1368 
1369   if (!CI->isFast())
1370     return Ret;
1371   Value *Op1 = CI->getArgOperand(0);
1372   auto *OpC = dyn_cast<CallInst>(Op1);
1373 
1374   // The earlier call must also be 'fast' in order to do these transforms.
1375   if (!OpC || !OpC->isFast())
1376     return Ret;
1377 
1378   // log(pow(x,y)) -> y*log(x)
1379   // This is only applicable to log, log2, log10.
1380   if (Name != "log" && Name != "log2" && Name != "log10")
1381     return Ret;
1382 
1383   IRBuilder<>::FastMathFlagGuard Guard(B);
1384   FastMathFlags FMF;
1385   FMF.setFast();
1386   B.setFastMathFlags(FMF);
1387 
1388   LibFunc Func;
1389   Function *F = OpC->getCalledFunction();
1390   if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1391       Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1392     return B.CreateFMul(OpC->getArgOperand(1),
1393       emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1394                            Callee->getAttributes()), "mul");
1395 
1396   // log(exp2(y)) -> y*log(2)
1397   if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1398       TLI->has(Func) && Func == LibFunc_exp2)
1399     return B.CreateFMul(
1400         OpC->getArgOperand(0),
1401         emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1402                              Callee->getName(), B, Callee->getAttributes()),
1403         "logmul");
1404   return Ret;
1405 }
1406 
1407 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1408   Function *Callee = CI->getCalledFunction();
1409   Value *Ret = nullptr;
1410   // TODO: Once we have a way (other than checking for the existince of the
1411   // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1412   // condition below.
1413   if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1414                                   Callee->getIntrinsicID() == Intrinsic::sqrt))
1415     Ret = optimizeUnaryDoubleFP(CI, B, true);
1416 
1417   if (!CI->isFast())
1418     return Ret;
1419 
1420   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1421   if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
1422     return Ret;
1423 
1424   // We're looking for a repeated factor in a multiplication tree,
1425   // so we can do this fold: sqrt(x * x) -> fabs(x);
1426   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1427   Value *Op0 = I->getOperand(0);
1428   Value *Op1 = I->getOperand(1);
1429   Value *RepeatOp = nullptr;
1430   Value *OtherOp = nullptr;
1431   if (Op0 == Op1) {
1432     // Simple match: the operands of the multiply are identical.
1433     RepeatOp = Op0;
1434   } else {
1435     // Look for a more complicated pattern: one of the operands is itself
1436     // a multiply, so search for a common factor in that multiply.
1437     // Note: We don't bother looking any deeper than this first level or for
1438     // variations of this pattern because instcombine's visitFMUL and/or the
1439     // reassociation pass should give us this form.
1440     Value *OtherMul0, *OtherMul1;
1441     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1442       // Pattern: sqrt((x * y) * z)
1443       if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
1444         // Matched: sqrt((x * x) * z)
1445         RepeatOp = OtherMul0;
1446         OtherOp = Op1;
1447       }
1448     }
1449   }
1450   if (!RepeatOp)
1451     return Ret;
1452 
1453   // Fast math flags for any created instructions should match the sqrt
1454   // and multiply.
1455   IRBuilder<>::FastMathFlagGuard Guard(B);
1456   B.setFastMathFlags(I->getFastMathFlags());
1457 
1458   // If we found a repeated factor, hoist it out of the square root and
1459   // replace it with the fabs of that factor.
1460   Module *M = Callee->getParent();
1461   Type *ArgType = I->getType();
1462   Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1463   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1464   if (OtherOp) {
1465     // If we found a non-repeated factor, we still need to get its square
1466     // root. We then multiply that by the value that was simplified out
1467     // of the square root calculation.
1468     Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1469     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1470     return B.CreateFMul(FabsCall, SqrtCall);
1471   }
1472   return FabsCall;
1473 }
1474 
1475 // TODO: Generalize to handle any trig function and its inverse.
1476 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1477   Function *Callee = CI->getCalledFunction();
1478   Value *Ret = nullptr;
1479   StringRef Name = Callee->getName();
1480   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1481     Ret = optimizeUnaryDoubleFP(CI, B, true);
1482 
1483   Value *Op1 = CI->getArgOperand(0);
1484   auto *OpC = dyn_cast<CallInst>(Op1);
1485   if (!OpC)
1486     return Ret;
1487 
1488   // Both calls must be 'fast' in order to remove them.
1489   if (!CI->isFast() || !OpC->isFast())
1490     return Ret;
1491 
1492   // tan(atan(x)) -> x
1493   // tanf(atanf(x)) -> x
1494   // tanl(atanl(x)) -> x
1495   LibFunc Func;
1496   Function *F = OpC->getCalledFunction();
1497   if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1498       ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1499        (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1500        (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1501     Ret = OpC->getArgOperand(0);
1502   return Ret;
1503 }
1504 
1505 static bool isTrigLibCall(CallInst *CI) {
1506   // We can only hope to do anything useful if we can ignore things like errno
1507   // and floating-point exceptions.
1508   // We already checked the prototype.
1509   return CI->hasFnAttr(Attribute::NoUnwind) &&
1510          CI->hasFnAttr(Attribute::ReadNone);
1511 }
1512 
1513 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1514                              bool UseFloat, Value *&Sin, Value *&Cos,
1515                              Value *&SinCos) {
1516   Type *ArgTy = Arg->getType();
1517   Type *ResTy;
1518   StringRef Name;
1519 
1520   Triple T(OrigCallee->getParent()->getTargetTriple());
1521   if (UseFloat) {
1522     Name = "__sincospif_stret";
1523 
1524     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1525     // x86_64 can't use {float, float} since that would be returned in both
1526     // xmm0 and xmm1, which isn't what a real struct would do.
1527     ResTy = T.getArch() == Triple::x86_64
1528                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1529                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1530   } else {
1531     Name = "__sincospi_stret";
1532     ResTy = StructType::get(ArgTy, ArgTy);
1533   }
1534 
1535   Module *M = OrigCallee->getParent();
1536   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1537                                          ResTy, ArgTy);
1538 
1539   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1540     // If the argument is an instruction, it must dominate all uses so put our
1541     // sincos call there.
1542     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1543   } else {
1544     // Otherwise (e.g. for a constant) the beginning of the function is as
1545     // good a place as any.
1546     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1547     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1548   }
1549 
1550   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1551 
1552   if (SinCos->getType()->isStructTy()) {
1553     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1554     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1555   } else {
1556     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1557                                  "sinpi");
1558     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1559                                  "cospi");
1560   }
1561 }
1562 
1563 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1564   // Make sure the prototype is as expected, otherwise the rest of the
1565   // function is probably invalid and likely to abort.
1566   if (!isTrigLibCall(CI))
1567     return nullptr;
1568 
1569   Value *Arg = CI->getArgOperand(0);
1570   SmallVector<CallInst *, 1> SinCalls;
1571   SmallVector<CallInst *, 1> CosCalls;
1572   SmallVector<CallInst *, 1> SinCosCalls;
1573 
1574   bool IsFloat = Arg->getType()->isFloatTy();
1575 
1576   // Look for all compatible sinpi, cospi and sincospi calls with the same
1577   // argument. If there are enough (in some sense) we can make the
1578   // substitution.
1579   Function *F = CI->getFunction();
1580   for (User *U : Arg->users())
1581     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1582 
1583   // It's only worthwhile if both sinpi and cospi are actually used.
1584   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1585     return nullptr;
1586 
1587   Value *Sin, *Cos, *SinCos;
1588   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1589 
1590   auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1591                                  Value *Res) {
1592     for (CallInst *C : Calls)
1593       replaceAllUsesWith(C, Res);
1594   };
1595 
1596   replaceTrigInsts(SinCalls, Sin);
1597   replaceTrigInsts(CosCalls, Cos);
1598   replaceTrigInsts(SinCosCalls, SinCos);
1599 
1600   return nullptr;
1601 }
1602 
1603 void LibCallSimplifier::classifyArgUse(
1604     Value *Val, Function *F, bool IsFloat,
1605     SmallVectorImpl<CallInst *> &SinCalls,
1606     SmallVectorImpl<CallInst *> &CosCalls,
1607     SmallVectorImpl<CallInst *> &SinCosCalls) {
1608   CallInst *CI = dyn_cast<CallInst>(Val);
1609 
1610   if (!CI)
1611     return;
1612 
1613   // Don't consider calls in other functions.
1614   if (CI->getFunction() != F)
1615     return;
1616 
1617   Function *Callee = CI->getCalledFunction();
1618   LibFunc Func;
1619   if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1620       !isTrigLibCall(CI))
1621     return;
1622 
1623   if (IsFloat) {
1624     if (Func == LibFunc_sinpif)
1625       SinCalls.push_back(CI);
1626     else if (Func == LibFunc_cospif)
1627       CosCalls.push_back(CI);
1628     else if (Func == LibFunc_sincospif_stret)
1629       SinCosCalls.push_back(CI);
1630   } else {
1631     if (Func == LibFunc_sinpi)
1632       SinCalls.push_back(CI);
1633     else if (Func == LibFunc_cospi)
1634       CosCalls.push_back(CI);
1635     else if (Func == LibFunc_sincospi_stret)
1636       SinCosCalls.push_back(CI);
1637   }
1638 }
1639 
1640 //===----------------------------------------------------------------------===//
1641 // Integer Library Call Optimizations
1642 //===----------------------------------------------------------------------===//
1643 
1644 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1645   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1646   Value *Op = CI->getArgOperand(0);
1647   Type *ArgType = Op->getType();
1648   Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1649                                        Intrinsic::cttz, ArgType);
1650   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1651   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1652   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1653 
1654   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1655   return B.CreateSelect(Cond, V, B.getInt32(0));
1656 }
1657 
1658 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1659   // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1660   Value *Op = CI->getArgOperand(0);
1661   Type *ArgType = Op->getType();
1662   Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1663                                        Intrinsic::ctlz, ArgType);
1664   Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1665   V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1666                   V);
1667   return B.CreateIntCast(V, CI->getType(), false);
1668 }
1669 
1670 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1671   // abs(x) -> x <s 0 ? -x : x
1672   // The negation has 'nsw' because abs of INT_MIN is undefined.
1673   Value *X = CI->getArgOperand(0);
1674   Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1675   Value *NegX = B.CreateNSWNeg(X, "neg");
1676   return B.CreateSelect(IsNeg, NegX, X);
1677 }
1678 
1679 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1680   // isdigit(c) -> (c-'0') <u 10
1681   Value *Op = CI->getArgOperand(0);
1682   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1683   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1684   return B.CreateZExt(Op, CI->getType());
1685 }
1686 
1687 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1688   // isascii(c) -> c <u 128
1689   Value *Op = CI->getArgOperand(0);
1690   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1691   return B.CreateZExt(Op, CI->getType());
1692 }
1693 
1694 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1695   // toascii(c) -> c & 0x7f
1696   return B.CreateAnd(CI->getArgOperand(0),
1697                      ConstantInt::get(CI->getType(), 0x7F));
1698 }
1699 
1700 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1701   StringRef Str;
1702   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1703     return nullptr;
1704 
1705   return convertStrToNumber(CI, Str, 10);
1706 }
1707 
1708 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1709   StringRef Str;
1710   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1711     return nullptr;
1712 
1713   if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1714     return nullptr;
1715 
1716   if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1717     return convertStrToNumber(CI, Str, CInt->getSExtValue());
1718   }
1719 
1720   return nullptr;
1721 }
1722 
1723 //===----------------------------------------------------------------------===//
1724 // Formatting and IO Library Call Optimizations
1725 //===----------------------------------------------------------------------===//
1726 
1727 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1728 
1729 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1730                                                  int StreamArg) {
1731   Function *Callee = CI->getCalledFunction();
1732   // Error reporting calls should be cold, mark them as such.
1733   // This applies even to non-builtin calls: it is only a hint and applies to
1734   // functions that the frontend might not understand as builtins.
1735 
1736   // This heuristic was suggested in:
1737   // Improving Static Branch Prediction in a Compiler
1738   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1739   // Proceedings of PACT'98, Oct. 1998, IEEE
1740   if (!CI->hasFnAttr(Attribute::Cold) &&
1741       isReportingError(Callee, CI, StreamArg)) {
1742     CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
1743   }
1744 
1745   return nullptr;
1746 }
1747 
1748 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1749   if (!Callee || !Callee->isDeclaration())
1750     return false;
1751 
1752   if (StreamArg < 0)
1753     return true;
1754 
1755   // These functions might be considered cold, but only if their stream
1756   // argument is stderr.
1757 
1758   if (StreamArg >= (int)CI->getNumArgOperands())
1759     return false;
1760   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1761   if (!LI)
1762     return false;
1763   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1764   if (!GV || !GV->isDeclaration())
1765     return false;
1766   return GV->getName() == "stderr";
1767 }
1768 
1769 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1770   // Check for a fixed format string.
1771   StringRef FormatStr;
1772   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1773     return nullptr;
1774 
1775   // Empty format string -> noop.
1776   if (FormatStr.empty()) // Tolerate printf's declared void.
1777     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1778 
1779   // Do not do any of the following transformations if the printf return value
1780   // is used, in general the printf return value is not compatible with either
1781   // putchar() or puts().
1782   if (!CI->use_empty())
1783     return nullptr;
1784 
1785   // printf("x") -> putchar('x'), even for "%" and "%%".
1786   if (FormatStr.size() == 1 || FormatStr == "%%")
1787     return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1788 
1789   // printf("%s", "a") --> putchar('a')
1790   if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1791     StringRef ChrStr;
1792     if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1793       return nullptr;
1794     if (ChrStr.size() != 1)
1795       return nullptr;
1796     return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1797   }
1798 
1799   // printf("foo\n") --> puts("foo")
1800   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1801       FormatStr.find('%') == StringRef::npos) { // No format characters.
1802     // Create a string literal with no \n on it.  We expect the constant merge
1803     // pass to be run after this pass, to merge duplicate strings.
1804     FormatStr = FormatStr.drop_back();
1805     Value *GV = B.CreateGlobalString(FormatStr, "str");
1806     return emitPutS(GV, B, TLI);
1807   }
1808 
1809   // Optimize specific format strings.
1810   // printf("%c", chr) --> putchar(chr)
1811   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1812       CI->getArgOperand(1)->getType()->isIntegerTy())
1813     return emitPutChar(CI->getArgOperand(1), B, TLI);
1814 
1815   // printf("%s\n", str) --> puts(str)
1816   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1817       CI->getArgOperand(1)->getType()->isPointerTy())
1818     return emitPutS(CI->getArgOperand(1), B, TLI);
1819   return nullptr;
1820 }
1821 
1822 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1823 
1824   Function *Callee = CI->getCalledFunction();
1825   FunctionType *FT = Callee->getFunctionType();
1826   if (Value *V = optimizePrintFString(CI, B)) {
1827     return V;
1828   }
1829 
1830   // printf(format, ...) -> iprintf(format, ...) if no floating point
1831   // arguments.
1832   if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
1833     Module *M = B.GetInsertBlock()->getParent()->getParent();
1834     Constant *IPrintFFn =
1835         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1836     CallInst *New = cast<CallInst>(CI->clone());
1837     New->setCalledFunction(IPrintFFn);
1838     B.Insert(New);
1839     return New;
1840   }
1841   return nullptr;
1842 }
1843 
1844 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1845   // Check for a fixed format string.
1846   StringRef FormatStr;
1847   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1848     return nullptr;
1849 
1850   // If we just have a format string (nothing else crazy) transform it.
1851   if (CI->getNumArgOperands() == 2) {
1852     // Make sure there's no % in the constant array.  We could try to handle
1853     // %% -> % in the future if we cared.
1854     if (FormatStr.find('%') != StringRef::npos)
1855       return nullptr; // we found a format specifier, bail out.
1856 
1857     // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1858     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
1859                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1860                                     FormatStr.size() + 1)); // Copy the null byte.
1861     return ConstantInt::get(CI->getType(), FormatStr.size());
1862   }
1863 
1864   // The remaining optimizations require the format string to be "%s" or "%c"
1865   // and have an extra operand.
1866   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1867       CI->getNumArgOperands() < 3)
1868     return nullptr;
1869 
1870   // Decode the second character of the format string.
1871   if (FormatStr[1] == 'c') {
1872     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1873     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1874       return nullptr;
1875     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1876     Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1877     B.CreateStore(V, Ptr);
1878     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1879     B.CreateStore(B.getInt8(0), Ptr);
1880 
1881     return ConstantInt::get(CI->getType(), 1);
1882   }
1883 
1884   if (FormatStr[1] == 's') {
1885     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1886     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1887       return nullptr;
1888 
1889     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1890     if (!Len)
1891       return nullptr;
1892     Value *IncLen =
1893         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1894     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
1895 
1896     // The sprintf result is the unincremented number of bytes in the string.
1897     return B.CreateIntCast(Len, CI->getType(), false);
1898   }
1899   return nullptr;
1900 }
1901 
1902 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1903   Function *Callee = CI->getCalledFunction();
1904   FunctionType *FT = Callee->getFunctionType();
1905   if (Value *V = optimizeSPrintFString(CI, B)) {
1906     return V;
1907   }
1908 
1909   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1910   // point arguments.
1911   if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
1912     Module *M = B.GetInsertBlock()->getParent()->getParent();
1913     Constant *SIPrintFFn =
1914         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1915     CallInst *New = cast<CallInst>(CI->clone());
1916     New->setCalledFunction(SIPrintFFn);
1917     B.Insert(New);
1918     return New;
1919   }
1920   return nullptr;
1921 }
1922 
1923 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
1924   // Check for a fixed format string.
1925   StringRef FormatStr;
1926   if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
1927     return nullptr;
1928 
1929   // Check for size
1930   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1931   if (!Size)
1932     return nullptr;
1933 
1934   uint64_t N = Size->getZExtValue();
1935 
1936   // If we just have a format string (nothing else crazy) transform it.
1937   if (CI->getNumArgOperands() == 3) {
1938     // Make sure there's no % in the constant array.  We could try to handle
1939     // %% -> % in the future if we cared.
1940     if (FormatStr.find('%') != StringRef::npos)
1941       return nullptr; // we found a format specifier, bail out.
1942 
1943     if (N == 0)
1944       return ConstantInt::get(CI->getType(), FormatStr.size());
1945     else if (N < FormatStr.size() + 1)
1946       return nullptr;
1947 
1948     // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
1949     // strlen(fmt)+1)
1950     B.CreateMemCpy(
1951         CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
1952         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1953                          FormatStr.size() + 1)); // Copy the null byte.
1954     return ConstantInt::get(CI->getType(), FormatStr.size());
1955   }
1956 
1957   // The remaining optimizations require the format string to be "%s" or "%c"
1958   // and have an extra operand.
1959   if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
1960       CI->getNumArgOperands() == 4) {
1961 
1962     // Decode the second character of the format string.
1963     if (FormatStr[1] == 'c') {
1964       if (N == 0)
1965         return ConstantInt::get(CI->getType(), 1);
1966       else if (N == 1)
1967         return nullptr;
1968 
1969       // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1970       if (!CI->getArgOperand(3)->getType()->isIntegerTy())
1971         return nullptr;
1972       Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
1973       Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1974       B.CreateStore(V, Ptr);
1975       Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1976       B.CreateStore(B.getInt8(0), Ptr);
1977 
1978       return ConstantInt::get(CI->getType(), 1);
1979     }
1980 
1981     if (FormatStr[1] == 's') {
1982       // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
1983       StringRef Str;
1984       if (!getConstantStringInfo(CI->getArgOperand(3), Str))
1985         return nullptr;
1986 
1987       if (N == 0)
1988         return ConstantInt::get(CI->getType(), Str.size());
1989       else if (N < Str.size() + 1)
1990         return nullptr;
1991 
1992       B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
1993                      ConstantInt::get(CI->getType(), Str.size() + 1));
1994 
1995       // The snprintf result is the unincremented number of bytes in the string.
1996       return ConstantInt::get(CI->getType(), Str.size());
1997     }
1998   }
1999   return nullptr;
2000 }
2001 
2002 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2003   if (Value *V = optimizeSnPrintFString(CI, B)) {
2004     return V;
2005   }
2006 
2007   return nullptr;
2008 }
2009 
2010 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2011   optimizeErrorReporting(CI, B, 0);
2012 
2013   // All the optimizations depend on the format string.
2014   StringRef FormatStr;
2015   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2016     return nullptr;
2017 
2018   // Do not do any of the following transformations if the fprintf return
2019   // value is used, in general the fprintf return value is not compatible
2020   // with fwrite(), fputc() or fputs().
2021   if (!CI->use_empty())
2022     return nullptr;
2023 
2024   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2025   if (CI->getNumArgOperands() == 2) {
2026     // Could handle %% -> % if we cared.
2027     if (FormatStr.find('%') != StringRef::npos)
2028       return nullptr; // We found a format specifier.
2029 
2030     return emitFWrite(
2031         CI->getArgOperand(1),
2032         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2033         CI->getArgOperand(0), B, DL, TLI);
2034   }
2035 
2036   // The remaining optimizations require the format string to be "%s" or "%c"
2037   // and have an extra operand.
2038   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2039       CI->getNumArgOperands() < 3)
2040     return nullptr;
2041 
2042   // Decode the second character of the format string.
2043   if (FormatStr[1] == 'c') {
2044     // fprintf(F, "%c", chr) --> fputc(chr, F)
2045     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2046       return nullptr;
2047     return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2048   }
2049 
2050   if (FormatStr[1] == 's') {
2051     // fprintf(F, "%s", str) --> fputs(str, F)
2052     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2053       return nullptr;
2054     return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2055   }
2056   return nullptr;
2057 }
2058 
2059 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2060   Function *Callee = CI->getCalledFunction();
2061   FunctionType *FT = Callee->getFunctionType();
2062   if (Value *V = optimizeFPrintFString(CI, B)) {
2063     return V;
2064   }
2065 
2066   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2067   // floating point arguments.
2068   if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
2069     Module *M = B.GetInsertBlock()->getParent()->getParent();
2070     Constant *FIPrintFFn =
2071         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2072     CallInst *New = cast<CallInst>(CI->clone());
2073     New->setCalledFunction(FIPrintFFn);
2074     B.Insert(New);
2075     return New;
2076   }
2077   return nullptr;
2078 }
2079 
2080 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2081   optimizeErrorReporting(CI, B, 3);
2082 
2083   // Get the element size and count.
2084   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2085   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2086   if (SizeC && CountC) {
2087     uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2088 
2089     // If this is writing zero records, remove the call (it's a noop).
2090     if (Bytes == 0)
2091       return ConstantInt::get(CI->getType(), 0);
2092 
2093     // If this is writing one byte, turn it into fputc.
2094     // This optimisation is only valid, if the return value is unused.
2095     if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2096       Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2097       Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2098       return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2099     }
2100   }
2101 
2102   if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2103     return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2104                               CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2105                               TLI);
2106 
2107   return nullptr;
2108 }
2109 
2110 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2111   optimizeErrorReporting(CI, B, 1);
2112 
2113   // Don't rewrite fputs to fwrite when optimising for size because fwrite
2114   // requires more arguments and thus extra MOVs are required.
2115   if (CI->getFunction()->optForSize())
2116     return nullptr;
2117 
2118   // Check if has any use
2119   if (!CI->use_empty()) {
2120     if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2121       return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2122                                TLI);
2123     else
2124       // We can't optimize if return value is used.
2125       return nullptr;
2126   }
2127 
2128   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2129   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2130   if (!Len)
2131     return nullptr;
2132 
2133   // Known to have no uses (see above).
2134   return emitFWrite(
2135       CI->getArgOperand(0),
2136       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2137       CI->getArgOperand(1), B, DL, TLI);
2138 }
2139 
2140 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2141   optimizeErrorReporting(CI, B, 1);
2142 
2143   if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2144     return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2145                              TLI);
2146 
2147   return nullptr;
2148 }
2149 
2150 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2151   if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2152     return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2153 
2154   return nullptr;
2155 }
2156 
2157 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2158   if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2159     return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2160                              CI->getArgOperand(2), B, TLI);
2161 
2162   return nullptr;
2163 }
2164 
2165 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2166   if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2167     return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2168                              CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2169                              TLI);
2170 
2171   return nullptr;
2172 }
2173 
2174 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2175   // Check for a constant string.
2176   StringRef Str;
2177   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2178     return nullptr;
2179 
2180   if (Str.empty() && CI->use_empty()) {
2181     // puts("") -> putchar('\n')
2182     Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2183     if (CI->use_empty() || !Res)
2184       return Res;
2185     return B.CreateIntCast(Res, CI->getType(), true);
2186   }
2187 
2188   return nullptr;
2189 }
2190 
2191 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2192   LibFunc Func;
2193   SmallString<20> FloatFuncName = FuncName;
2194   FloatFuncName += 'f';
2195   if (TLI->getLibFunc(FloatFuncName, Func))
2196     return TLI->has(Func);
2197   return false;
2198 }
2199 
2200 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2201                                                       IRBuilder<> &Builder) {
2202   LibFunc Func;
2203   Function *Callee = CI->getCalledFunction();
2204   // Check for string/memory library functions.
2205   if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2206     // Make sure we never change the calling convention.
2207     assert((ignoreCallingConv(Func) ||
2208             isCallingConvCCompatible(CI)) &&
2209       "Optimizing string/memory libcall would change the calling convention");
2210     switch (Func) {
2211     case LibFunc_strcat:
2212       return optimizeStrCat(CI, Builder);
2213     case LibFunc_strncat:
2214       return optimizeStrNCat(CI, Builder);
2215     case LibFunc_strchr:
2216       return optimizeStrChr(CI, Builder);
2217     case LibFunc_strrchr:
2218       return optimizeStrRChr(CI, Builder);
2219     case LibFunc_strcmp:
2220       return optimizeStrCmp(CI, Builder);
2221     case LibFunc_strncmp:
2222       return optimizeStrNCmp(CI, Builder);
2223     case LibFunc_strcpy:
2224       return optimizeStrCpy(CI, Builder);
2225     case LibFunc_stpcpy:
2226       return optimizeStpCpy(CI, Builder);
2227     case LibFunc_strncpy:
2228       return optimizeStrNCpy(CI, Builder);
2229     case LibFunc_strlen:
2230       return optimizeStrLen(CI, Builder);
2231     case LibFunc_strpbrk:
2232       return optimizeStrPBrk(CI, Builder);
2233     case LibFunc_strtol:
2234     case LibFunc_strtod:
2235     case LibFunc_strtof:
2236     case LibFunc_strtoul:
2237     case LibFunc_strtoll:
2238     case LibFunc_strtold:
2239     case LibFunc_strtoull:
2240       return optimizeStrTo(CI, Builder);
2241     case LibFunc_strspn:
2242       return optimizeStrSpn(CI, Builder);
2243     case LibFunc_strcspn:
2244       return optimizeStrCSpn(CI, Builder);
2245     case LibFunc_strstr:
2246       return optimizeStrStr(CI, Builder);
2247     case LibFunc_memchr:
2248       return optimizeMemChr(CI, Builder);
2249     case LibFunc_memcmp:
2250       return optimizeMemCmp(CI, Builder);
2251     case LibFunc_memcpy:
2252       return optimizeMemCpy(CI, Builder);
2253     case LibFunc_memmove:
2254       return optimizeMemMove(CI, Builder);
2255     case LibFunc_memset:
2256       return optimizeMemSet(CI, Builder);
2257     case LibFunc_realloc:
2258       return optimizeRealloc(CI, Builder);
2259     case LibFunc_wcslen:
2260       return optimizeWcslen(CI, Builder);
2261     default:
2262       break;
2263     }
2264   }
2265   return nullptr;
2266 }
2267 
2268 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2269                                                        LibFunc Func,
2270                                                        IRBuilder<> &Builder) {
2271   // Don't optimize calls that require strict floating point semantics.
2272   if (CI->isStrictFP())
2273     return nullptr;
2274 
2275   switch (Func) {
2276   case LibFunc_cosf:
2277   case LibFunc_cos:
2278   case LibFunc_cosl:
2279     return optimizeCos(CI, Builder);
2280   case LibFunc_sinpif:
2281   case LibFunc_sinpi:
2282   case LibFunc_cospif:
2283   case LibFunc_cospi:
2284     return optimizeSinCosPi(CI, Builder);
2285   case LibFunc_powf:
2286   case LibFunc_pow:
2287   case LibFunc_powl:
2288     return optimizePow(CI, Builder);
2289   case LibFunc_exp2l:
2290   case LibFunc_exp2:
2291   case LibFunc_exp2f:
2292     return optimizeExp2(CI, Builder);
2293   case LibFunc_fabsf:
2294   case LibFunc_fabs:
2295   case LibFunc_fabsl:
2296     return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2297   case LibFunc_sqrtf:
2298   case LibFunc_sqrt:
2299   case LibFunc_sqrtl:
2300     return optimizeSqrt(CI, Builder);
2301   case LibFunc_log:
2302   case LibFunc_log10:
2303   case LibFunc_log1p:
2304   case LibFunc_log2:
2305   case LibFunc_logb:
2306     return optimizeLog(CI, Builder);
2307   case LibFunc_tan:
2308   case LibFunc_tanf:
2309   case LibFunc_tanl:
2310     return optimizeTan(CI, Builder);
2311   case LibFunc_ceil:
2312     return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2313   case LibFunc_floor:
2314     return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2315   case LibFunc_round:
2316     return replaceUnaryCall(CI, Builder, Intrinsic::round);
2317   case LibFunc_nearbyint:
2318     return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2319   case LibFunc_rint:
2320     return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2321   case LibFunc_trunc:
2322     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2323   case LibFunc_acos:
2324   case LibFunc_acosh:
2325   case LibFunc_asin:
2326   case LibFunc_asinh:
2327   case LibFunc_atan:
2328   case LibFunc_atanh:
2329   case LibFunc_cbrt:
2330   case LibFunc_cosh:
2331   case LibFunc_exp:
2332   case LibFunc_exp10:
2333   case LibFunc_expm1:
2334   case LibFunc_sin:
2335   case LibFunc_sinh:
2336   case LibFunc_tanh:
2337     if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2338       return optimizeUnaryDoubleFP(CI, Builder, true);
2339     return nullptr;
2340   case LibFunc_copysign:
2341     if (hasFloatVersion(CI->getCalledFunction()->getName()))
2342       return optimizeBinaryDoubleFP(CI, Builder);
2343     return nullptr;
2344   case LibFunc_fminf:
2345   case LibFunc_fmin:
2346   case LibFunc_fminl:
2347   case LibFunc_fmaxf:
2348   case LibFunc_fmax:
2349   case LibFunc_fmaxl:
2350     return optimizeFMinFMax(CI, Builder);
2351   case LibFunc_cabs:
2352   case LibFunc_cabsf:
2353   case LibFunc_cabsl:
2354     return optimizeCAbs(CI, Builder);
2355   default:
2356     return nullptr;
2357   }
2358 }
2359 
2360 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2361   // TODO: Split out the code below that operates on FP calls so that
2362   //       we can all non-FP calls with the StrictFP attribute to be
2363   //       optimized.
2364   if (CI->isNoBuiltin())
2365     return nullptr;
2366 
2367   LibFunc Func;
2368   Function *Callee = CI->getCalledFunction();
2369 
2370   SmallVector<OperandBundleDef, 2> OpBundles;
2371   CI->getOperandBundlesAsDefs(OpBundles);
2372   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2373   bool isCallingConvC = isCallingConvCCompatible(CI);
2374 
2375   // Command-line parameter overrides instruction attribute.
2376   // This can't be moved to optimizeFloatingPointLibCall() because it may be
2377   // used by the intrinsic optimizations.
2378   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2379     UnsafeFPShrink = EnableUnsafeFPShrink;
2380   else if (isa<FPMathOperator>(CI) && CI->isFast())
2381     UnsafeFPShrink = true;
2382 
2383   // First, check for intrinsics.
2384   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2385     if (!isCallingConvC)
2386       return nullptr;
2387     // The FP intrinsics have corresponding constrained versions so we don't
2388     // need to check for the StrictFP attribute here.
2389     switch (II->getIntrinsicID()) {
2390     case Intrinsic::pow:
2391       return optimizePow(CI, Builder);
2392     case Intrinsic::exp2:
2393       return optimizeExp2(CI, Builder);
2394     case Intrinsic::log:
2395       return optimizeLog(CI, Builder);
2396     case Intrinsic::sqrt:
2397       return optimizeSqrt(CI, Builder);
2398     // TODO: Use foldMallocMemset() with memset intrinsic.
2399     default:
2400       return nullptr;
2401     }
2402   }
2403 
2404   // Also try to simplify calls to fortified library functions.
2405   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2406     // Try to further simplify the result.
2407     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2408     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2409       // Use an IR Builder from SimplifiedCI if available instead of CI
2410       // to guarantee we reach all uses we might replace later on.
2411       IRBuilder<> TmpBuilder(SimplifiedCI);
2412       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2413         // If we were able to further simplify, remove the now redundant call.
2414         SimplifiedCI->replaceAllUsesWith(V);
2415         SimplifiedCI->eraseFromParent();
2416         return V;
2417       }
2418     }
2419     return SimplifiedFortifiedCI;
2420   }
2421 
2422   // Then check for known library functions.
2423   if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2424     // We never change the calling convention.
2425     if (!ignoreCallingConv(Func) && !isCallingConvC)
2426       return nullptr;
2427     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2428       return V;
2429     if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2430       return V;
2431     switch (Func) {
2432     case LibFunc_ffs:
2433     case LibFunc_ffsl:
2434     case LibFunc_ffsll:
2435       return optimizeFFS(CI, Builder);
2436     case LibFunc_fls:
2437     case LibFunc_flsl:
2438     case LibFunc_flsll:
2439       return optimizeFls(CI, Builder);
2440     case LibFunc_abs:
2441     case LibFunc_labs:
2442     case LibFunc_llabs:
2443       return optimizeAbs(CI, Builder);
2444     case LibFunc_isdigit:
2445       return optimizeIsDigit(CI, Builder);
2446     case LibFunc_isascii:
2447       return optimizeIsAscii(CI, Builder);
2448     case LibFunc_toascii:
2449       return optimizeToAscii(CI, Builder);
2450     case LibFunc_atoi:
2451     case LibFunc_atol:
2452     case LibFunc_atoll:
2453       return optimizeAtoi(CI, Builder);
2454     case LibFunc_strtol:
2455     case LibFunc_strtoll:
2456       return optimizeStrtol(CI, Builder);
2457     case LibFunc_printf:
2458       return optimizePrintF(CI, Builder);
2459     case LibFunc_sprintf:
2460       return optimizeSPrintF(CI, Builder);
2461     case LibFunc_snprintf:
2462       return optimizeSnPrintF(CI, Builder);
2463     case LibFunc_fprintf:
2464       return optimizeFPrintF(CI, Builder);
2465     case LibFunc_fwrite:
2466       return optimizeFWrite(CI, Builder);
2467     case LibFunc_fread:
2468       return optimizeFRead(CI, Builder);
2469     case LibFunc_fputs:
2470       return optimizeFPuts(CI, Builder);
2471     case LibFunc_fgets:
2472       return optimizeFGets(CI, Builder);
2473     case LibFunc_fputc:
2474       return optimizeFPutc(CI, Builder);
2475     case LibFunc_fgetc:
2476       return optimizeFGetc(CI, Builder);
2477     case LibFunc_puts:
2478       return optimizePuts(CI, Builder);
2479     case LibFunc_perror:
2480       return optimizeErrorReporting(CI, Builder);
2481     case LibFunc_vfprintf:
2482     case LibFunc_fiprintf:
2483       return optimizeErrorReporting(CI, Builder, 0);
2484     default:
2485       return nullptr;
2486     }
2487   }
2488   return nullptr;
2489 }
2490 
2491 LibCallSimplifier::LibCallSimplifier(
2492     const DataLayout &DL, const TargetLibraryInfo *TLI,
2493     OptimizationRemarkEmitter &ORE,
2494     function_ref<void(Instruction *, Value *)> Replacer)
2495     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2496       UnsafeFPShrink(false), Replacer(Replacer) {}
2497 
2498 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2499   // Indirect through the replacer used in this instance.
2500   Replacer(I, With);
2501 }
2502 
2503 // TODO:
2504 //   Additional cases that we need to add to this file:
2505 //
2506 // cbrt:
2507 //   * cbrt(expN(X))  -> expN(x/3)
2508 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2509 //   * cbrt(cbrt(x))  -> pow(x,1/9)
2510 //
2511 // exp, expf, expl:
2512 //   * exp(log(x))  -> x
2513 //
2514 // log, logf, logl:
2515 //   * log(exp(x))   -> x
2516 //   * log(exp(y))   -> y*log(e)
2517 //   * log(exp10(y)) -> y*log(10)
2518 //   * log(sqrt(x))  -> 0.5*log(x)
2519 //
2520 // pow, powf, powl:
2521 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2522 //   * pow(pow(x,y),z)-> pow(x,y*z)
2523 //
2524 // signbit:
2525 //   * signbit(cnst) -> cnst'
2526 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2527 //
2528 // sqrt, sqrtf, sqrtl:
2529 //   * sqrt(expN(x))  -> expN(x*0.5)
2530 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2531 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2532 //
2533 
2534 //===----------------------------------------------------------------------===//
2535 // Fortified Library Call Optimizations
2536 //===----------------------------------------------------------------------===//
2537 
2538 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2539                                                          unsigned ObjSizeOp,
2540                                                          unsigned SizeOp,
2541                                                          bool isString) {
2542   if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2543     return true;
2544   if (ConstantInt *ObjSizeCI =
2545           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2546     if (ObjSizeCI->isMinusOne())
2547       return true;
2548     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2549     if (OnlyLowerUnknownSize)
2550       return false;
2551     if (isString) {
2552       uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2553       // If the length is 0 we don't know how long it is and so we can't
2554       // remove the check.
2555       if (Len == 0)
2556         return false;
2557       return ObjSizeCI->getZExtValue() >= Len;
2558     }
2559     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2560       return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2561   }
2562   return false;
2563 }
2564 
2565 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2566                                                      IRBuilder<> &B) {
2567   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2568     B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2569                    CI->getArgOperand(2));
2570     return CI->getArgOperand(0);
2571   }
2572   return nullptr;
2573 }
2574 
2575 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2576                                                       IRBuilder<> &B) {
2577   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2578     B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2579                     CI->getArgOperand(2));
2580     return CI->getArgOperand(0);
2581   }
2582   return nullptr;
2583 }
2584 
2585 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2586                                                      IRBuilder<> &B) {
2587   // TODO: Try foldMallocMemset() here.
2588 
2589   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2590     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2591     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2592     return CI->getArgOperand(0);
2593   }
2594   return nullptr;
2595 }
2596 
2597 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2598                                                       IRBuilder<> &B,
2599                                                       LibFunc Func) {
2600   Function *Callee = CI->getCalledFunction();
2601   StringRef Name = Callee->getName();
2602   const DataLayout &DL = CI->getModule()->getDataLayout();
2603   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2604         *ObjSize = CI->getArgOperand(2);
2605 
2606   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
2607   if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2608     Value *StrLen = emitStrLen(Src, B, DL, TLI);
2609     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2610   }
2611 
2612   // If a) we don't have any length information, or b) we know this will
2613   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2614   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2615   // TODO: It might be nice to get a maximum length out of the possible
2616   // string lengths for varying.
2617   if (isFortifiedCallFoldable(CI, 2, 1, true))
2618     return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2619 
2620   if (OnlyLowerUnknownSize)
2621     return nullptr;
2622 
2623   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2624   uint64_t Len = GetStringLength(Src);
2625   if (Len == 0)
2626     return nullptr;
2627 
2628   Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2629   Value *LenV = ConstantInt::get(SizeTTy, Len);
2630   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2631   // If the function was an __stpcpy_chk, and we were able to fold it into
2632   // a __memcpy_chk, we still need to return the correct end pointer.
2633   if (Ret && Func == LibFunc_stpcpy_chk)
2634     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2635   return Ret;
2636 }
2637 
2638 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2639                                                        IRBuilder<> &B,
2640                                                        LibFunc Func) {
2641   Function *Callee = CI->getCalledFunction();
2642   StringRef Name = Callee->getName();
2643   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2644     Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2645                              CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2646     return Ret;
2647   }
2648   return nullptr;
2649 }
2650 
2651 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2652   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2653   // Some clang users checked for _chk libcall availability using:
2654   //   __has_builtin(__builtin___memcpy_chk)
2655   // When compiling with -fno-builtin, this is always true.
2656   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2657   // end up with fortified libcalls, which isn't acceptable in a freestanding
2658   // environment which only provides their non-fortified counterparts.
2659   //
2660   // Until we change clang and/or teach external users to check for availability
2661   // differently, disregard the "nobuiltin" attribute and TLI::has.
2662   //
2663   // PR23093.
2664 
2665   LibFunc Func;
2666   Function *Callee = CI->getCalledFunction();
2667 
2668   SmallVector<OperandBundleDef, 2> OpBundles;
2669   CI->getOperandBundlesAsDefs(OpBundles);
2670   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2671   bool isCallingConvC = isCallingConvCCompatible(CI);
2672 
2673   // First, check that this is a known library functions and that the prototype
2674   // is correct.
2675   if (!TLI->getLibFunc(*Callee, Func))
2676     return nullptr;
2677 
2678   // We never change the calling convention.
2679   if (!ignoreCallingConv(Func) && !isCallingConvC)
2680     return nullptr;
2681 
2682   switch (Func) {
2683   case LibFunc_memcpy_chk:
2684     return optimizeMemCpyChk(CI, Builder);
2685   case LibFunc_memmove_chk:
2686     return optimizeMemMoveChk(CI, Builder);
2687   case LibFunc_memset_chk:
2688     return optimizeMemSetChk(CI, Builder);
2689   case LibFunc_stpcpy_chk:
2690   case LibFunc_strcpy_chk:
2691     return optimizeStrpCpyChk(CI, Builder, Func);
2692   case LibFunc_stpncpy_chk:
2693   case LibFunc_strncpy_chk:
2694     return optimizeStrpNCpyChk(CI, Builder, Func);
2695   default:
2696     break;
2697   }
2698   return nullptr;
2699 }
2700 
2701 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2702     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2703     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
2704