DataLayout is mandatory, update the API to reflect it with references.
[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::optimizeMemCmp(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)->isPointerTy() ||
753       !FT->getReturnType()->isIntegerTy(32))
754     return nullptr;
755
756   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
757
758   if (LHS == RHS) // memcmp(s,s,x) -> 0
759     return Constant::getNullValue(CI->getType());
760
761   // Make sure we have a constant length.
762   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
763   if (!LenC)
764     return nullptr;
765   uint64_t Len = LenC->getZExtValue();
766
767   if (Len == 0) // memcmp(s1,s2,0) -> 0
768     return Constant::getNullValue(CI->getType());
769
770   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
771   if (Len == 1) {
772     Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
773                                CI->getType(), "lhsv");
774     Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
775                                CI->getType(), "rhsv");
776     return B.CreateSub(LHSV, RHSV, "chardiff");
777   }
778
779   // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
780   StringRef LHSStr, RHSStr;
781   if (getConstantStringInfo(LHS, LHSStr) &&
782       getConstantStringInfo(RHS, RHSStr)) {
783     // Make sure we're not reading out-of-bounds memory.
784     if (Len > LHSStr.size() || Len > RHSStr.size())
785       return nullptr;
786     // Fold the memcmp and normalize the result.  This way we get consistent
787     // results across multiple platforms.
788     uint64_t Ret = 0;
789     int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
790     if (Cmp < 0)
791       Ret = -1;
792     else if (Cmp > 0)
793       Ret = 1;
794     return ConstantInt::get(CI->getType(), Ret);
795   }
796
797   return nullptr;
798 }
799
800 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
801   Function *Callee = CI->getCalledFunction();
802
803   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
804     return nullptr;
805
806   // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
807   B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
808                  CI->getArgOperand(2), 1);
809   return CI->getArgOperand(0);
810 }
811
812 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
813   Function *Callee = CI->getCalledFunction();
814
815   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
816     return nullptr;
817
818   // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
819   B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
820                   CI->getArgOperand(2), 1);
821   return CI->getArgOperand(0);
822 }
823
824 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
825   Function *Callee = CI->getCalledFunction();
826
827   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
828     return nullptr;
829
830   // memset(p, v, n) -> llvm.memset(p, v, n, 1)
831   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
832   B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
833   return CI->getArgOperand(0);
834 }
835
836 //===----------------------------------------------------------------------===//
837 // Math Library Optimizations
838 //===----------------------------------------------------------------------===//
839
840 /// Return a variant of Val with float type.
841 /// Currently this works in two cases: If Val is an FPExtension of a float
842 /// value to something bigger, simply return the operand.
843 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
844 /// loss of precision do so.
845 static Value *valueHasFloatPrecision(Value *Val) {
846   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
847     Value *Op = Cast->getOperand(0);
848     if (Op->getType()->isFloatTy())
849       return Op;
850   }
851   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
852     APFloat F = Const->getValueAPF();
853     bool losesInfo;
854     (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
855                     &losesInfo);
856     if (!losesInfo)
857       return ConstantFP::get(Const->getContext(), F);
858   }
859   return nullptr;
860 }
861
862 //===----------------------------------------------------------------------===//
863 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
864
865 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
866                                                 bool CheckRetType) {
867   Function *Callee = CI->getCalledFunction();
868   FunctionType *FT = Callee->getFunctionType();
869   if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
870       !FT->getParamType(0)->isDoubleTy())
871     return nullptr;
872
873   if (CheckRetType) {
874     // Check if all the uses for function like 'sin' are converted to float.
875     for (User *U : CI->users()) {
876       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
877       if (!Cast || !Cast->getType()->isFloatTy())
878         return nullptr;
879     }
880   }
881
882   // If this is something like 'floor((double)floatval)', convert to floorf.
883   Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
884   if (V == nullptr)
885     return nullptr;
886
887   // floor((double)floatval) -> (double)floorf(floatval)
888   if (Callee->isIntrinsic()) {
889     Module *M = CI->getParent()->getParent()->getParent();
890     Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
891     Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
892     V = B.CreateCall(F, V);
893   } else {
894     // The call is a library call rather than an intrinsic.
895     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
896   }
897
898   return B.CreateFPExt(V, B.getDoubleTy());
899 }
900
901 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
902 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
903   Function *Callee = CI->getCalledFunction();
904   FunctionType *FT = Callee->getFunctionType();
905   // Just make sure this has 2 arguments of the same FP type, which match the
906   // result type.
907   if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
908       FT->getParamType(0) != FT->getParamType(1) ||
909       !FT->getParamType(0)->isFloatingPointTy())
910     return nullptr;
911
912   // If this is something like 'fmin((double)floatval1, (double)floatval2)',
913   // or fmin(1.0, (double)floatval), then we convert it to fminf.
914   Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
915   if (V1 == nullptr)
916     return nullptr;
917   Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
918   if (V2 == nullptr)
919     return nullptr;
920
921   // fmin((double)floatval1, (double)floatval2)
922   //                      -> (double)fminf(floatval1, floatval2)
923   // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
924   Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
925                                    Callee->getAttributes());
926   return B.CreateFPExt(V, B.getDoubleTy());
927 }
928
929 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
930   Function *Callee = CI->getCalledFunction();
931   Value *Ret = nullptr;
932   if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
933     Ret = optimizeUnaryDoubleFP(CI, B, true);
934   }
935
936   FunctionType *FT = Callee->getFunctionType();
937   // Just make sure this has 1 argument of FP type, which matches the
938   // result type.
939   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
940       !FT->getParamType(0)->isFloatingPointTy())
941     return Ret;
942
943   // cos(-x) -> cos(x)
944   Value *Op1 = CI->getArgOperand(0);
945   if (BinaryOperator::isFNeg(Op1)) {
946     BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
947     return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
948   }
949   return Ret;
950 }
951
952 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
953   Function *Callee = CI->getCalledFunction();
954
955   Value *Ret = nullptr;
956   if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
957     Ret = optimizeUnaryDoubleFP(CI, B, true);
958   }
959
960   FunctionType *FT = Callee->getFunctionType();
961   // Just make sure this has 2 arguments of the same FP type, which match the
962   // result type.
963   if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
964       FT->getParamType(0) != FT->getParamType(1) ||
965       !FT->getParamType(0)->isFloatingPointTy())
966     return Ret;
967
968   Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
969   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
970     // pow(1.0, x) -> 1.0
971     if (Op1C->isExactlyValue(1.0))
972       return Op1C;
973     // pow(2.0, x) -> exp2(x)
974     if (Op1C->isExactlyValue(2.0) &&
975         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
976                         LibFunc::exp2l))
977       return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
978     // pow(10.0, x) -> exp10(x)
979     if (Op1C->isExactlyValue(10.0) &&
980         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
981                         LibFunc::exp10l))
982       return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
983                                   Callee->getAttributes());
984   }
985
986   ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
987   if (!Op2C)
988     return Ret;
989
990   if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
991     return ConstantFP::get(CI->getType(), 1.0);
992
993   if (Op2C->isExactlyValue(0.5) &&
994       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
995                       LibFunc::sqrtl) &&
996       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
997                       LibFunc::fabsl)) {
998     // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
999     // This is faster than calling pow, and still handles negative zero
1000     // and negative infinity correctly.
1001     // TODO: In fast-math mode, this could be just sqrt(x).
1002     // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1003     Value *Inf = ConstantFP::getInfinity(CI->getType());
1004     Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1005     Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1006     Value *FAbs =
1007         EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1008     Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1009     Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1010     return Sel;
1011   }
1012
1013   if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1014     return Op1;
1015   if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1016     return B.CreateFMul(Op1, Op1, "pow2");
1017   if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1018     return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1019   return nullptr;
1020 }
1021
1022 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1023   Function *Callee = CI->getCalledFunction();
1024   Function *Caller = CI->getParent()->getParent();
1025
1026   Value *Ret = nullptr;
1027   if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1028       TLI->has(LibFunc::exp2f)) {
1029     Ret = optimizeUnaryDoubleFP(CI, B, true);
1030   }
1031
1032   FunctionType *FT = Callee->getFunctionType();
1033   // Just make sure this has 1 argument of FP type, which matches the
1034   // result type.
1035   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1036       !FT->getParamType(0)->isFloatingPointTy())
1037     return Ret;
1038
1039   Value *Op = CI->getArgOperand(0);
1040   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1041   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1042   LibFunc::Func LdExp = LibFunc::ldexpl;
1043   if (Op->getType()->isFloatTy())
1044     LdExp = LibFunc::ldexpf;
1045   else if (Op->getType()->isDoubleTy())
1046     LdExp = LibFunc::ldexp;
1047
1048   if (TLI->has(LdExp)) {
1049     Value *LdExpArg = nullptr;
1050     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1051       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1052         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1053     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1054       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1055         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1056     }
1057
1058     if (LdExpArg) {
1059       Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1060       if (!Op->getType()->isFloatTy())
1061         One = ConstantExpr::getFPExtend(One, Op->getType());
1062
1063       Module *M = Caller->getParent();
1064       Value *Callee =
1065           M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1066                                  Op->getType(), B.getInt32Ty(), nullptr);
1067       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1068       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1069         CI->setCallingConv(F->getCallingConv());
1070
1071       return CI;
1072     }
1073   }
1074   return Ret;
1075 }
1076
1077 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1078   Function *Callee = CI->getCalledFunction();
1079
1080   Value *Ret = nullptr;
1081   if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1082     Ret = optimizeUnaryDoubleFP(CI, B, false);
1083   }
1084
1085   FunctionType *FT = Callee->getFunctionType();
1086   // Make sure this has 1 argument of FP type which matches the result type.
1087   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1088       !FT->getParamType(0)->isFloatingPointTy())
1089     return Ret;
1090
1091   Value *Op = CI->getArgOperand(0);
1092   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1093     // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1094     if (I->getOpcode() == Instruction::FMul)
1095       if (I->getOperand(0) == I->getOperand(1))
1096         return Op;
1097   }
1098   return Ret;
1099 }
1100
1101 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1102   Function *Callee = CI->getCalledFunction();
1103   
1104   Value *Ret = nullptr;
1105   if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1106                                    Callee->getIntrinsicID() == Intrinsic::sqrt))
1107     Ret = optimizeUnaryDoubleFP(CI, B, true);
1108
1109   // FIXME: For finer-grain optimization, we need intrinsics to have the same
1110   // fast-math flag decorations that are applied to FP instructions. For now,
1111   // we have to rely on the function-level unsafe-fp-math attribute to do this
1112   // optimization because there's no other way to express that the sqrt can be
1113   // reassociated.
1114   Function *F = CI->getParent()->getParent();
1115   if (F->hasFnAttribute("unsafe-fp-math")) {
1116     // Check for unsafe-fp-math = true.
1117     Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1118     if (Attr.getValueAsString() != "true")
1119       return Ret;
1120   }
1121   Value *Op = CI->getArgOperand(0);
1122   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1123     if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1124       // We're looking for a repeated factor in a multiplication tree,
1125       // so we can do this fold: sqrt(x * x) -> fabs(x);
1126       // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1127       Value *Op0 = I->getOperand(0);
1128       Value *Op1 = I->getOperand(1);
1129       Value *RepeatOp = nullptr;
1130       Value *OtherOp = nullptr;
1131       if (Op0 == Op1) {
1132         // Simple match: the operands of the multiply are identical.
1133         RepeatOp = Op0;
1134       } else {
1135         // Look for a more complicated pattern: one of the operands is itself
1136         // a multiply, so search for a common factor in that multiply.
1137         // Note: We don't bother looking any deeper than this first level or for
1138         // variations of this pattern because instcombine's visitFMUL and/or the
1139         // reassociation pass should give us this form.
1140         Value *OtherMul0, *OtherMul1;
1141         if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1142           // Pattern: sqrt((x * y) * z)
1143           if (OtherMul0 == OtherMul1) {
1144             // Matched: sqrt((x * x) * z)
1145             RepeatOp = OtherMul0;
1146             OtherOp = Op1;
1147           }
1148         }
1149       }
1150       if (RepeatOp) {
1151         // Fast math flags for any created instructions should match the sqrt
1152         // and multiply.
1153         // FIXME: We're not checking the sqrt because it doesn't have
1154         // fast-math-flags (see earlier comment).
1155         IRBuilder<true, ConstantFolder,
1156           IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1157         B.SetFastMathFlags(I->getFastMathFlags());
1158         // If we found a repeated factor, hoist it out of the square root and
1159         // replace it with the fabs of that factor.
1160         Module *M = Callee->getParent();
1161         Type *ArgType = Op->getType();
1162         Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1163         Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1164         if (OtherOp) {
1165           // If we found a non-repeated factor, we still need to get its square
1166           // root. We then multiply that by the value that was simplified out
1167           // of the square root calculation.
1168           Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1169           Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1170           return B.CreateFMul(FabsCall, SqrtCall);
1171         }
1172         return FabsCall;
1173       }
1174     }
1175   }
1176   return Ret;
1177 }
1178
1179 static bool isTrigLibCall(CallInst *CI);
1180 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1181                              bool UseFloat, Value *&Sin, Value *&Cos,
1182                              Value *&SinCos);
1183
1184 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1185
1186   // Make sure the prototype is as expected, otherwise the rest of the
1187   // function is probably invalid and likely to abort.
1188   if (!isTrigLibCall(CI))
1189     return nullptr;
1190
1191   Value *Arg = CI->getArgOperand(0);
1192   SmallVector<CallInst *, 1> SinCalls;
1193   SmallVector<CallInst *, 1> CosCalls;
1194   SmallVector<CallInst *, 1> SinCosCalls;
1195
1196   bool IsFloat = Arg->getType()->isFloatTy();
1197
1198   // Look for all compatible sinpi, cospi and sincospi calls with the same
1199   // argument. If there are enough (in some sense) we can make the
1200   // substitution.
1201   for (User *U : Arg->users())
1202     classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1203                    SinCosCalls);
1204
1205   // It's only worthwhile if both sinpi and cospi are actually used.
1206   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1207     return nullptr;
1208
1209   Value *Sin, *Cos, *SinCos;
1210   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1211
1212   replaceTrigInsts(SinCalls, Sin);
1213   replaceTrigInsts(CosCalls, Cos);
1214   replaceTrigInsts(SinCosCalls, SinCos);
1215
1216   return nullptr;
1217 }
1218
1219 static bool isTrigLibCall(CallInst *CI) {
1220   Function *Callee = CI->getCalledFunction();
1221   FunctionType *FT = Callee->getFunctionType();
1222
1223   // We can only hope to do anything useful if we can ignore things like errno
1224   // and floating-point exceptions.
1225   bool AttributesSafe =
1226       CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1227
1228   // Other than that we need float(float) or double(double)
1229   return AttributesSafe && FT->getNumParams() == 1 &&
1230          FT->getReturnType() == FT->getParamType(0) &&
1231          (FT->getParamType(0)->isFloatTy() ||
1232           FT->getParamType(0)->isDoubleTy());
1233 }
1234
1235 void
1236 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1237                                   SmallVectorImpl<CallInst *> &SinCalls,
1238                                   SmallVectorImpl<CallInst *> &CosCalls,
1239                                   SmallVectorImpl<CallInst *> &SinCosCalls) {
1240   CallInst *CI = dyn_cast<CallInst>(Val);
1241
1242   if (!CI)
1243     return;
1244
1245   Function *Callee = CI->getCalledFunction();
1246   StringRef FuncName = Callee->getName();
1247   LibFunc::Func Func;
1248   if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1249     return;
1250
1251   if (IsFloat) {
1252     if (Func == LibFunc::sinpif)
1253       SinCalls.push_back(CI);
1254     else if (Func == LibFunc::cospif)
1255       CosCalls.push_back(CI);
1256     else if (Func == LibFunc::sincospif_stret)
1257       SinCosCalls.push_back(CI);
1258   } else {
1259     if (Func == LibFunc::sinpi)
1260       SinCalls.push_back(CI);
1261     else if (Func == LibFunc::cospi)
1262       CosCalls.push_back(CI);
1263     else if (Func == LibFunc::sincospi_stret)
1264       SinCosCalls.push_back(CI);
1265   }
1266 }
1267
1268 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1269                                          Value *Res) {
1270   for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1271        I != E; ++I) {
1272     replaceAllUsesWith(*I, Res);
1273   }
1274 }
1275
1276 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1277                       bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1278   Type *ArgTy = Arg->getType();
1279   Type *ResTy;
1280   StringRef Name;
1281
1282   Triple T(OrigCallee->getParent()->getTargetTriple());
1283   if (UseFloat) {
1284     Name = "__sincospif_stret";
1285
1286     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1287     // x86_64 can't use {float, float} since that would be returned in both
1288     // xmm0 and xmm1, which isn't what a real struct would do.
1289     ResTy = T.getArch() == Triple::x86_64
1290                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1291                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1292   } else {
1293     Name = "__sincospi_stret";
1294     ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1295   }
1296
1297   Module *M = OrigCallee->getParent();
1298   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1299                                          ResTy, ArgTy, nullptr);
1300
1301   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1302     // If the argument is an instruction, it must dominate all uses so put our
1303     // sincos call there.
1304     BasicBlock::iterator Loc = ArgInst;
1305     B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1306   } else {
1307     // Otherwise (e.g. for a constant) the beginning of the function is as
1308     // good a place as any.
1309     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1310     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1311   }
1312
1313   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1314
1315   if (SinCos->getType()->isStructTy()) {
1316     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1317     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1318   } else {
1319     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1320                                  "sinpi");
1321     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1322                                  "cospi");
1323   }
1324 }
1325
1326 //===----------------------------------------------------------------------===//
1327 // Integer Library Call Optimizations
1328 //===----------------------------------------------------------------------===//
1329
1330 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1331   Function *Callee = CI->getCalledFunction();
1332   FunctionType *FT = Callee->getFunctionType();
1333   // Just make sure this has 2 arguments of the same FP type, which match the
1334   // result type.
1335   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1336       !FT->getParamType(0)->isIntegerTy())
1337     return nullptr;
1338
1339   Value *Op = CI->getArgOperand(0);
1340
1341   // Constant fold.
1342   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1343     if (CI->isZero()) // ffs(0) -> 0.
1344       return B.getInt32(0);
1345     // ffs(c) -> cttz(c)+1
1346     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1347   }
1348
1349   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1350   Type *ArgType = Op->getType();
1351   Value *F =
1352       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1353   Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1354   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1355   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1356
1357   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1358   return B.CreateSelect(Cond, V, B.getInt32(0));
1359 }
1360
1361 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1362   Function *Callee = CI->getCalledFunction();
1363   FunctionType *FT = Callee->getFunctionType();
1364   // We require integer(integer) where the types agree.
1365   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1366       FT->getParamType(0) != FT->getReturnType())
1367     return nullptr;
1368
1369   // abs(x) -> x >s -1 ? x : -x
1370   Value *Op = CI->getArgOperand(0);
1371   Value *Pos =
1372       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1373   Value *Neg = B.CreateNeg(Op, "neg");
1374   return B.CreateSelect(Pos, Op, Neg);
1375 }
1376
1377 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1378   Function *Callee = CI->getCalledFunction();
1379   FunctionType *FT = Callee->getFunctionType();
1380   // We require integer(i32)
1381   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1382       !FT->getParamType(0)->isIntegerTy(32))
1383     return nullptr;
1384
1385   // isdigit(c) -> (c-'0') <u 10
1386   Value *Op = CI->getArgOperand(0);
1387   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1388   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1389   return B.CreateZExt(Op, CI->getType());
1390 }
1391
1392 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1393   Function *Callee = CI->getCalledFunction();
1394   FunctionType *FT = Callee->getFunctionType();
1395   // We require integer(i32)
1396   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1397       !FT->getParamType(0)->isIntegerTy(32))
1398     return nullptr;
1399
1400   // isascii(c) -> c <u 128
1401   Value *Op = CI->getArgOperand(0);
1402   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1403   return B.CreateZExt(Op, CI->getType());
1404 }
1405
1406 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1407   Function *Callee = CI->getCalledFunction();
1408   FunctionType *FT = Callee->getFunctionType();
1409   // We require i32(i32)
1410   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1411       !FT->getParamType(0)->isIntegerTy(32))
1412     return nullptr;
1413
1414   // toascii(c) -> c & 0x7f
1415   return B.CreateAnd(CI->getArgOperand(0),
1416                      ConstantInt::get(CI->getType(), 0x7F));
1417 }
1418
1419 //===----------------------------------------------------------------------===//
1420 // Formatting and IO Library Call Optimizations
1421 //===----------------------------------------------------------------------===//
1422
1423 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1424
1425 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1426                                                  int StreamArg) {
1427   // Error reporting calls should be cold, mark them as such.
1428   // This applies even to non-builtin calls: it is only a hint and applies to
1429   // functions that the frontend might not understand as builtins.
1430
1431   // This heuristic was suggested in:
1432   // Improving Static Branch Prediction in a Compiler
1433   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1434   // Proceedings of PACT'98, Oct. 1998, IEEE
1435   Function *Callee = CI->getCalledFunction();
1436
1437   if (!CI->hasFnAttr(Attribute::Cold) &&
1438       isReportingError(Callee, CI, StreamArg)) {
1439     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1440   }
1441
1442   return nullptr;
1443 }
1444
1445 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1446   if (!ColdErrorCalls)
1447     return false;
1448
1449   if (!Callee || !Callee->isDeclaration())
1450     return false;
1451
1452   if (StreamArg < 0)
1453     return true;
1454
1455   // These functions might be considered cold, but only if their stream
1456   // argument is stderr.
1457
1458   if (StreamArg >= (int)CI->getNumArgOperands())
1459     return false;
1460   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1461   if (!LI)
1462     return false;
1463   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1464   if (!GV || !GV->isDeclaration())
1465     return false;
1466   return GV->getName() == "stderr";
1467 }
1468
1469 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1470   // Check for a fixed format string.
1471   StringRef FormatStr;
1472   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1473     return nullptr;
1474
1475   // Empty format string -> noop.
1476   if (FormatStr.empty()) // Tolerate printf's declared void.
1477     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1478
1479   // Do not do any of the following transformations if the printf return value
1480   // is used, in general the printf return value is not compatible with either
1481   // putchar() or puts().
1482   if (!CI->use_empty())
1483     return nullptr;
1484
1485   // printf("x") -> putchar('x'), even for '%'.
1486   if (FormatStr.size() == 1) {
1487     Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1488     if (CI->use_empty() || !Res)
1489       return Res;
1490     return B.CreateIntCast(Res, CI->getType(), true);
1491   }
1492
1493   // printf("foo\n") --> puts("foo")
1494   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1495       FormatStr.find('%') == StringRef::npos) { // No format characters.
1496     // Create a string literal with no \n on it.  We expect the constant merge
1497     // pass to be run after this pass, to merge duplicate strings.
1498     FormatStr = FormatStr.drop_back();
1499     Value *GV = B.CreateGlobalString(FormatStr, "str");
1500     Value *NewCI = EmitPutS(GV, B, TLI);
1501     return (CI->use_empty() || !NewCI)
1502                ? NewCI
1503                : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1504   }
1505
1506   // Optimize specific format strings.
1507   // printf("%c", chr) --> putchar(chr)
1508   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1509       CI->getArgOperand(1)->getType()->isIntegerTy()) {
1510     Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1511
1512     if (CI->use_empty() || !Res)
1513       return Res;
1514     return B.CreateIntCast(Res, CI->getType(), true);
1515   }
1516
1517   // printf("%s\n", str) --> puts(str)
1518   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1519       CI->getArgOperand(1)->getType()->isPointerTy()) {
1520     return EmitPutS(CI->getArgOperand(1), B, TLI);
1521   }
1522   return nullptr;
1523 }
1524
1525 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1526
1527   Function *Callee = CI->getCalledFunction();
1528   // Require one fixed pointer argument and an integer/void result.
1529   FunctionType *FT = Callee->getFunctionType();
1530   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1531       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1532     return nullptr;
1533
1534   if (Value *V = optimizePrintFString(CI, B)) {
1535     return V;
1536   }
1537
1538   // printf(format, ...) -> iprintf(format, ...) if no floating point
1539   // arguments.
1540   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1541     Module *M = B.GetInsertBlock()->getParent()->getParent();
1542     Constant *IPrintFFn =
1543         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1544     CallInst *New = cast<CallInst>(CI->clone());
1545     New->setCalledFunction(IPrintFFn);
1546     B.Insert(New);
1547     return New;
1548   }
1549   return nullptr;
1550 }
1551
1552 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1553   // Check for a fixed format string.
1554   StringRef FormatStr;
1555   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1556     return nullptr;
1557
1558   // If we just have a format string (nothing else crazy) transform it.
1559   if (CI->getNumArgOperands() == 2) {
1560     // Make sure there's no % in the constant array.  We could try to handle
1561     // %% -> % in the future if we cared.
1562     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1563       if (FormatStr[i] == '%')
1564         return nullptr; // we found a format specifier, bail out.
1565
1566     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1567     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1568                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1569                                     FormatStr.size() + 1),
1570                    1); // Copy the null byte.
1571     return ConstantInt::get(CI->getType(), FormatStr.size());
1572   }
1573
1574   // The remaining optimizations require the format string to be "%s" or "%c"
1575   // and have an extra operand.
1576   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1577       CI->getNumArgOperands() < 3)
1578     return nullptr;
1579
1580   // Decode the second character of the format string.
1581   if (FormatStr[1] == 'c') {
1582     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1583     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1584       return nullptr;
1585     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1586     Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1587     B.CreateStore(V, Ptr);
1588     Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1589     B.CreateStore(B.getInt8(0), Ptr);
1590
1591     return ConstantInt::get(CI->getType(), 1);
1592   }
1593
1594   if (FormatStr[1] == 's') {
1595     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1596     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1597       return nullptr;
1598
1599     Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1600     if (!Len)
1601       return nullptr;
1602     Value *IncLen =
1603         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1604     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1605
1606     // The sprintf result is the unincremented number of bytes in the string.
1607     return B.CreateIntCast(Len, CI->getType(), false);
1608   }
1609   return nullptr;
1610 }
1611
1612 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1613   Function *Callee = CI->getCalledFunction();
1614   // Require two fixed pointer arguments and an integer result.
1615   FunctionType *FT = Callee->getFunctionType();
1616   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1617       !FT->getParamType(1)->isPointerTy() ||
1618       !FT->getReturnType()->isIntegerTy())
1619     return nullptr;
1620
1621   if (Value *V = optimizeSPrintFString(CI, B)) {
1622     return V;
1623   }
1624
1625   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1626   // point arguments.
1627   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1628     Module *M = B.GetInsertBlock()->getParent()->getParent();
1629     Constant *SIPrintFFn =
1630         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1631     CallInst *New = cast<CallInst>(CI->clone());
1632     New->setCalledFunction(SIPrintFFn);
1633     B.Insert(New);
1634     return New;
1635   }
1636   return nullptr;
1637 }
1638
1639 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1640   optimizeErrorReporting(CI, B, 0);
1641
1642   // All the optimizations depend on the format string.
1643   StringRef FormatStr;
1644   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1645     return nullptr;
1646
1647   // Do not do any of the following transformations if the fprintf return
1648   // value is used, in general the fprintf return value is not compatible
1649   // with fwrite(), fputc() or fputs().
1650   if (!CI->use_empty())
1651     return nullptr;
1652
1653   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1654   if (CI->getNumArgOperands() == 2) {
1655     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1656       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1657         return nullptr;        // We found a format specifier.
1658
1659     return EmitFWrite(
1660         CI->getArgOperand(1),
1661         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1662         CI->getArgOperand(0), B, DL, TLI);
1663   }
1664
1665   // The remaining optimizations require the format string to be "%s" or "%c"
1666   // and have an extra operand.
1667   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1668       CI->getNumArgOperands() < 3)
1669     return nullptr;
1670
1671   // Decode the second character of the format string.
1672   if (FormatStr[1] == 'c') {
1673     // fprintf(F, "%c", chr) --> fputc(chr, F)
1674     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1675       return nullptr;
1676     return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1677   }
1678
1679   if (FormatStr[1] == 's') {
1680     // fprintf(F, "%s", str) --> fputs(str, F)
1681     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1682       return nullptr;
1683     return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1684   }
1685   return nullptr;
1686 }
1687
1688 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1689   Function *Callee = CI->getCalledFunction();
1690   // Require two fixed paramters as pointers and integer result.
1691   FunctionType *FT = Callee->getFunctionType();
1692   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1693       !FT->getParamType(1)->isPointerTy() ||
1694       !FT->getReturnType()->isIntegerTy())
1695     return nullptr;
1696
1697   if (Value *V = optimizeFPrintFString(CI, B)) {
1698     return V;
1699   }
1700
1701   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1702   // floating point arguments.
1703   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1704     Module *M = B.GetInsertBlock()->getParent()->getParent();
1705     Constant *FIPrintFFn =
1706         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1707     CallInst *New = cast<CallInst>(CI->clone());
1708     New->setCalledFunction(FIPrintFFn);
1709     B.Insert(New);
1710     return New;
1711   }
1712   return nullptr;
1713 }
1714
1715 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1716   optimizeErrorReporting(CI, B, 3);
1717
1718   Function *Callee = CI->getCalledFunction();
1719   // Require a pointer, an integer, an integer, a pointer, returning integer.
1720   FunctionType *FT = Callee->getFunctionType();
1721   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1722       !FT->getParamType(1)->isIntegerTy() ||
1723       !FT->getParamType(2)->isIntegerTy() ||
1724       !FT->getParamType(3)->isPointerTy() ||
1725       !FT->getReturnType()->isIntegerTy())
1726     return nullptr;
1727
1728   // Get the element size and count.
1729   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1730   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1731   if (!SizeC || !CountC)
1732     return nullptr;
1733   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1734
1735   // If this is writing zero records, remove the call (it's a noop).
1736   if (Bytes == 0)
1737     return ConstantInt::get(CI->getType(), 0);
1738
1739   // If this is writing one byte, turn it into fputc.
1740   // This optimisation is only valid, if the return value is unused.
1741   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1742     Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1743     Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1744     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1745   }
1746
1747   return nullptr;
1748 }
1749
1750 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1751   optimizeErrorReporting(CI, B, 1);
1752
1753   Function *Callee = CI->getCalledFunction();
1754
1755   // Require two pointers.  Also, we can't optimize if return value is used.
1756   FunctionType *FT = Callee->getFunctionType();
1757   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1758       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1759     return nullptr;
1760
1761   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1762   uint64_t Len = GetStringLength(CI->getArgOperand(0));
1763   if (!Len)
1764     return nullptr;
1765
1766   // Known to have no uses (see above).
1767   return EmitFWrite(
1768       CI->getArgOperand(0),
1769       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1770       CI->getArgOperand(1), B, DL, TLI);
1771 }
1772
1773 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1774   Function *Callee = CI->getCalledFunction();
1775   // Require one fixed pointer argument and an integer/void result.
1776   FunctionType *FT = Callee->getFunctionType();
1777   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1778       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1779     return nullptr;
1780
1781   // Check for a constant string.
1782   StringRef Str;
1783   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1784     return nullptr;
1785
1786   if (Str.empty() && CI->use_empty()) {
1787     // puts("") -> putchar('\n')
1788     Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1789     if (CI->use_empty() || !Res)
1790       return Res;
1791     return B.CreateIntCast(Res, CI->getType(), true);
1792   }
1793
1794   return nullptr;
1795 }
1796
1797 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1798   LibFunc::Func Func;
1799   SmallString<20> FloatFuncName = FuncName;
1800   FloatFuncName += 'f';
1801   if (TLI->getLibFunc(FloatFuncName, Func))
1802     return TLI->has(Func);
1803   return false;
1804 }
1805
1806 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1807                                                       IRBuilder<> &Builder) {
1808   LibFunc::Func Func;
1809   Function *Callee = CI->getCalledFunction();
1810   StringRef FuncName = Callee->getName();
1811
1812   // Check for string/memory library functions.
1813   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1814     // Make sure we never change the calling convention.
1815     assert((ignoreCallingConv(Func) ||
1816             CI->getCallingConv() == llvm::CallingConv::C) &&
1817       "Optimizing string/memory libcall would change the calling convention");
1818     switch (Func) {
1819     case LibFunc::strcat:
1820       return optimizeStrCat(CI, Builder);
1821     case LibFunc::strncat:
1822       return optimizeStrNCat(CI, Builder);
1823     case LibFunc::strchr:
1824       return optimizeStrChr(CI, Builder);
1825     case LibFunc::strrchr:
1826       return optimizeStrRChr(CI, Builder);
1827     case LibFunc::strcmp:
1828       return optimizeStrCmp(CI, Builder);
1829     case LibFunc::strncmp:
1830       return optimizeStrNCmp(CI, Builder);
1831     case LibFunc::strcpy:
1832       return optimizeStrCpy(CI, Builder);
1833     case LibFunc::stpcpy:
1834       return optimizeStpCpy(CI, Builder);
1835     case LibFunc::strncpy:
1836       return optimizeStrNCpy(CI, Builder);
1837     case LibFunc::strlen:
1838       return optimizeStrLen(CI, Builder);
1839     case LibFunc::strpbrk:
1840       return optimizeStrPBrk(CI, Builder);
1841     case LibFunc::strtol:
1842     case LibFunc::strtod:
1843     case LibFunc::strtof:
1844     case LibFunc::strtoul:
1845     case LibFunc::strtoll:
1846     case LibFunc::strtold:
1847     case LibFunc::strtoull:
1848       return optimizeStrTo(CI, Builder);
1849     case LibFunc::strspn:
1850       return optimizeStrSpn(CI, Builder);
1851     case LibFunc::strcspn:
1852       return optimizeStrCSpn(CI, Builder);
1853     case LibFunc::strstr:
1854       return optimizeStrStr(CI, Builder);
1855     case LibFunc::memcmp:
1856       return optimizeMemCmp(CI, Builder);
1857     case LibFunc::memcpy:
1858       return optimizeMemCpy(CI, Builder);
1859     case LibFunc::memmove:
1860       return optimizeMemMove(CI, Builder);
1861     case LibFunc::memset:
1862       return optimizeMemSet(CI, Builder);
1863     default:
1864       break;
1865     }
1866   }
1867   return nullptr;
1868 }
1869
1870 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1871   if (CI->isNoBuiltin())
1872     return nullptr;
1873
1874   LibFunc::Func Func;
1875   Function *Callee = CI->getCalledFunction();
1876   StringRef FuncName = Callee->getName();
1877   IRBuilder<> Builder(CI);
1878   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1879
1880   // Command-line parameter overrides function attribute.
1881   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1882     UnsafeFPShrink = EnableUnsafeFPShrink;
1883   else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1884     // FIXME: This is the same problem as described in optimizeSqrt().
1885     // If calls gain access to IR-level FMF, then use that instead of a
1886     // function attribute.
1887
1888     // Check for unsafe-fp-math = true.
1889     Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1890     if (Attr.getValueAsString() == "true")
1891       UnsafeFPShrink = true;
1892   }
1893
1894   // First, check for intrinsics.
1895   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1896     if (!isCallingConvC)
1897       return nullptr;
1898     switch (II->getIntrinsicID()) {
1899     case Intrinsic::pow:
1900       return optimizePow(CI, Builder);
1901     case Intrinsic::exp2:
1902       return optimizeExp2(CI, Builder);
1903     case Intrinsic::fabs:
1904       return optimizeFabs(CI, Builder);
1905     case Intrinsic::sqrt:
1906       return optimizeSqrt(CI, Builder);
1907     default:
1908       return nullptr;
1909     }
1910   }
1911
1912   // Also try to simplify calls to fortified library functions.
1913   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1914     // Try to further simplify the result.
1915     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
1916     if (SimplifiedCI && SimplifiedCI->getCalledFunction())
1917       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
1918         // If we were able to further simplify, remove the now redundant call.
1919         SimplifiedCI->replaceAllUsesWith(V);
1920         SimplifiedCI->eraseFromParent();
1921         return V;
1922       }
1923     return SimplifiedFortifiedCI;
1924   }
1925
1926   // Then check for known library functions.
1927   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1928     // We never change the calling convention.
1929     if (!ignoreCallingConv(Func) && !isCallingConvC)
1930       return nullptr;
1931     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
1932       return V;
1933     switch (Func) {
1934     case LibFunc::cosf:
1935     case LibFunc::cos:
1936     case LibFunc::cosl:
1937       return optimizeCos(CI, Builder);
1938     case LibFunc::sinpif:
1939     case LibFunc::sinpi:
1940     case LibFunc::cospif:
1941     case LibFunc::cospi:
1942       return optimizeSinCosPi(CI, Builder);
1943     case LibFunc::powf:
1944     case LibFunc::pow:
1945     case LibFunc::powl:
1946       return optimizePow(CI, Builder);
1947     case LibFunc::exp2l:
1948     case LibFunc::exp2:
1949     case LibFunc::exp2f:
1950       return optimizeExp2(CI, Builder);
1951     case LibFunc::fabsf:
1952     case LibFunc::fabs:
1953     case LibFunc::fabsl:
1954       return optimizeFabs(CI, Builder);
1955     case LibFunc::sqrtf:
1956     case LibFunc::sqrt:
1957     case LibFunc::sqrtl:
1958       return optimizeSqrt(CI, Builder);
1959     case LibFunc::ffs:
1960     case LibFunc::ffsl:
1961     case LibFunc::ffsll:
1962       return optimizeFFS(CI, Builder);
1963     case LibFunc::abs:
1964     case LibFunc::labs:
1965     case LibFunc::llabs:
1966       return optimizeAbs(CI, Builder);
1967     case LibFunc::isdigit:
1968       return optimizeIsDigit(CI, Builder);
1969     case LibFunc::isascii:
1970       return optimizeIsAscii(CI, Builder);
1971     case LibFunc::toascii:
1972       return optimizeToAscii(CI, Builder);
1973     case LibFunc::printf:
1974       return optimizePrintF(CI, Builder);
1975     case LibFunc::sprintf:
1976       return optimizeSPrintF(CI, Builder);
1977     case LibFunc::fprintf:
1978       return optimizeFPrintF(CI, Builder);
1979     case LibFunc::fwrite:
1980       return optimizeFWrite(CI, Builder);
1981     case LibFunc::fputs:
1982       return optimizeFPuts(CI, Builder);
1983     case LibFunc::puts:
1984       return optimizePuts(CI, Builder);
1985     case LibFunc::perror:
1986       return optimizeErrorReporting(CI, Builder);
1987     case LibFunc::vfprintf:
1988     case LibFunc::fiprintf:
1989       return optimizeErrorReporting(CI, Builder, 0);
1990     case LibFunc::fputc:
1991       return optimizeErrorReporting(CI, Builder, 1);
1992     case LibFunc::ceil:
1993     case LibFunc::floor:
1994     case LibFunc::rint:
1995     case LibFunc::round:
1996     case LibFunc::nearbyint:
1997     case LibFunc::trunc:
1998       if (hasFloatVersion(FuncName))
1999         return optimizeUnaryDoubleFP(CI, Builder, false);
2000       return nullptr;
2001     case LibFunc::acos:
2002     case LibFunc::acosh:
2003     case LibFunc::asin:
2004     case LibFunc::asinh:
2005     case LibFunc::atan:
2006     case LibFunc::atanh:
2007     case LibFunc::cbrt:
2008     case LibFunc::cosh:
2009     case LibFunc::exp:
2010     case LibFunc::exp10:
2011     case LibFunc::expm1:
2012     case LibFunc::log:
2013     case LibFunc::log10:
2014     case LibFunc::log1p:
2015     case LibFunc::log2:
2016     case LibFunc::logb:
2017     case LibFunc::sin:
2018     case LibFunc::sinh:
2019     case LibFunc::tan:
2020     case LibFunc::tanh:
2021       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2022         return optimizeUnaryDoubleFP(CI, Builder, true);
2023       return nullptr;
2024     case LibFunc::copysign:
2025     case LibFunc::fmin:
2026     case LibFunc::fmax:
2027       if (hasFloatVersion(FuncName))
2028         return optimizeBinaryDoubleFP(CI, Builder);
2029       return nullptr;
2030     default:
2031       return nullptr;
2032     }
2033   }
2034   return nullptr;
2035 }
2036
2037 LibCallSimplifier::LibCallSimplifier(
2038     const DataLayout &DL, const TargetLibraryInfo *TLI,
2039     function_ref<void(Instruction *, Value *)> Replacer)
2040     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2041       Replacer(Replacer) {}
2042
2043 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2044   // Indirect through the replacer used in this instance.
2045   Replacer(I, With);
2046 }
2047
2048 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2049                                                              Value *With) {
2050   I->replaceAllUsesWith(With);
2051   I->eraseFromParent();
2052 }
2053
2054 // TODO:
2055 //   Additional cases that we need to add to this file:
2056 //
2057 // cbrt:
2058 //   * cbrt(expN(X))  -> expN(x/3)
2059 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2060 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2061 //
2062 // exp, expf, expl:
2063 //   * exp(log(x))  -> x
2064 //
2065 // log, logf, logl:
2066 //   * log(exp(x))   -> x
2067 //   * log(x**y)     -> y*log(x)
2068 //   * log(exp(y))   -> y*log(e)
2069 //   * log(exp2(y))  -> y*log(2)
2070 //   * log(exp10(y)) -> y*log(10)
2071 //   * log(sqrt(x))  -> 0.5*log(x)
2072 //   * log(pow(x,y)) -> y*log(x)
2073 //
2074 // lround, lroundf, lroundl:
2075 //   * lround(cnst) -> cnst'
2076 //
2077 // pow, powf, powl:
2078 //   * pow(exp(x),y)  -> exp(x*y)
2079 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2080 //   * pow(pow(x,y),z)-> pow(x,y*z)
2081 //
2082 // round, roundf, roundl:
2083 //   * round(cnst) -> cnst'
2084 //
2085 // signbit:
2086 //   * signbit(cnst) -> cnst'
2087 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2088 //
2089 // sqrt, sqrtf, sqrtl:
2090 //   * sqrt(expN(x))  -> expN(x*0.5)
2091 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2092 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2093 //
2094 // tan, tanf, tanl:
2095 //   * tan(atan(x)) -> x
2096 //
2097 // trunc, truncf, truncl:
2098 //   * trunc(cnst) -> cnst'
2099 //
2100 //
2101
2102 //===----------------------------------------------------------------------===//
2103 // Fortified Library Call Optimizations
2104 //===----------------------------------------------------------------------===//
2105
2106 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2107                                                          unsigned ObjSizeOp,
2108                                                          unsigned SizeOp,
2109                                                          bool isString) {
2110   if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2111     return true;
2112   if (ConstantInt *ObjSizeCI =
2113           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2114     if (ObjSizeCI->isAllOnesValue())
2115       return true;
2116     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2117     if (OnlyLowerUnknownSize)
2118       return false;
2119     if (isString) {
2120       uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2121       // If the length is 0 we don't know how long it is and so we can't
2122       // remove the check.
2123       if (Len == 0)
2124         return false;
2125       return ObjSizeCI->getZExtValue() >= Len;
2126     }
2127     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2128       return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2129   }
2130   return false;
2131 }
2132
2133 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2134   Function *Callee = CI->getCalledFunction();
2135
2136   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2137     return nullptr;
2138
2139   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2140     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2141                    CI->getArgOperand(2), 1);
2142     return CI->getArgOperand(0);
2143   }
2144   return nullptr;
2145 }
2146
2147 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2148   Function *Callee = CI->getCalledFunction();
2149
2150   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2151     return nullptr;
2152
2153   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2154     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2155                     CI->getArgOperand(2), 1);
2156     return CI->getArgOperand(0);
2157   }
2158   return nullptr;
2159 }
2160
2161 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2162   Function *Callee = CI->getCalledFunction();
2163
2164   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2165     return nullptr;
2166
2167   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2168     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2169     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2170     return CI->getArgOperand(0);
2171   }
2172   return nullptr;
2173 }
2174
2175 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2176                                                       IRBuilder<> &B,
2177                                                       LibFunc::Func Func) {
2178   Function *Callee = CI->getCalledFunction();
2179   StringRef Name = Callee->getName();
2180   const DataLayout &DL = CI->getModule()->getDataLayout();
2181
2182   if (!checkStringCopyLibFuncSignature(Callee, Func))
2183     return nullptr;
2184
2185   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2186         *ObjSize = CI->getArgOperand(2);
2187
2188   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
2189   if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2190     Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2191     return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2192   }
2193
2194   // If a) we don't have any length information, or b) we know this will
2195   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2196   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2197   // TODO: It might be nice to get a maximum length out of the possible
2198   // string lengths for varying.
2199   if (isFortifiedCallFoldable(CI, 2, 1, true)) {
2200     Value *Ret = EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2201     return Ret;
2202   } else if (!OnlyLowerUnknownSize) {
2203     // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2204     uint64_t Len = GetStringLength(Src);
2205     if (Len == 0)
2206       return nullptr;
2207
2208     Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2209     Value *LenV = ConstantInt::get(SizeTTy, Len);
2210     Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2211     // If the function was an __stpcpy_chk, and we were able to fold it into
2212     // a __memcpy_chk, we still need to return the correct end pointer.
2213     if (Ret && Func == LibFunc::stpcpy_chk)
2214       return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2215     return Ret;
2216   }
2217   return nullptr;
2218 }
2219
2220 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2221                                                        IRBuilder<> &B,
2222                                                        LibFunc::Func Func) {
2223   Function *Callee = CI->getCalledFunction();
2224   StringRef Name = Callee->getName();
2225
2226   if (!checkStringCopyLibFuncSignature(Callee, Func))
2227     return nullptr;
2228   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2229     Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2230                              CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2231     return Ret;
2232   }
2233   return nullptr;
2234 }
2235
2236 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2237   if (CI->isNoBuiltin())
2238     return nullptr;
2239
2240   LibFunc::Func Func;
2241   Function *Callee = CI->getCalledFunction();
2242   StringRef FuncName = Callee->getName();
2243   IRBuilder<> Builder(CI);
2244   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2245
2246   // First, check that this is a known library functions.
2247   if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2248     return nullptr;
2249
2250   // We never change the calling convention.
2251   if (!ignoreCallingConv(Func) && !isCallingConvC)
2252     return nullptr;
2253
2254   switch (Func) {
2255   case LibFunc::memcpy_chk:
2256     return optimizeMemCpyChk(CI, Builder);
2257   case LibFunc::memmove_chk:
2258     return optimizeMemMoveChk(CI, Builder);
2259   case LibFunc::memset_chk:
2260     return optimizeMemSetChk(CI, Builder);
2261   case LibFunc::stpcpy_chk:
2262   case LibFunc::strcpy_chk:
2263     return optimizeStrpCpyChk(CI, Builder, Func);
2264   case LibFunc::stpncpy_chk:
2265   case LibFunc::strncpy_chk:
2266     return optimizeStrpNCpyChk(CI, Builder, Func);
2267   default:
2268     break;
2269   }
2270   return nullptr;
2271 }
2272
2273 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2274     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2275     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}