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