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