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