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