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