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