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