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