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