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