[SimplifyLibCalls] Use range-based loop. No functional change.
[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 (CallInst *C : Calls)
1431     replaceAllUsesWith(C, Res);
1432 }
1433
1434 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1435                       bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1436   Type *ArgTy = Arg->getType();
1437   Type *ResTy;
1438   StringRef Name;
1439
1440   Triple T(OrigCallee->getParent()->getTargetTriple());
1441   if (UseFloat) {
1442     Name = "__sincospif_stret";
1443
1444     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1445     // x86_64 can't use {float, float} since that would be returned in both
1446     // xmm0 and xmm1, which isn't what a real struct would do.
1447     ResTy = T.getArch() == Triple::x86_64
1448                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1449                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1450   } else {
1451     Name = "__sincospi_stret";
1452     ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1453   }
1454
1455   Module *M = OrigCallee->getParent();
1456   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1457                                          ResTy, ArgTy, nullptr);
1458
1459   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1460     // If the argument is an instruction, it must dominate all uses so put our
1461     // sincos call there.
1462     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1463   } else {
1464     // Otherwise (e.g. for a constant) the beginning of the function is as
1465     // good a place as any.
1466     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1467     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1468   }
1469
1470   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1471
1472   if (SinCos->getType()->isStructTy()) {
1473     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1474     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1475   } else {
1476     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1477                                  "sinpi");
1478     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1479                                  "cospi");
1480   }
1481 }
1482
1483 //===----------------------------------------------------------------------===//
1484 // Integer Library Call Optimizations
1485 //===----------------------------------------------------------------------===//
1486
1487 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1488   Function *Callee = CI->getCalledFunction();
1489   FunctionType *FT = Callee->getFunctionType();
1490   // Just make sure this has 2 arguments of the same FP type, which match the
1491   // result type.
1492   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1493       !FT->getParamType(0)->isIntegerTy())
1494     return nullptr;
1495
1496   Value *Op = CI->getArgOperand(0);
1497
1498   // Constant fold.
1499   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1500     if (CI->isZero()) // ffs(0) -> 0.
1501       return B.getInt32(0);
1502     // ffs(c) -> cttz(c)+1
1503     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1504   }
1505
1506   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1507   Type *ArgType = Op->getType();
1508   Value *F =
1509       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1510   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1511   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1512   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1513
1514   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1515   return B.CreateSelect(Cond, V, B.getInt32(0));
1516 }
1517
1518 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1519   Function *Callee = CI->getCalledFunction();
1520   FunctionType *FT = Callee->getFunctionType();
1521   // We require integer(integer) where the types agree.
1522   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1523       FT->getParamType(0) != FT->getReturnType())
1524     return nullptr;
1525
1526   // abs(x) -> x >s -1 ? x : -x
1527   Value *Op = CI->getArgOperand(0);
1528   Value *Pos =
1529       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1530   Value *Neg = B.CreateNeg(Op, "neg");
1531   return B.CreateSelect(Pos, Op, Neg);
1532 }
1533
1534 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1535   Function *Callee = CI->getCalledFunction();
1536   FunctionType *FT = Callee->getFunctionType();
1537   // We require integer(i32)
1538   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1539       !FT->getParamType(0)->isIntegerTy(32))
1540     return nullptr;
1541
1542   // isdigit(c) -> (c-'0') <u 10
1543   Value *Op = CI->getArgOperand(0);
1544   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1545   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1546   return B.CreateZExt(Op, CI->getType());
1547 }
1548
1549 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1550   Function *Callee = CI->getCalledFunction();
1551   FunctionType *FT = Callee->getFunctionType();
1552   // We require integer(i32)
1553   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1554       !FT->getParamType(0)->isIntegerTy(32))
1555     return nullptr;
1556
1557   // isascii(c) -> c <u 128
1558   Value *Op = CI->getArgOperand(0);
1559   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1560   return B.CreateZExt(Op, CI->getType());
1561 }
1562
1563 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1564   Function *Callee = CI->getCalledFunction();
1565   FunctionType *FT = Callee->getFunctionType();
1566   // We require i32(i32)
1567   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1568       !FT->getParamType(0)->isIntegerTy(32))
1569     return nullptr;
1570
1571   // toascii(c) -> c & 0x7f
1572   return B.CreateAnd(CI->getArgOperand(0),
1573                      ConstantInt::get(CI->getType(), 0x7F));
1574 }
1575
1576 //===----------------------------------------------------------------------===//
1577 // Formatting and IO Library Call Optimizations
1578 //===----------------------------------------------------------------------===//
1579
1580 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1581
1582 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1583                                                  int StreamArg) {
1584   // Error reporting calls should be cold, mark them as such.
1585   // This applies even to non-builtin calls: it is only a hint and applies to
1586   // functions that the frontend might not understand as builtins.
1587
1588   // This heuristic was suggested in:
1589   // Improving Static Branch Prediction in a Compiler
1590   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1591   // Proceedings of PACT'98, Oct. 1998, IEEE
1592   Function *Callee = CI->getCalledFunction();
1593
1594   if (!CI->hasFnAttr(Attribute::Cold) &&
1595       isReportingError(Callee, CI, StreamArg)) {
1596     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1597   }
1598
1599   return nullptr;
1600 }
1601
1602 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1603   if (!ColdErrorCalls)
1604     return false;
1605
1606   if (!Callee || !Callee->isDeclaration())
1607     return false;
1608
1609   if (StreamArg < 0)
1610     return true;
1611
1612   // These functions might be considered cold, but only if their stream
1613   // argument is stderr.
1614
1615   if (StreamArg >= (int)CI->getNumArgOperands())
1616     return false;
1617   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1618   if (!LI)
1619     return false;
1620   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1621   if (!GV || !GV->isDeclaration())
1622     return false;
1623   return GV->getName() == "stderr";
1624 }
1625
1626 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1627   // Check for a fixed format string.
1628   StringRef FormatStr;
1629   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1630     return nullptr;
1631
1632   // Empty format string -> noop.
1633   if (FormatStr.empty()) // Tolerate printf's declared void.
1634     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1635
1636   // Do not do any of the following transformations if the printf return value
1637   // is used, in general the printf return value is not compatible with either
1638   // putchar() or puts().
1639   if (!CI->use_empty())
1640     return nullptr;
1641
1642   // printf("x") -> putchar('x'), even for '%'.
1643   if (FormatStr.size() == 1) {
1644     Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1645     if (CI->use_empty() || !Res)
1646       return Res;
1647     return B.CreateIntCast(Res, CI->getType(), true);
1648   }
1649
1650   // printf("foo\n") --> puts("foo")
1651   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1652       FormatStr.find('%') == StringRef::npos) { // No format characters.
1653     // Create a string literal with no \n on it.  We expect the constant merge
1654     // pass to be run after this pass, to merge duplicate strings.
1655     FormatStr = FormatStr.drop_back();
1656     Value *GV = B.CreateGlobalString(FormatStr, "str");
1657     Value *NewCI = EmitPutS(GV, B, TLI);
1658     return (CI->use_empty() || !NewCI)
1659                ? NewCI
1660                : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1661   }
1662
1663   // Optimize specific format strings.
1664   // printf("%c", chr) --> putchar(chr)
1665   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1666       CI->getArgOperand(1)->getType()->isIntegerTy()) {
1667     Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1668
1669     if (CI->use_empty() || !Res)
1670       return Res;
1671     return B.CreateIntCast(Res, CI->getType(), true);
1672   }
1673
1674   // printf("%s\n", str) --> puts(str)
1675   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1676       CI->getArgOperand(1)->getType()->isPointerTy()) {
1677     return EmitPutS(CI->getArgOperand(1), B, TLI);
1678   }
1679   return nullptr;
1680 }
1681
1682 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1683
1684   Function *Callee = CI->getCalledFunction();
1685   // Require one fixed pointer argument and an integer/void result.
1686   FunctionType *FT = Callee->getFunctionType();
1687   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1688       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1689     return nullptr;
1690
1691   if (Value *V = optimizePrintFString(CI, B)) {
1692     return V;
1693   }
1694
1695   // printf(format, ...) -> iprintf(format, ...) if no floating point
1696   // arguments.
1697   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1698     Module *M = B.GetInsertBlock()->getParent()->getParent();
1699     Constant *IPrintFFn =
1700         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1701     CallInst *New = cast<CallInst>(CI->clone());
1702     New->setCalledFunction(IPrintFFn);
1703     B.Insert(New);
1704     return New;
1705   }
1706   return nullptr;
1707 }
1708
1709 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1710   // Check for a fixed format string.
1711   StringRef FormatStr;
1712   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1713     return nullptr;
1714
1715   // If we just have a format string (nothing else crazy) transform it.
1716   if (CI->getNumArgOperands() == 2) {
1717     // Make sure there's no % in the constant array.  We could try to handle
1718     // %% -> % in the future if we cared.
1719     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1720       if (FormatStr[i] == '%')
1721         return nullptr; // we found a format specifier, bail out.
1722
1723     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1724     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1725                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1726                                     FormatStr.size() + 1),
1727                    1); // Copy the null byte.
1728     return ConstantInt::get(CI->getType(), FormatStr.size());
1729   }
1730
1731   // The remaining optimizations require the format string to be "%s" or "%c"
1732   // and have an extra operand.
1733   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1734       CI->getNumArgOperands() < 3)
1735     return nullptr;
1736
1737   // Decode the second character of the format string.
1738   if (FormatStr[1] == 'c') {
1739     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1740     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1741       return nullptr;
1742     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1743     Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1744     B.CreateStore(V, Ptr);
1745     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1746     B.CreateStore(B.getInt8(0), Ptr);
1747
1748     return ConstantInt::get(CI->getType(), 1);
1749   }
1750
1751   if (FormatStr[1] == 's') {
1752     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1753     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1754       return nullptr;
1755
1756     Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1757     if (!Len)
1758       return nullptr;
1759     Value *IncLen =
1760         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1761     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1762
1763     // The sprintf result is the unincremented number of bytes in the string.
1764     return B.CreateIntCast(Len, CI->getType(), false);
1765   }
1766   return nullptr;
1767 }
1768
1769 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1770   Function *Callee = CI->getCalledFunction();
1771   // Require two fixed pointer arguments and an integer result.
1772   FunctionType *FT = Callee->getFunctionType();
1773   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1774       !FT->getParamType(1)->isPointerTy() ||
1775       !FT->getReturnType()->isIntegerTy())
1776     return nullptr;
1777
1778   if (Value *V = optimizeSPrintFString(CI, B)) {
1779     return V;
1780   }
1781
1782   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1783   // point arguments.
1784   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1785     Module *M = B.GetInsertBlock()->getParent()->getParent();
1786     Constant *SIPrintFFn =
1787         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1788     CallInst *New = cast<CallInst>(CI->clone());
1789     New->setCalledFunction(SIPrintFFn);
1790     B.Insert(New);
1791     return New;
1792   }
1793   return nullptr;
1794 }
1795
1796 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1797   optimizeErrorReporting(CI, B, 0);
1798
1799   // All the optimizations depend on the format string.
1800   StringRef FormatStr;
1801   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1802     return nullptr;
1803
1804   // Do not do any of the following transformations if the fprintf return
1805   // value is used, in general the fprintf return value is not compatible
1806   // with fwrite(), fputc() or fputs().
1807   if (!CI->use_empty())
1808     return nullptr;
1809
1810   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1811   if (CI->getNumArgOperands() == 2) {
1812     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1813       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1814         return nullptr;        // We found a format specifier.
1815
1816     return EmitFWrite(
1817         CI->getArgOperand(1),
1818         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1819         CI->getArgOperand(0), B, DL, TLI);
1820   }
1821
1822   // The remaining optimizations require the format string to be "%s" or "%c"
1823   // and have an extra operand.
1824   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1825       CI->getNumArgOperands() < 3)
1826     return nullptr;
1827
1828   // Decode the second character of the format string.
1829   if (FormatStr[1] == 'c') {
1830     // fprintf(F, "%c", chr) --> fputc(chr, F)
1831     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1832       return nullptr;
1833     return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1834   }
1835
1836   if (FormatStr[1] == 's') {
1837     // fprintf(F, "%s", str) --> fputs(str, F)
1838     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1839       return nullptr;
1840     return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1841   }
1842   return nullptr;
1843 }
1844
1845 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1846   Function *Callee = CI->getCalledFunction();
1847   // Require two fixed paramters as pointers and integer result.
1848   FunctionType *FT = Callee->getFunctionType();
1849   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1850       !FT->getParamType(1)->isPointerTy() ||
1851       !FT->getReturnType()->isIntegerTy())
1852     return nullptr;
1853
1854   if (Value *V = optimizeFPrintFString(CI, B)) {
1855     return V;
1856   }
1857
1858   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1859   // floating point arguments.
1860   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1861     Module *M = B.GetInsertBlock()->getParent()->getParent();
1862     Constant *FIPrintFFn =
1863         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1864     CallInst *New = cast<CallInst>(CI->clone());
1865     New->setCalledFunction(FIPrintFFn);
1866     B.Insert(New);
1867     return New;
1868   }
1869   return nullptr;
1870 }
1871
1872 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1873   optimizeErrorReporting(CI, B, 3);
1874
1875   Function *Callee = CI->getCalledFunction();
1876   // Require a pointer, an integer, an integer, a pointer, returning integer.
1877   FunctionType *FT = Callee->getFunctionType();
1878   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1879       !FT->getParamType(1)->isIntegerTy() ||
1880       !FT->getParamType(2)->isIntegerTy() ||
1881       !FT->getParamType(3)->isPointerTy() ||
1882       !FT->getReturnType()->isIntegerTy())
1883     return nullptr;
1884
1885   // Get the element size and count.
1886   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1887   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1888   if (!SizeC || !CountC)
1889     return nullptr;
1890   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1891
1892   // If this is writing zero records, remove the call (it's a noop).
1893   if (Bytes == 0)
1894     return ConstantInt::get(CI->getType(), 0);
1895
1896   // If this is writing one byte, turn it into fputc.
1897   // This optimisation is only valid, if the return value is unused.
1898   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1899     Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1900     Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1901     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1902   }
1903
1904   return nullptr;
1905 }
1906
1907 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1908   optimizeErrorReporting(CI, B, 1);
1909
1910   Function *Callee = CI->getCalledFunction();
1911
1912   // Require two pointers.  Also, we can't optimize if return value is used.
1913   FunctionType *FT = Callee->getFunctionType();
1914   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1915       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1916     return nullptr;
1917
1918   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1919   uint64_t Len = GetStringLength(CI->getArgOperand(0));
1920   if (!Len)
1921     return nullptr;
1922
1923   // Known to have no uses (see above).
1924   return EmitFWrite(
1925       CI->getArgOperand(0),
1926       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1927       CI->getArgOperand(1), B, DL, TLI);
1928 }
1929
1930 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1931   Function *Callee = CI->getCalledFunction();
1932   // Require one fixed pointer argument and an integer/void result.
1933   FunctionType *FT = Callee->getFunctionType();
1934   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1935       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1936     return nullptr;
1937
1938   // Check for a constant string.
1939   StringRef Str;
1940   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1941     return nullptr;
1942
1943   if (Str.empty() && CI->use_empty()) {
1944     // puts("") -> putchar('\n')
1945     Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1946     if (CI->use_empty() || !Res)
1947       return Res;
1948     return B.CreateIntCast(Res, CI->getType(), true);
1949   }
1950
1951   return nullptr;
1952 }
1953
1954 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1955   LibFunc::Func Func;
1956   SmallString<20> FloatFuncName = FuncName;
1957   FloatFuncName += 'f';
1958   if (TLI->getLibFunc(FloatFuncName, Func))
1959     return TLI->has(Func);
1960   return false;
1961 }
1962
1963 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1964                                                       IRBuilder<> &Builder) {
1965   LibFunc::Func Func;
1966   Function *Callee = CI->getCalledFunction();
1967   StringRef FuncName = Callee->getName();
1968
1969   // Check for string/memory library functions.
1970   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1971     // Make sure we never change the calling convention.
1972     assert((ignoreCallingConv(Func) ||
1973             CI->getCallingConv() == llvm::CallingConv::C) &&
1974       "Optimizing string/memory libcall would change the calling convention");
1975     switch (Func) {
1976     case LibFunc::strcat:
1977       return optimizeStrCat(CI, Builder);
1978     case LibFunc::strncat:
1979       return optimizeStrNCat(CI, Builder);
1980     case LibFunc::strchr:
1981       return optimizeStrChr(CI, Builder);
1982     case LibFunc::strrchr:
1983       return optimizeStrRChr(CI, Builder);
1984     case LibFunc::strcmp:
1985       return optimizeStrCmp(CI, Builder);
1986     case LibFunc::strncmp:
1987       return optimizeStrNCmp(CI, Builder);
1988     case LibFunc::strcpy:
1989       return optimizeStrCpy(CI, Builder);
1990     case LibFunc::stpcpy:
1991       return optimizeStpCpy(CI, Builder);
1992     case LibFunc::strncpy:
1993       return optimizeStrNCpy(CI, Builder);
1994     case LibFunc::strlen:
1995       return optimizeStrLen(CI, Builder);
1996     case LibFunc::strpbrk:
1997       return optimizeStrPBrk(CI, Builder);
1998     case LibFunc::strtol:
1999     case LibFunc::strtod:
2000     case LibFunc::strtof:
2001     case LibFunc::strtoul:
2002     case LibFunc::strtoll:
2003     case LibFunc::strtold:
2004     case LibFunc::strtoull:
2005       return optimizeStrTo(CI, Builder);
2006     case LibFunc::strspn:
2007       return optimizeStrSpn(CI, Builder);
2008     case LibFunc::strcspn:
2009       return optimizeStrCSpn(CI, Builder);
2010     case LibFunc::strstr:
2011       return optimizeStrStr(CI, Builder);
2012     case LibFunc::memchr:
2013       return optimizeMemChr(CI, Builder);
2014     case LibFunc::memcmp:
2015       return optimizeMemCmp(CI, Builder);
2016     case LibFunc::memcpy:
2017       return optimizeMemCpy(CI, Builder);
2018     case LibFunc::memmove:
2019       return optimizeMemMove(CI, Builder);
2020     case LibFunc::memset:
2021       return optimizeMemSet(CI, Builder);
2022     default:
2023       break;
2024     }
2025   }
2026   return nullptr;
2027 }
2028
2029 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2030   if (CI->isNoBuiltin())
2031     return nullptr;
2032
2033   LibFunc::Func Func;
2034   Function *Callee = CI->getCalledFunction();
2035   StringRef FuncName = Callee->getName();
2036   IRBuilder<> Builder(CI);
2037   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2038
2039   // Command-line parameter overrides function attribute.
2040   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2041     UnsafeFPShrink = EnableUnsafeFPShrink;
2042   else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2043     // FIXME: This is the same problem as described in optimizeSqrt().
2044     // If calls gain access to IR-level FMF, then use that instead of a
2045     // function attribute.
2046
2047     // Check for unsafe-fp-math = true.
2048     Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2049     if (Attr.getValueAsString() == "true")
2050       UnsafeFPShrink = true;
2051   }
2052
2053   // First, check for intrinsics.
2054   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2055     if (!isCallingConvC)
2056       return nullptr;
2057     switch (II->getIntrinsicID()) {
2058     case Intrinsic::pow:
2059       return optimizePow(CI, Builder);
2060     case Intrinsic::exp2:
2061       return optimizeExp2(CI, Builder);
2062     case Intrinsic::fabs:
2063       return optimizeFabs(CI, Builder);
2064     case Intrinsic::sqrt:
2065       return optimizeSqrt(CI, Builder);
2066     default:
2067       return nullptr;
2068     }
2069   }
2070
2071   // Also try to simplify calls to fortified library functions.
2072   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2073     // Try to further simplify the result.
2074     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2075     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2076       // Use an IR Builder from SimplifiedCI if available instead of CI
2077       // to guarantee we reach all uses we might replace later on.
2078       IRBuilder<> TmpBuilder(SimplifiedCI);
2079       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
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     }
2086     return SimplifiedFortifiedCI;
2087   }
2088
2089   // Then check for known library functions.
2090   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2091     // We never change the calling convention.
2092     if (!ignoreCallingConv(Func) && !isCallingConvC)
2093       return nullptr;
2094     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2095       return V;
2096     switch (Func) {
2097     case LibFunc::cosf:
2098     case LibFunc::cos:
2099     case LibFunc::cosl:
2100       return optimizeCos(CI, Builder);
2101     case LibFunc::sinpif:
2102     case LibFunc::sinpi:
2103     case LibFunc::cospif:
2104     case LibFunc::cospi:
2105       return optimizeSinCosPi(CI, Builder);
2106     case LibFunc::powf:
2107     case LibFunc::pow:
2108     case LibFunc::powl:
2109       return optimizePow(CI, Builder);
2110     case LibFunc::exp2l:
2111     case LibFunc::exp2:
2112     case LibFunc::exp2f:
2113       return optimizeExp2(CI, Builder);
2114     case LibFunc::fabsf:
2115     case LibFunc::fabs:
2116     case LibFunc::fabsl:
2117       return optimizeFabs(CI, Builder);
2118     case LibFunc::sqrtf:
2119     case LibFunc::sqrt:
2120     case LibFunc::sqrtl:
2121       return optimizeSqrt(CI, Builder);
2122     case LibFunc::ffs:
2123     case LibFunc::ffsl:
2124     case LibFunc::ffsll:
2125       return optimizeFFS(CI, Builder);
2126     case LibFunc::abs:
2127     case LibFunc::labs:
2128     case LibFunc::llabs:
2129       return optimizeAbs(CI, Builder);
2130     case LibFunc::isdigit:
2131       return optimizeIsDigit(CI, Builder);
2132     case LibFunc::isascii:
2133       return optimizeIsAscii(CI, Builder);
2134     case LibFunc::toascii:
2135       return optimizeToAscii(CI, Builder);
2136     case LibFunc::printf:
2137       return optimizePrintF(CI, Builder);
2138     case LibFunc::sprintf:
2139       return optimizeSPrintF(CI, Builder);
2140     case LibFunc::fprintf:
2141       return optimizeFPrintF(CI, Builder);
2142     case LibFunc::fwrite:
2143       return optimizeFWrite(CI, Builder);
2144     case LibFunc::fputs:
2145       return optimizeFPuts(CI, Builder);
2146     case LibFunc::puts:
2147       return optimizePuts(CI, Builder);
2148     case LibFunc::perror:
2149       return optimizeErrorReporting(CI, Builder);
2150     case LibFunc::vfprintf:
2151     case LibFunc::fiprintf:
2152       return optimizeErrorReporting(CI, Builder, 0);
2153     case LibFunc::fputc:
2154       return optimizeErrorReporting(CI, Builder, 1);
2155     case LibFunc::ceil:
2156     case LibFunc::floor:
2157     case LibFunc::rint:
2158     case LibFunc::round:
2159     case LibFunc::nearbyint:
2160     case LibFunc::trunc:
2161       if (hasFloatVersion(FuncName))
2162         return optimizeUnaryDoubleFP(CI, Builder, false);
2163       return nullptr;
2164     case LibFunc::acos:
2165     case LibFunc::acosh:
2166     case LibFunc::asin:
2167     case LibFunc::asinh:
2168     case LibFunc::atan:
2169     case LibFunc::atanh:
2170     case LibFunc::cbrt:
2171     case LibFunc::cosh:
2172     case LibFunc::exp:
2173     case LibFunc::exp10:
2174     case LibFunc::expm1:
2175     case LibFunc::log:
2176     case LibFunc::log10:
2177     case LibFunc::log1p:
2178     case LibFunc::log2:
2179     case LibFunc::logb:
2180     case LibFunc::sin:
2181     case LibFunc::sinh:
2182     case LibFunc::tan:
2183     case LibFunc::tanh:
2184       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2185         return optimizeUnaryDoubleFP(CI, Builder, true);
2186       return nullptr;
2187     case LibFunc::copysign:
2188       if (hasFloatVersion(FuncName))
2189         return optimizeBinaryDoubleFP(CI, Builder);
2190       return nullptr;
2191     case LibFunc::fminf:
2192     case LibFunc::fmin:
2193     case LibFunc::fminl:
2194     case LibFunc::fmaxf:
2195     case LibFunc::fmax:
2196     case LibFunc::fmaxl:
2197       return optimizeFMinFMax(CI, Builder);
2198     default:
2199       return nullptr;
2200     }
2201   }
2202   return nullptr;
2203 }
2204
2205 LibCallSimplifier::LibCallSimplifier(
2206     const DataLayout &DL, const TargetLibraryInfo *TLI,
2207     function_ref<void(Instruction *, Value *)> Replacer)
2208     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2209       Replacer(Replacer) {}
2210
2211 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2212   // Indirect through the replacer used in this instance.
2213   Replacer(I, With);
2214 }
2215
2216 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2217                                                              Value *With) {
2218   I->replaceAllUsesWith(With);
2219   I->eraseFromParent();
2220 }
2221
2222 // TODO:
2223 //   Additional cases that we need to add to this file:
2224 //
2225 // cbrt:
2226 //   * cbrt(expN(X))  -> expN(x/3)
2227 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2228 //   * cbrt(cbrt(x))  -> pow(x,1/9)
2229 //
2230 // exp, expf, expl:
2231 //   * exp(log(x))  -> x
2232 //
2233 // log, logf, logl:
2234 //   * log(exp(x))   -> x
2235 //   * log(x**y)     -> y*log(x)
2236 //   * log(exp(y))   -> y*log(e)
2237 //   * log(exp2(y))  -> y*log(2)
2238 //   * log(exp10(y)) -> y*log(10)
2239 //   * log(sqrt(x))  -> 0.5*log(x)
2240 //   * log(pow(x,y)) -> y*log(x)
2241 //
2242 // lround, lroundf, lroundl:
2243 //   * lround(cnst) -> cnst'
2244 //
2245 // pow, powf, powl:
2246 //   * pow(exp(x),y)  -> exp(x*y)
2247 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2248 //   * pow(pow(x,y),z)-> pow(x,y*z)
2249 //
2250 // round, roundf, roundl:
2251 //   * round(cnst) -> cnst'
2252 //
2253 // signbit:
2254 //   * signbit(cnst) -> cnst'
2255 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2256 //
2257 // sqrt, sqrtf, sqrtl:
2258 //   * sqrt(expN(x))  -> expN(x*0.5)
2259 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2260 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2261 //
2262 // tan, tanf, tanl:
2263 //   * tan(atan(x)) -> x
2264 //
2265 // trunc, truncf, truncl:
2266 //   * trunc(cnst) -> cnst'
2267 //
2268 //
2269
2270 //===----------------------------------------------------------------------===//
2271 // Fortified Library Call Optimizations
2272 //===----------------------------------------------------------------------===//
2273
2274 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2275                                                          unsigned ObjSizeOp,
2276                                                          unsigned SizeOp,
2277                                                          bool isString) {
2278   if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2279     return true;
2280   if (ConstantInt *ObjSizeCI =
2281           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2282     if (ObjSizeCI->isAllOnesValue())
2283       return true;
2284     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2285     if (OnlyLowerUnknownSize)
2286       return false;
2287     if (isString) {
2288       uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2289       // If the length is 0 we don't know how long it is and so we can't
2290       // remove the check.
2291       if (Len == 0)
2292         return false;
2293       return ObjSizeCI->getZExtValue() >= Len;
2294     }
2295     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2296       return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2297   }
2298   return false;
2299 }
2300
2301 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2302   Function *Callee = CI->getCalledFunction();
2303
2304   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2305     return nullptr;
2306
2307   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2308     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2309                    CI->getArgOperand(2), 1);
2310     return CI->getArgOperand(0);
2311   }
2312   return nullptr;
2313 }
2314
2315 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2316   Function *Callee = CI->getCalledFunction();
2317
2318   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2319     return nullptr;
2320
2321   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2322     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2323                     CI->getArgOperand(2), 1);
2324     return CI->getArgOperand(0);
2325   }
2326   return nullptr;
2327 }
2328
2329 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2330   Function *Callee = CI->getCalledFunction();
2331
2332   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2333     return nullptr;
2334
2335   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2336     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2337     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2338     return CI->getArgOperand(0);
2339   }
2340   return nullptr;
2341 }
2342
2343 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2344                                                       IRBuilder<> &B,
2345                                                       LibFunc::Func Func) {
2346   Function *Callee = CI->getCalledFunction();
2347   StringRef Name = Callee->getName();
2348   const DataLayout &DL = CI->getModule()->getDataLayout();
2349
2350   if (!checkStringCopyLibFuncSignature(Callee, Func))
2351     return nullptr;
2352
2353   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2354         *ObjSize = CI->getArgOperand(2);
2355
2356   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
2357   if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2358     Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2359     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2360   }
2361
2362   // If a) we don't have any length information, or b) we know this will
2363   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2364   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2365   // TODO: It might be nice to get a maximum length out of the possible
2366   // string lengths for varying.
2367   if (isFortifiedCallFoldable(CI, 2, 1, true))
2368     return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2369
2370   if (OnlyLowerUnknownSize)
2371     return nullptr;
2372
2373   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2374   uint64_t Len = GetStringLength(Src);
2375   if (Len == 0)
2376     return nullptr;
2377
2378   Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2379   Value *LenV = ConstantInt::get(SizeTTy, Len);
2380   Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2381   // If the function was an __stpcpy_chk, and we were able to fold it into
2382   // a __memcpy_chk, we still need to return the correct end pointer.
2383   if (Ret && Func == LibFunc::stpcpy_chk)
2384     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2385   return Ret;
2386 }
2387
2388 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2389                                                        IRBuilder<> &B,
2390                                                        LibFunc::Func Func) {
2391   Function *Callee = CI->getCalledFunction();
2392   StringRef Name = Callee->getName();
2393
2394   if (!checkStringCopyLibFuncSignature(Callee, Func))
2395     return nullptr;
2396   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2397     Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2398                              CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2399     return Ret;
2400   }
2401   return nullptr;
2402 }
2403
2404 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2405   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2406   // Some clang users checked for _chk libcall availability using:
2407   //   __has_builtin(__builtin___memcpy_chk)
2408   // When compiling with -fno-builtin, this is always true.
2409   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2410   // end up with fortified libcalls, which isn't acceptable in a freestanding
2411   // environment which only provides their non-fortified counterparts.
2412   //
2413   // Until we change clang and/or teach external users to check for availability
2414   // differently, disregard the "nobuiltin" attribute and TLI::has.
2415   //
2416   // PR23093.
2417
2418   LibFunc::Func Func;
2419   Function *Callee = CI->getCalledFunction();
2420   StringRef FuncName = Callee->getName();
2421   IRBuilder<> Builder(CI);
2422   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2423
2424   // First, check that this is a known library functions.
2425   if (!TLI->getLibFunc(FuncName, Func))
2426     return nullptr;
2427
2428   // We never change the calling convention.
2429   if (!ignoreCallingConv(Func) && !isCallingConvC)
2430     return nullptr;
2431
2432   switch (Func) {
2433   case LibFunc::memcpy_chk:
2434     return optimizeMemCpyChk(CI, Builder);
2435   case LibFunc::memmove_chk:
2436     return optimizeMemMoveChk(CI, Builder);
2437   case LibFunc::memset_chk:
2438     return optimizeMemSetChk(CI, Builder);
2439   case LibFunc::stpcpy_chk:
2440   case LibFunc::strcpy_chk:
2441     return optimizeStrpCpyChk(CI, Builder, Func);
2442   case LibFunc::stpncpy_chk:
2443   case LibFunc::strncpy_chk:
2444     return optimizeStrpNCpyChk(CI, Builder, Func);
2445   default:
2446     break;
2447   }
2448   return nullptr;
2449 }
2450
2451 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2452     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2453     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}