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