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