d9c9100197329592d5aa9997dac325e1e95c53be
[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();
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 static bool isTrigLibCall(CallInst *CI);
1234 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1235                              bool UseFloat, Value *&Sin, Value *&Cos,
1236                              Value *&SinCos);
1237
1238 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1239
1240   // Make sure the prototype is as expected, otherwise the rest of the
1241   // function is probably invalid and likely to abort.
1242   if (!isTrigLibCall(CI))
1243     return nullptr;
1244
1245   Value *Arg = CI->getArgOperand(0);
1246   SmallVector<CallInst *, 1> SinCalls;
1247   SmallVector<CallInst *, 1> CosCalls;
1248   SmallVector<CallInst *, 1> SinCosCalls;
1249
1250   bool IsFloat = Arg->getType()->isFloatTy();
1251
1252   // Look for all compatible sinpi, cospi and sincospi calls with the same
1253   // argument. If there are enough (in some sense) we can make the
1254   // substitution.
1255   for (User *U : Arg->users())
1256     classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1257                    SinCosCalls);
1258
1259   // It's only worthwhile if both sinpi and cospi are actually used.
1260   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1261     return nullptr;
1262
1263   Value *Sin, *Cos, *SinCos;
1264   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1265
1266   replaceTrigInsts(SinCalls, Sin);
1267   replaceTrigInsts(CosCalls, Cos);
1268   replaceTrigInsts(SinCosCalls, SinCos);
1269
1270   return nullptr;
1271 }
1272
1273 static bool isTrigLibCall(CallInst *CI) {
1274   Function *Callee = CI->getCalledFunction();
1275   FunctionType *FT = Callee->getFunctionType();
1276
1277   // We can only hope to do anything useful if we can ignore things like errno
1278   // and floating-point exceptions.
1279   bool AttributesSafe =
1280       CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1281
1282   // Other than that we need float(float) or double(double)
1283   return AttributesSafe && FT->getNumParams() == 1 &&
1284          FT->getReturnType() == FT->getParamType(0) &&
1285          (FT->getParamType(0)->isFloatTy() ||
1286           FT->getParamType(0)->isDoubleTy());
1287 }
1288
1289 void
1290 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1291                                   SmallVectorImpl<CallInst *> &SinCalls,
1292                                   SmallVectorImpl<CallInst *> &CosCalls,
1293                                   SmallVectorImpl<CallInst *> &SinCosCalls) {
1294   CallInst *CI = dyn_cast<CallInst>(Val);
1295
1296   if (!CI)
1297     return;
1298
1299   Function *Callee = CI->getCalledFunction();
1300   StringRef FuncName = Callee->getName();
1301   LibFunc::Func Func;
1302   if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1303     return;
1304
1305   if (IsFloat) {
1306     if (Func == LibFunc::sinpif)
1307       SinCalls.push_back(CI);
1308     else if (Func == LibFunc::cospif)
1309       CosCalls.push_back(CI);
1310     else if (Func == LibFunc::sincospif_stret)
1311       SinCosCalls.push_back(CI);
1312   } else {
1313     if (Func == LibFunc::sinpi)
1314       SinCalls.push_back(CI);
1315     else if (Func == LibFunc::cospi)
1316       CosCalls.push_back(CI);
1317     else if (Func == LibFunc::sincospi_stret)
1318       SinCosCalls.push_back(CI);
1319   }
1320 }
1321
1322 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1323                                          Value *Res) {
1324   for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1325        I != E; ++I) {
1326     replaceAllUsesWith(*I, Res);
1327   }
1328 }
1329
1330 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1331                       bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1332   Type *ArgTy = Arg->getType();
1333   Type *ResTy;
1334   StringRef Name;
1335
1336   Triple T(OrigCallee->getParent()->getTargetTriple());
1337   if (UseFloat) {
1338     Name = "__sincospif_stret";
1339
1340     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1341     // x86_64 can't use {float, float} since that would be returned in both
1342     // xmm0 and xmm1, which isn't what a real struct would do.
1343     ResTy = T.getArch() == Triple::x86_64
1344                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1345                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1346   } else {
1347     Name = "__sincospi_stret";
1348     ResTy = StructType::get(ArgTy, ArgTy, NULL);
1349   }
1350
1351   Module *M = OrigCallee->getParent();
1352   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1353                                          ResTy, ArgTy, NULL);
1354
1355   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1356     // If the argument is an instruction, it must dominate all uses so put our
1357     // sincos call there.
1358     BasicBlock::iterator Loc = ArgInst;
1359     B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1360   } else {
1361     // Otherwise (e.g. for a constant) the beginning of the function is as
1362     // good a place as any.
1363     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1364     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1365   }
1366
1367   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1368
1369   if (SinCos->getType()->isStructTy()) {
1370     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1371     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1372   } else {
1373     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1374                                  "sinpi");
1375     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1376                                  "cospi");
1377   }
1378 }
1379
1380 //===----------------------------------------------------------------------===//
1381 // Integer Library Call Optimizations
1382 //===----------------------------------------------------------------------===//
1383
1384 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1385   Function *Callee = CI->getCalledFunction();
1386   FunctionType *FT = Callee->getFunctionType();
1387   // Just make sure this has 2 arguments of the same FP type, which match the
1388   // result type.
1389   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1390       !FT->getParamType(0)->isIntegerTy())
1391     return nullptr;
1392
1393   Value *Op = CI->getArgOperand(0);
1394
1395   // Constant fold.
1396   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1397     if (CI->isZero()) // ffs(0) -> 0.
1398       return B.getInt32(0);
1399     // ffs(c) -> cttz(c)+1
1400     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1401   }
1402
1403   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1404   Type *ArgType = Op->getType();
1405   Value *F =
1406       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1407   Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1408   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1409   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1410
1411   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1412   return B.CreateSelect(Cond, V, B.getInt32(0));
1413 }
1414
1415 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1416   Function *Callee = CI->getCalledFunction();
1417   FunctionType *FT = Callee->getFunctionType();
1418   // We require integer(integer) where the types agree.
1419   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1420       FT->getParamType(0) != FT->getReturnType())
1421     return nullptr;
1422
1423   // abs(x) -> x >s -1 ? x : -x
1424   Value *Op = CI->getArgOperand(0);
1425   Value *Pos =
1426       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1427   Value *Neg = B.CreateNeg(Op, "neg");
1428   return B.CreateSelect(Pos, Op, Neg);
1429 }
1430
1431 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1432   Function *Callee = CI->getCalledFunction();
1433   FunctionType *FT = Callee->getFunctionType();
1434   // We require integer(i32)
1435   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1436       !FT->getParamType(0)->isIntegerTy(32))
1437     return nullptr;
1438
1439   // isdigit(c) -> (c-'0') <u 10
1440   Value *Op = CI->getArgOperand(0);
1441   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1442   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1443   return B.CreateZExt(Op, CI->getType());
1444 }
1445
1446 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1447   Function *Callee = CI->getCalledFunction();
1448   FunctionType *FT = Callee->getFunctionType();
1449   // We require integer(i32)
1450   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1451       !FT->getParamType(0)->isIntegerTy(32))
1452     return nullptr;
1453
1454   // isascii(c) -> c <u 128
1455   Value *Op = CI->getArgOperand(0);
1456   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1457   return B.CreateZExt(Op, CI->getType());
1458 }
1459
1460 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1461   Function *Callee = CI->getCalledFunction();
1462   FunctionType *FT = Callee->getFunctionType();
1463   // We require i32(i32)
1464   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1465       !FT->getParamType(0)->isIntegerTy(32))
1466     return nullptr;
1467
1468   // toascii(c) -> c & 0x7f
1469   return B.CreateAnd(CI->getArgOperand(0),
1470                      ConstantInt::get(CI->getType(), 0x7F));
1471 }
1472
1473 //===----------------------------------------------------------------------===//
1474 // Formatting and IO Library Call Optimizations
1475 //===----------------------------------------------------------------------===//
1476
1477 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1478
1479 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1480                                                  int StreamArg) {
1481   // Error reporting calls should be cold, mark them as such.
1482   // This applies even to non-builtin calls: it is only a hint and applies to
1483   // functions that the frontend might not understand as builtins.
1484
1485   // This heuristic was suggested in:
1486   // Improving Static Branch Prediction in a Compiler
1487   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1488   // Proceedings of PACT'98, Oct. 1998, IEEE
1489   Function *Callee = CI->getCalledFunction();
1490
1491   if (!CI->hasFnAttr(Attribute::Cold) &&
1492       isReportingError(Callee, CI, StreamArg)) {
1493     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1494   }
1495
1496   return nullptr;
1497 }
1498
1499 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1500   if (!ColdErrorCalls)
1501     return false;
1502
1503   if (!Callee || !Callee->isDeclaration())
1504     return false;
1505
1506   if (StreamArg < 0)
1507     return true;
1508
1509   // These functions might be considered cold, but only if their stream
1510   // argument is stderr.
1511
1512   if (StreamArg >= (int)CI->getNumArgOperands())
1513     return false;
1514   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1515   if (!LI)
1516     return false;
1517   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1518   if (!GV || !GV->isDeclaration())
1519     return false;
1520   return GV->getName() == "stderr";
1521 }
1522
1523 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1524   // Check for a fixed format string.
1525   StringRef FormatStr;
1526   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1527     return nullptr;
1528
1529   // Empty format string -> noop.
1530   if (FormatStr.empty()) // Tolerate printf's declared void.
1531     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1532
1533   // Do not do any of the following transformations if the printf return value
1534   // is used, in general the printf return value is not compatible with either
1535   // putchar() or puts().
1536   if (!CI->use_empty())
1537     return nullptr;
1538
1539   // printf("x") -> putchar('x'), even for '%'.
1540   if (FormatStr.size() == 1) {
1541     Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1542     if (CI->use_empty() || !Res)
1543       return Res;
1544     return B.CreateIntCast(Res, CI->getType(), true);
1545   }
1546
1547   // printf("foo\n") --> puts("foo")
1548   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1549       FormatStr.find('%') == StringRef::npos) { // No format characters.
1550     // Create a string literal with no \n on it.  We expect the constant merge
1551     // pass to be run after this pass, to merge duplicate strings.
1552     FormatStr = FormatStr.drop_back();
1553     Value *GV = B.CreateGlobalString(FormatStr, "str");
1554     Value *NewCI = EmitPutS(GV, B, DL, TLI);
1555     return (CI->use_empty() || !NewCI)
1556                ? NewCI
1557                : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1558   }
1559
1560   // Optimize specific format strings.
1561   // printf("%c", chr) --> putchar(chr)
1562   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1563       CI->getArgOperand(1)->getType()->isIntegerTy()) {
1564     Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1565
1566     if (CI->use_empty() || !Res)
1567       return Res;
1568     return B.CreateIntCast(Res, CI->getType(), true);
1569   }
1570
1571   // printf("%s\n", str) --> puts(str)
1572   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1573       CI->getArgOperand(1)->getType()->isPointerTy()) {
1574     return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1575   }
1576   return nullptr;
1577 }
1578
1579 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1580
1581   Function *Callee = CI->getCalledFunction();
1582   // Require one fixed pointer argument and an integer/void result.
1583   FunctionType *FT = Callee->getFunctionType();
1584   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1585       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1586     return nullptr;
1587
1588   if (Value *V = optimizePrintFString(CI, B)) {
1589     return V;
1590   }
1591
1592   // printf(format, ...) -> iprintf(format, ...) if no floating point
1593   // arguments.
1594   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1595     Module *M = B.GetInsertBlock()->getParent()->getParent();
1596     Constant *IPrintFFn =
1597         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1598     CallInst *New = cast<CallInst>(CI->clone());
1599     New->setCalledFunction(IPrintFFn);
1600     B.Insert(New);
1601     return New;
1602   }
1603   return nullptr;
1604 }
1605
1606 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1607   // Check for a fixed format string.
1608   StringRef FormatStr;
1609   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1610     return nullptr;
1611
1612   // If we just have a format string (nothing else crazy) transform it.
1613   if (CI->getNumArgOperands() == 2) {
1614     // Make sure there's no % in the constant array.  We could try to handle
1615     // %% -> % in the future if we cared.
1616     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1617       if (FormatStr[i] == '%')
1618         return nullptr; // we found a format specifier, bail out.
1619
1620     // These optimizations require DataLayout.
1621     if (!DL)
1622       return nullptr;
1623
1624     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1625     B.CreateMemCpy(
1626         CI->getArgOperand(0), CI->getArgOperand(1),
1627         ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1628                          FormatStr.size() + 1),
1629         1); // Copy the null byte.
1630     return ConstantInt::get(CI->getType(), FormatStr.size());
1631   }
1632
1633   // The remaining optimizations require the format string to be "%s" or "%c"
1634   // and have an extra operand.
1635   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1636       CI->getNumArgOperands() < 3)
1637     return nullptr;
1638
1639   // Decode the second character of the format string.
1640   if (FormatStr[1] == 'c') {
1641     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1642     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1643       return nullptr;
1644     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1645     Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1646     B.CreateStore(V, Ptr);
1647     Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1648     B.CreateStore(B.getInt8(0), Ptr);
1649
1650     return ConstantInt::get(CI->getType(), 1);
1651   }
1652
1653   if (FormatStr[1] == 's') {
1654     // These optimizations require DataLayout.
1655     if (!DL)
1656       return nullptr;
1657
1658     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1659     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1660       return nullptr;
1661
1662     Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1663     if (!Len)
1664       return nullptr;
1665     Value *IncLen =
1666         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1667     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1668
1669     // The sprintf result is the unincremented number of bytes in the string.
1670     return B.CreateIntCast(Len, CI->getType(), false);
1671   }
1672   return nullptr;
1673 }
1674
1675 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1676   Function *Callee = CI->getCalledFunction();
1677   // Require two fixed pointer arguments and an integer result.
1678   FunctionType *FT = Callee->getFunctionType();
1679   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1680       !FT->getParamType(1)->isPointerTy() ||
1681       !FT->getReturnType()->isIntegerTy())
1682     return nullptr;
1683
1684   if (Value *V = optimizeSPrintFString(CI, B)) {
1685     return V;
1686   }
1687
1688   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1689   // point arguments.
1690   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1691     Module *M = B.GetInsertBlock()->getParent()->getParent();
1692     Constant *SIPrintFFn =
1693         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1694     CallInst *New = cast<CallInst>(CI->clone());
1695     New->setCalledFunction(SIPrintFFn);
1696     B.Insert(New);
1697     return New;
1698   }
1699   return nullptr;
1700 }
1701
1702 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1703   optimizeErrorReporting(CI, B, 0);
1704
1705   // All the optimizations depend on the format string.
1706   StringRef FormatStr;
1707   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1708     return nullptr;
1709
1710   // Do not do any of the following transformations if the fprintf return
1711   // value is used, in general the fprintf return value is not compatible
1712   // with fwrite(), fputc() or fputs().
1713   if (!CI->use_empty())
1714     return nullptr;
1715
1716   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1717   if (CI->getNumArgOperands() == 2) {
1718     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1719       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1720         return nullptr;        // We found a format specifier.
1721
1722     // These optimizations require DataLayout.
1723     if (!DL)
1724       return nullptr;
1725
1726     return EmitFWrite(
1727         CI->getArgOperand(1),
1728         ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1729         CI->getArgOperand(0), B, DL, TLI);
1730   }
1731
1732   // The remaining optimizations require the format string to be "%s" or "%c"
1733   // and have an extra operand.
1734   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1735       CI->getNumArgOperands() < 3)
1736     return nullptr;
1737
1738   // Decode the second character of the format string.
1739   if (FormatStr[1] == 'c') {
1740     // fprintf(F, "%c", chr) --> fputc(chr, F)
1741     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1742       return nullptr;
1743     return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1744   }
1745
1746   if (FormatStr[1] == 's') {
1747     // fprintf(F, "%s", str) --> fputs(str, F)
1748     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1749       return nullptr;
1750     return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1751   }
1752   return nullptr;
1753 }
1754
1755 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1756   Function *Callee = CI->getCalledFunction();
1757   // Require two fixed paramters as pointers and integer result.
1758   FunctionType *FT = Callee->getFunctionType();
1759   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1760       !FT->getParamType(1)->isPointerTy() ||
1761       !FT->getReturnType()->isIntegerTy())
1762     return nullptr;
1763
1764   if (Value *V = optimizeFPrintFString(CI, B)) {
1765     return V;
1766   }
1767
1768   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1769   // floating point arguments.
1770   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1771     Module *M = B.GetInsertBlock()->getParent()->getParent();
1772     Constant *FIPrintFFn =
1773         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1774     CallInst *New = cast<CallInst>(CI->clone());
1775     New->setCalledFunction(FIPrintFFn);
1776     B.Insert(New);
1777     return New;
1778   }
1779   return nullptr;
1780 }
1781
1782 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1783   optimizeErrorReporting(CI, B, 3);
1784
1785   Function *Callee = CI->getCalledFunction();
1786   // Require a pointer, an integer, an integer, a pointer, returning integer.
1787   FunctionType *FT = Callee->getFunctionType();
1788   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1789       !FT->getParamType(1)->isIntegerTy() ||
1790       !FT->getParamType(2)->isIntegerTy() ||
1791       !FT->getParamType(3)->isPointerTy() ||
1792       !FT->getReturnType()->isIntegerTy())
1793     return nullptr;
1794
1795   // Get the element size and count.
1796   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1797   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1798   if (!SizeC || !CountC)
1799     return nullptr;
1800   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1801
1802   // If this is writing zero records, remove the call (it's a noop).
1803   if (Bytes == 0)
1804     return ConstantInt::get(CI->getType(), 0);
1805
1806   // If this is writing one byte, turn it into fputc.
1807   // This optimisation is only valid, if the return value is unused.
1808   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1809     Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1810     Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1811     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1812   }
1813
1814   return nullptr;
1815 }
1816
1817 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1818   optimizeErrorReporting(CI, B, 1);
1819
1820   Function *Callee = CI->getCalledFunction();
1821
1822   // These optimizations require DataLayout.
1823   if (!DL)
1824     return nullptr;
1825
1826   // Require two pointers.  Also, we can't optimize if return value is used.
1827   FunctionType *FT = Callee->getFunctionType();
1828   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1829       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1830     return nullptr;
1831
1832   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1833   uint64_t Len = GetStringLength(CI->getArgOperand(0));
1834   if (!Len)
1835     return nullptr;
1836
1837   // Known to have no uses (see above).
1838   return EmitFWrite(
1839       CI->getArgOperand(0),
1840       ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1841       CI->getArgOperand(1), B, DL, TLI);
1842 }
1843
1844 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1845   Function *Callee = CI->getCalledFunction();
1846   // Require one fixed pointer argument and an integer/void result.
1847   FunctionType *FT = Callee->getFunctionType();
1848   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1849       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1850     return nullptr;
1851
1852   // Check for a constant string.
1853   StringRef Str;
1854   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1855     return nullptr;
1856
1857   if (Str.empty() && CI->use_empty()) {
1858     // puts("") -> putchar('\n')
1859     Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1860     if (CI->use_empty() || !Res)
1861       return Res;
1862     return B.CreateIntCast(Res, CI->getType(), true);
1863   }
1864
1865   return nullptr;
1866 }
1867
1868 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1869   LibFunc::Func Func;
1870   SmallString<20> FloatFuncName = FuncName;
1871   FloatFuncName += 'f';
1872   if (TLI->getLibFunc(FloatFuncName, Func))
1873     return TLI->has(Func);
1874   return false;
1875 }
1876
1877 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1878   if (CI->isNoBuiltin())
1879     return nullptr;
1880
1881   LibFunc::Func Func;
1882   Function *Callee = CI->getCalledFunction();
1883   StringRef FuncName = Callee->getName();
1884   IRBuilder<> Builder(CI);
1885   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1886
1887   // Next check for intrinsics.
1888   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1889     if (!isCallingConvC)
1890       return nullptr;
1891     switch (II->getIntrinsicID()) {
1892     case Intrinsic::pow:
1893       return optimizePow(CI, Builder);
1894     case Intrinsic::exp2:
1895       return optimizeExp2(CI, Builder);
1896     default:
1897       return nullptr;
1898     }
1899   }
1900
1901   // Then check for known library functions.
1902   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1903     // We never change the calling convention.
1904     if (!ignoreCallingConv(Func) && !isCallingConvC)
1905       return nullptr;
1906     switch (Func) {
1907     case LibFunc::strcat:
1908       return optimizeStrCat(CI, Builder);
1909     case LibFunc::strncat:
1910       return optimizeStrNCat(CI, Builder);
1911     case LibFunc::strchr:
1912       return optimizeStrChr(CI, Builder);
1913     case LibFunc::strrchr:
1914       return optimizeStrRChr(CI, Builder);
1915     case LibFunc::strcmp:
1916       return optimizeStrCmp(CI, Builder);
1917     case LibFunc::strncmp:
1918       return optimizeStrNCmp(CI, Builder);
1919     case LibFunc::strcpy:
1920       return optimizeStrCpy(CI, Builder);
1921     case LibFunc::stpcpy:
1922       return optimizeStpCpy(CI, Builder);
1923     case LibFunc::strncpy:
1924       return optimizeStrNCpy(CI, Builder);
1925     case LibFunc::strlen:
1926       return optimizeStrLen(CI, Builder);
1927     case LibFunc::strpbrk:
1928       return optimizeStrPBrk(CI, Builder);
1929     case LibFunc::strtol:
1930     case LibFunc::strtod:
1931     case LibFunc::strtof:
1932     case LibFunc::strtoul:
1933     case LibFunc::strtoll:
1934     case LibFunc::strtold:
1935     case LibFunc::strtoull:
1936       return optimizeStrTo(CI, Builder);
1937     case LibFunc::strspn:
1938       return optimizeStrSpn(CI, Builder);
1939     case LibFunc::strcspn:
1940       return optimizeStrCSpn(CI, Builder);
1941     case LibFunc::strstr:
1942       return optimizeStrStr(CI, Builder);
1943     case LibFunc::memcmp:
1944       return optimizeMemCmp(CI, Builder);
1945     case LibFunc::memcpy:
1946       return optimizeMemCpy(CI, Builder);
1947     case LibFunc::memmove:
1948       return optimizeMemMove(CI, Builder);
1949     case LibFunc::memset:
1950       return optimizeMemSet(CI, Builder);
1951     case LibFunc::cosf:
1952     case LibFunc::cos:
1953     case LibFunc::cosl:
1954       return optimizeCos(CI, Builder);
1955     case LibFunc::sinpif:
1956     case LibFunc::sinpi:
1957     case LibFunc::cospif:
1958     case LibFunc::cospi:
1959       return optimizeSinCosPi(CI, Builder);
1960     case LibFunc::powf:
1961     case LibFunc::pow:
1962     case LibFunc::powl:
1963       return optimizePow(CI, Builder);
1964     case LibFunc::exp2l:
1965     case LibFunc::exp2:
1966     case LibFunc::exp2f:
1967       return optimizeExp2(CI, Builder);
1968     case LibFunc::ffs:
1969     case LibFunc::ffsl:
1970     case LibFunc::ffsll:
1971       return optimizeFFS(CI, Builder);
1972     case LibFunc::abs:
1973     case LibFunc::labs:
1974     case LibFunc::llabs:
1975       return optimizeAbs(CI, Builder);
1976     case LibFunc::isdigit:
1977       return optimizeIsDigit(CI, Builder);
1978     case LibFunc::isascii:
1979       return optimizeIsAscii(CI, Builder);
1980     case LibFunc::toascii:
1981       return optimizeToAscii(CI, Builder);
1982     case LibFunc::printf:
1983       return optimizePrintF(CI, Builder);
1984     case LibFunc::sprintf:
1985       return optimizeSPrintF(CI, Builder);
1986     case LibFunc::fprintf:
1987       return optimizeFPrintF(CI, Builder);
1988     case LibFunc::fwrite:
1989       return optimizeFWrite(CI, Builder);
1990     case LibFunc::fputs:
1991       return optimizeFPuts(CI, Builder);
1992     case LibFunc::puts:
1993       return optimizePuts(CI, Builder);
1994     case LibFunc::perror:
1995       return optimizeErrorReporting(CI, Builder);
1996     case LibFunc::vfprintf:
1997     case LibFunc::fiprintf:
1998       return optimizeErrorReporting(CI, Builder, 0);
1999     case LibFunc::fputc:
2000       return optimizeErrorReporting(CI, Builder, 1);
2001     case LibFunc::ceil:
2002     case LibFunc::fabs:
2003     case LibFunc::floor:
2004     case LibFunc::rint:
2005     case LibFunc::round:
2006     case LibFunc::nearbyint:
2007     case LibFunc::trunc:
2008       if (hasFloatVersion(FuncName))
2009         return optimizeUnaryDoubleFP(CI, Builder, false);
2010       return nullptr;
2011     case LibFunc::acos:
2012     case LibFunc::acosh:
2013     case LibFunc::asin:
2014     case LibFunc::asinh:
2015     case LibFunc::atan:
2016     case LibFunc::atanh:
2017     case LibFunc::cbrt:
2018     case LibFunc::cosh:
2019     case LibFunc::exp:
2020     case LibFunc::exp10:
2021     case LibFunc::expm1:
2022     case LibFunc::log:
2023     case LibFunc::log10:
2024     case LibFunc::log1p:
2025     case LibFunc::log2:
2026     case LibFunc::logb:
2027     case LibFunc::sin:
2028     case LibFunc::sinh:
2029     case LibFunc::sqrt:
2030     case LibFunc::tan:
2031     case LibFunc::tanh:
2032       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2033         return optimizeUnaryDoubleFP(CI, Builder, true);
2034       return nullptr;
2035     case LibFunc::fmin:
2036     case LibFunc::fmax:
2037       if (hasFloatVersion(FuncName))
2038         return optimizeBinaryDoubleFP(CI, Builder);
2039       return nullptr;
2040     case LibFunc::memcpy_chk:
2041       return optimizeMemCpyChk(CI, Builder);
2042     default:
2043       return nullptr;
2044     }
2045   }
2046
2047   if (!isCallingConvC)
2048     return nullptr;
2049
2050   // Finally check for fortified library calls.
2051   if (FuncName.endswith("_chk")) {
2052     if (FuncName == "__memmove_chk")
2053       return optimizeMemMoveChk(CI, Builder);
2054     else if (FuncName == "__memset_chk")
2055       return optimizeMemSetChk(CI, Builder);
2056     else if (FuncName == "__strcpy_chk")
2057       return optimizeStrCpyChk(CI, Builder);
2058     else if (FuncName == "__stpcpy_chk")
2059       return optimizeStpCpyChk(CI, Builder);
2060     else if (FuncName == "__strncpy_chk")
2061       return optimizeStrNCpyChk(CI, Builder);
2062     else if (FuncName == "__stpncpy_chk")
2063       return optimizeStrNCpyChk(CI, Builder);
2064   }
2065
2066   return nullptr;
2067 }
2068
2069 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2070                                      const TargetLibraryInfo *TLI,
2071                                      bool UnsafeFPShrink) :
2072                                      DL(DL),
2073                                      TLI(TLI),
2074                                      UnsafeFPShrink(UnsafeFPShrink) {
2075 }
2076
2077 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2078   I->replaceAllUsesWith(With);
2079   I->eraseFromParent();
2080 }
2081
2082 // TODO:
2083 //   Additional cases that we need to add to this file:
2084 //
2085 // cbrt:
2086 //   * cbrt(expN(X))  -> expN(x/3)
2087 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2088 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2089 //
2090 // exp, expf, expl:
2091 //   * exp(log(x))  -> x
2092 //
2093 // log, logf, logl:
2094 //   * log(exp(x))   -> x
2095 //   * log(x**y)     -> y*log(x)
2096 //   * log(exp(y))   -> y*log(e)
2097 //   * log(exp2(y))  -> y*log(2)
2098 //   * log(exp10(y)) -> y*log(10)
2099 //   * log(sqrt(x))  -> 0.5*log(x)
2100 //   * log(pow(x,y)) -> y*log(x)
2101 //
2102 // lround, lroundf, lroundl:
2103 //   * lround(cnst) -> cnst'
2104 //
2105 // pow, powf, powl:
2106 //   * pow(exp(x),y)  -> exp(x*y)
2107 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2108 //   * pow(pow(x,y),z)-> pow(x,y*z)
2109 //
2110 // round, roundf, roundl:
2111 //   * round(cnst) -> cnst'
2112 //
2113 // signbit:
2114 //   * signbit(cnst) -> cnst'
2115 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2116 //
2117 // sqrt, sqrtf, sqrtl:
2118 //   * sqrt(expN(x))  -> expN(x*0.5)
2119 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2120 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2121 //
2122 // tan, tanf, tanl:
2123 //   * tan(atan(x)) -> x
2124 //
2125 // trunc, truncf, truncl:
2126 //   * trunc(cnst) -> cnst'
2127 //
2128 //