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