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