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