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