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