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