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