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