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