xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp (revision ccb59683b98360afaf5b5bb641a68fea22c68d0b)
1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the library calls simplifier. It does not implement
10 // any pass, but can't be used by other passes to do simplifications.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Transforms/Utils/BuildLibCalls.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/SizeOpts.h"
35 
36 using namespace llvm;
37 using namespace PatternMatch;
38 
39 static cl::opt<bool>
40     EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
41                          cl::init(false),
42                          cl::desc("Enable unsafe double to float "
43                                   "shrinking for math lib calls"));
44 
45 //===----------------------------------------------------------------------===//
46 // Helper Functions
47 //===----------------------------------------------------------------------===//
48 
49 static bool ignoreCallingConv(LibFunc Func) {
50   return Func == LibFunc_abs || Func == LibFunc_labs ||
51          Func == LibFunc_llabs || Func == LibFunc_strlen;
52 }
53 
54 /// Return true if it is only used in equality comparisons with With.
55 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
56   for (User *U : V->users()) {
57     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
58       if (IC->isEquality() && IC->getOperand(1) == With)
59         continue;
60     // Unknown instruction.
61     return false;
62   }
63   return true;
64 }
65 
66 static bool callHasFloatingPointArgument(const CallInst *CI) {
67   return any_of(CI->operands(), [](const Use &OI) {
68     return OI->getType()->isFloatingPointTy();
69   });
70 }
71 
72 static bool callHasFP128Argument(const CallInst *CI) {
73   return any_of(CI->operands(), [](const Use &OI) {
74     return OI->getType()->isFP128Ty();
75   });
76 }
77 
78 // Convert the entire string Str representing an integer in Base, up to
79 // the terminating nul if present, to a constant according to the rules
80 // of strtoul[l] or, when AsSigned is set, of strtol[l].  On success
81 // return the result, otherwise null.
82 // The function assumes the string is encoded in ASCII and carefully
83 // avoids converting sequences (including "") that the corresponding
84 // library call might fail and set errno for.
85 static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
86                               uint64_t Base, bool AsSigned, IRBuilderBase &B) {
87   if (Base < 2 || Base > 36)
88     if (Base != 0)
89       // Fail for an invalid base (required by POSIX).
90       return nullptr;
91 
92   // Current offset into the original string to reflect in EndPtr.
93   size_t Offset = 0;
94   // Strip leading whitespace.
95   for ( ; Offset != Str.size(); ++Offset)
96     if (!isSpace((unsigned char)Str[Offset])) {
97       Str = Str.substr(Offset);
98       break;
99     }
100 
101   if (Str.empty())
102     // Fail for empty subject sequences (POSIX allows but doesn't require
103     // strtol[l]/strtoul[l] to fail with EINVAL).
104     return nullptr;
105 
106   // Strip but remember the sign.
107   bool Negate = Str[0] == '-';
108   if (Str[0] == '-' || Str[0] == '+') {
109     Str = Str.drop_front();
110     if (Str.empty())
111       // Fail for a sign with nothing after it.
112       return nullptr;
113     ++Offset;
114   }
115 
116   // Set Max to the absolute value of the minimum (for signed), or
117   // to the maximum (for unsigned) value representable in the type.
118   Type *RetTy = CI->getType();
119   unsigned NBits = RetTy->getPrimitiveSizeInBits();
120   uint64_t Max = AsSigned && Negate ? 1 : 0;
121   Max += AsSigned ? maxIntN(NBits) : maxUIntN(NBits);
122 
123   // Autodetect Base if it's zero and consume the "0x" prefix.
124   if (Str.size() > 1) {
125     if (Str[0] == '0') {
126       if (toUpper((unsigned char)Str[1]) == 'X') {
127         if (Str.size() == 2 || (Base && Base != 16))
128           // Fail if Base doesn't allow the "0x" prefix or for the prefix
129           // alone that implementations like BSD set errno to EINVAL for.
130           return nullptr;
131 
132         Str = Str.drop_front(2);
133         Offset += 2;
134         Base = 16;
135       }
136       else if (Base == 0)
137         Base = 8;
138     } else if (Base == 0)
139       Base = 10;
140   }
141   else if (Base == 0)
142     Base = 10;
143 
144   // Convert the rest of the subject sequence, not including the sign,
145   // to its uint64_t representation (this assumes the source character
146   // set is ASCII).
147   uint64_t Result = 0;
148   for (unsigned i = 0; i != Str.size(); ++i) {
149     unsigned char DigVal = Str[i];
150     if (isDigit(DigVal))
151       DigVal = DigVal - '0';
152     else {
153       DigVal = toUpper(DigVal);
154       if (isAlpha(DigVal))
155         DigVal = DigVal - 'A' + 10;
156       else
157         return nullptr;
158     }
159 
160     if (DigVal >= Base)
161       // Fail if the digit is not valid in the Base.
162       return nullptr;
163 
164     // Add the digit and fail if the result is not representable in
165     // the (unsigned form of the) destination type.
166     bool VFlow;
167     Result = SaturatingMultiplyAdd(Result, Base, (uint64_t)DigVal, &VFlow);
168     if (VFlow || Result > Max)
169       return nullptr;
170   }
171 
172   if (EndPtr) {
173     // Store the pointer to the end.
174     Value *Off = B.getInt64(Offset + Str.size());
175     Value *StrBeg = CI->getArgOperand(0);
176     Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr");
177     B.CreateStore(StrEnd, EndPtr);
178   }
179 
180   if (Negate)
181     // Unsigned negation doesn't overflow.
182     Result = -Result;
183 
184   return ConstantInt::get(RetTy, Result);
185 }
186 
187 static bool isOnlyUsedInComparisonWithZero(Value *V) {
188   for (User *U : V->users()) {
189     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
190       if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
191         if (C->isNullValue())
192           continue;
193     // Unknown instruction.
194     return false;
195   }
196   return true;
197 }
198 
199 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
200                                  const DataLayout &DL) {
201   if (!isOnlyUsedInComparisonWithZero(CI))
202     return false;
203 
204   if (!isDereferenceableAndAlignedPointer(Str, Align(1), APInt(64, Len), DL))
205     return false;
206 
207   if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
208     return false;
209 
210   return true;
211 }
212 
213 static void annotateDereferenceableBytes(CallInst *CI,
214                                          ArrayRef<unsigned> ArgNos,
215                                          uint64_t DereferenceableBytes) {
216   const Function *F = CI->getCaller();
217   if (!F)
218     return;
219   for (unsigned ArgNo : ArgNos) {
220     uint64_t DerefBytes = DereferenceableBytes;
221     unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
222     if (!llvm::NullPointerIsDefined(F, AS) ||
223         CI->paramHasAttr(ArgNo, Attribute::NonNull))
224       DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo),
225                             DereferenceableBytes);
226 
227     if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) {
228       CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
229       if (!llvm::NullPointerIsDefined(F, AS) ||
230           CI->paramHasAttr(ArgNo, Attribute::NonNull))
231         CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
232       CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes(
233                                   CI->getContext(), DerefBytes));
234     }
235   }
236 }
237 
238 static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI,
239                                          ArrayRef<unsigned> ArgNos) {
240   Function *F = CI->getCaller();
241   if (!F)
242     return;
243 
244   for (unsigned ArgNo : ArgNos) {
245     if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef))
246       CI->addParamAttr(ArgNo, Attribute::NoUndef);
247 
248     if (CI->paramHasAttr(ArgNo, Attribute::NonNull))
249       continue;
250     unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
251     if (llvm::NullPointerIsDefined(F, AS))
252       continue;
253 
254     CI->addParamAttr(ArgNo, Attribute::NonNull);
255     annotateDereferenceableBytes(CI, ArgNo, 1);
256   }
257 }
258 
259 static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos,
260                                Value *Size, const DataLayout &DL) {
261   if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) {
262     annotateNonNullNoUndefBasedOnAccess(CI, ArgNos);
263     annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
264   } else if (isKnownNonZero(Size, DL)) {
265     annotateNonNullNoUndefBasedOnAccess(CI, ArgNos);
266     const APInt *X, *Y;
267     uint64_t DerefMin = 1;
268     if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) {
269       DerefMin = std::min(X->getZExtValue(), Y->getZExtValue());
270       annotateDereferenceableBytes(CI, ArgNos, DerefMin);
271     }
272   }
273 }
274 
275 // Copy CallInst "flags" like musttail, notail, and tail. Return New param for
276 // easier chaining. Calls to emit* and B.createCall should probably be wrapped
277 // in this function when New is created to replace Old. Callers should take
278 // care to check Old.isMustTailCall() if they aren't replacing Old directly
279 // with New.
280 static Value *copyFlags(const CallInst &Old, Value *New) {
281   assert(!Old.isMustTailCall() && "do not copy musttail call flags");
282   assert(!Old.isNoTailCall() && "do not copy notail call flags");
283   if (auto *NewCI = dyn_cast_or_null<CallInst>(New))
284     NewCI->setTailCallKind(Old.getTailCallKind());
285   return New;
286 }
287 
288 // Helper to avoid truncating the length if size_t is 32-bits.
289 static StringRef substr(StringRef Str, uint64_t Len) {
290   return Len >= Str.size() ? Str : Str.substr(0, Len);
291 }
292 
293 //===----------------------------------------------------------------------===//
294 // String and Memory Library Call Optimizations
295 //===----------------------------------------------------------------------===//
296 
297 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) {
298   // Extract some information from the instruction
299   Value *Dst = CI->getArgOperand(0);
300   Value *Src = CI->getArgOperand(1);
301   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
302 
303   // See if we can get the length of the input string.
304   uint64_t Len = GetStringLength(Src);
305   if (Len)
306     annotateDereferenceableBytes(CI, 1, Len);
307   else
308     return nullptr;
309   --Len; // Unbias length.
310 
311   // Handle the simple, do-nothing case: strcat(x, "") -> x
312   if (Len == 0)
313     return Dst;
314 
315   return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B));
316 }
317 
318 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
319                                            IRBuilderBase &B) {
320   // We need to find the end of the destination string.  That's where the
321   // memory is to be moved to. We just generate a call to strlen.
322   Value *DstLen = emitStrLen(Dst, B, DL, TLI);
323   if (!DstLen)
324     return nullptr;
325 
326   // Now that we have the destination's length, we must index into the
327   // destination's pointer to get the actual memcpy destination (end of
328   // the string .. we're concatenating).
329   Value *CpyDst = B.CreateInBoundsGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
330 
331   // We have enough information to now generate the memcpy call to do the
332   // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
333   B.CreateMemCpy(
334       CpyDst, Align(1), Src, Align(1),
335       ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
336   return Dst;
337 }
338 
339 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) {
340   // Extract some information from the instruction.
341   Value *Dst = CI->getArgOperand(0);
342   Value *Src = CI->getArgOperand(1);
343   Value *Size = CI->getArgOperand(2);
344   uint64_t Len;
345   annotateNonNullNoUndefBasedOnAccess(CI, 0);
346   if (isKnownNonZero(Size, DL))
347     annotateNonNullNoUndefBasedOnAccess(CI, 1);
348 
349   // We don't do anything if length is not constant.
350   ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
351   if (LengthArg) {
352     Len = LengthArg->getZExtValue();
353     // strncat(x, c, 0) -> x
354     if (!Len)
355       return Dst;
356   } else {
357     return nullptr;
358   }
359 
360   // See if we can get the length of the input string.
361   uint64_t SrcLen = GetStringLength(Src);
362   if (SrcLen) {
363     annotateDereferenceableBytes(CI, 1, SrcLen);
364     --SrcLen; // Unbias length.
365   } else {
366     return nullptr;
367   }
368 
369   // strncat(x, "", c) -> x
370   if (SrcLen == 0)
371     return Dst;
372 
373   // We don't optimize this case.
374   if (Len < SrcLen)
375     return nullptr;
376 
377   // strncat(x, s, c) -> strcat(x, s)
378   // s is constant so the strcat can be optimized further.
379   return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B));
380 }
381 
382 // Helper to transform memchr(S, C, N) == S to N && *S == C and, when
383 // NBytes is null, strchr(S, C) to *S == C.  A precondition of the function
384 // is that either S is dereferenceable or the value of N is nonzero.
385 static Value* memChrToCharCompare(CallInst *CI, Value *NBytes,
386                                   IRBuilderBase &B, const DataLayout &DL)
387 {
388   Value *Src = CI->getArgOperand(0);
389   Value *CharVal = CI->getArgOperand(1);
390 
391   // Fold memchr(A, C, N) == A to N && *A == C.
392   Type *CharTy = B.getInt8Ty();
393   Value *Char0 = B.CreateLoad(CharTy, Src);
394   CharVal = B.CreateTrunc(CharVal, CharTy);
395   Value *Cmp = B.CreateICmpEQ(Char0, CharVal, "char0cmp");
396 
397   if (NBytes) {
398     Value *Zero = ConstantInt::get(NBytes->getType(), 0);
399     Value *And = B.CreateICmpNE(NBytes, Zero);
400     Cmp = B.CreateLogicalAnd(And, Cmp);
401   }
402 
403   Value *NullPtr = Constant::getNullValue(CI->getType());
404   return B.CreateSelect(Cmp, Src, NullPtr);
405 }
406 
407 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) {
408   Value *SrcStr = CI->getArgOperand(0);
409   Value *CharVal = CI->getArgOperand(1);
410   annotateNonNullNoUndefBasedOnAccess(CI, 0);
411 
412   if (isOnlyUsedInEqualityComparison(CI, SrcStr))
413     return memChrToCharCompare(CI, nullptr, B, DL);
414 
415   // If the second operand is non-constant, see if we can compute the length
416   // of the input string and turn this into memchr.
417   ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
418   if (!CharC) {
419     uint64_t Len = GetStringLength(SrcStr);
420     if (Len)
421       annotateDereferenceableBytes(CI, 0, Len);
422     else
423       return nullptr;
424 
425     Function *Callee = CI->getCalledFunction();
426     FunctionType *FT = Callee->getFunctionType();
427     if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
428       return nullptr;
429 
430     return copyFlags(
431         *CI,
432         emitMemChr(SrcStr, CharVal, // include nul.
433                    ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), B,
434                    DL, TLI));
435   }
436 
437   if (CharC->isZero()) {
438     Value *NullPtr = Constant::getNullValue(CI->getType());
439     if (isOnlyUsedInEqualityComparison(CI, NullPtr))
440       // Pre-empt the transformation to strlen below and fold
441       // strchr(A, '\0') == null to false.
442       return B.CreateIntToPtr(B.getTrue(), CI->getType());
443   }
444 
445   // Otherwise, the character is a constant, see if the first argument is
446   // a string literal.  If so, we can constant fold.
447   StringRef Str;
448   if (!getConstantStringInfo(SrcStr, Str)) {
449     if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
450       if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI))
451         return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr");
452     return nullptr;
453   }
454 
455   // Compute the offset, make sure to handle the case when we're searching for
456   // zero (a weird way to spell strlen).
457   size_t I = (0xFF & CharC->getSExtValue()) == 0
458                  ? Str.size()
459                  : Str.find(CharC->getSExtValue());
460   if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
461     return Constant::getNullValue(CI->getType());
462 
463   // strchr(s+n,c)  -> gep(s+n+i,c)
464   return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
465 }
466 
467 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) {
468   Value *SrcStr = CI->getArgOperand(0);
469   Value *CharVal = CI->getArgOperand(1);
470   ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
471   annotateNonNullNoUndefBasedOnAccess(CI, 0);
472 
473   StringRef Str;
474   if (!getConstantStringInfo(SrcStr, Str)) {
475     // strrchr(s, 0) -> strchr(s, 0)
476     if (CharC && CharC->isZero())
477       return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI));
478     return nullptr;
479   }
480 
481   // Try to expand strrchr to the memrchr nonstandard extension if it's
482   // available, or simply fail otherwise.
483   uint64_t NBytes = Str.size() + 1;   // Include the terminating nul.
484   Type *IntPtrType = DL.getIntPtrType(CI->getContext());
485   Value *Size = ConstantInt::get(IntPtrType, NBytes);
486   return copyFlags(*CI, emitMemRChr(SrcStr, CharVal, Size, B, DL, TLI));
487 }
488 
489 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
490   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
491   if (Str1P == Str2P) // strcmp(x,x)  -> 0
492     return ConstantInt::get(CI->getType(), 0);
493 
494   StringRef Str1, Str2;
495   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
496   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
497 
498   // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
499   if (HasStr1 && HasStr2)
500     return ConstantInt::get(CI->getType(), Str1.compare(Str2));
501 
502   if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
503     return B.CreateNeg(B.CreateZExt(
504         B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
505 
506   if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
507     return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
508                         CI->getType());
509 
510   // strcmp(P, "x") -> memcmp(P, "x", 2)
511   uint64_t Len1 = GetStringLength(Str1P);
512   if (Len1)
513     annotateDereferenceableBytes(CI, 0, Len1);
514   uint64_t Len2 = GetStringLength(Str2P);
515   if (Len2)
516     annotateDereferenceableBytes(CI, 1, Len2);
517 
518   if (Len1 && Len2) {
519     return copyFlags(
520         *CI, emitMemCmp(Str1P, Str2P,
521                         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
522                                          std::min(Len1, Len2)),
523                         B, DL, TLI));
524   }
525 
526   // strcmp to memcmp
527   if (!HasStr1 && HasStr2) {
528     if (canTransformToMemCmp(CI, Str1P, Len2, DL))
529       return copyFlags(
530           *CI,
531           emitMemCmp(Str1P, Str2P,
532                      ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2),
533                      B, DL, TLI));
534   } else if (HasStr1 && !HasStr2) {
535     if (canTransformToMemCmp(CI, Str2P, Len1, DL))
536       return copyFlags(
537           *CI,
538           emitMemCmp(Str1P, Str2P,
539                      ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1),
540                      B, DL, TLI));
541   }
542 
543   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
544   return nullptr;
545 }
546 
547 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
548 // arrays LHS and RHS and nonconstant Size.
549 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS,
550                                     Value *Size, bool StrNCmp,
551                                     IRBuilderBase &B, const DataLayout &DL);
552 
553 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
554   Value *Str1P = CI->getArgOperand(0);
555   Value *Str2P = CI->getArgOperand(1);
556   Value *Size = CI->getArgOperand(2);
557   if (Str1P == Str2P) // strncmp(x,x,n)  -> 0
558     return ConstantInt::get(CI->getType(), 0);
559 
560   if (isKnownNonZero(Size, DL))
561     annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
562   // Get the length argument if it is constant.
563   uint64_t Length;
564   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
565     Length = LengthArg->getZExtValue();
566   else
567     return optimizeMemCmpVarSize(CI, Str1P, Str2P, Size, true, B, DL);
568 
569   if (Length == 0) // strncmp(x,y,0)   -> 0
570     return ConstantInt::get(CI->getType(), 0);
571 
572   if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
573     return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI));
574 
575   StringRef Str1, Str2;
576   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
577   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
578 
579   // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
580   if (HasStr1 && HasStr2) {
581     // Avoid truncating the 64-bit Length to 32 bits in ILP32.
582     StringRef SubStr1 = substr(Str1, Length);
583     StringRef SubStr2 = substr(Str2, Length);
584     return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
585   }
586 
587   if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
588     return B.CreateNeg(B.CreateZExt(
589         B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
590 
591   if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
592     return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
593                         CI->getType());
594 
595   uint64_t Len1 = GetStringLength(Str1P);
596   if (Len1)
597     annotateDereferenceableBytes(CI, 0, Len1);
598   uint64_t Len2 = GetStringLength(Str2P);
599   if (Len2)
600     annotateDereferenceableBytes(CI, 1, Len2);
601 
602   // strncmp to memcmp
603   if (!HasStr1 && HasStr2) {
604     Len2 = std::min(Len2, Length);
605     if (canTransformToMemCmp(CI, Str1P, Len2, DL))
606       return copyFlags(
607           *CI,
608           emitMemCmp(Str1P, Str2P,
609                      ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2),
610                      B, DL, TLI));
611   } else if (HasStr1 && !HasStr2) {
612     Len1 = std::min(Len1, Length);
613     if (canTransformToMemCmp(CI, Str2P, Len1, DL))
614       return copyFlags(
615           *CI,
616           emitMemCmp(Str1P, Str2P,
617                      ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1),
618                      B, DL, TLI));
619   }
620 
621   return nullptr;
622 }
623 
624 Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) {
625   Value *Src = CI->getArgOperand(0);
626   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
627   uint64_t SrcLen = GetStringLength(Src);
628   if (SrcLen && Size) {
629     annotateDereferenceableBytes(CI, 0, SrcLen);
630     if (SrcLen <= Size->getZExtValue() + 1)
631       return copyFlags(*CI, emitStrDup(Src, B, TLI));
632   }
633 
634   return nullptr;
635 }
636 
637 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) {
638   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
639   if (Dst == Src) // strcpy(x,x)  -> x
640     return Src;
641 
642   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
643   // See if we can get the length of the input string.
644   uint64_t Len = GetStringLength(Src);
645   if (Len)
646     annotateDereferenceableBytes(CI, 1, Len);
647   else
648     return nullptr;
649 
650   // We have enough information to now generate the memcpy call to do the
651   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
652   CallInst *NewCI =
653       B.CreateMemCpy(Dst, Align(1), Src, Align(1),
654                      ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
655   NewCI->setAttributes(CI->getAttributes());
656   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
657   copyFlags(*CI, NewCI);
658   return Dst;
659 }
660 
661 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) {
662   Function *Callee = CI->getCalledFunction();
663   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
664 
665   // stpcpy(d,s) -> strcpy(d,s) if the result is not used.
666   if (CI->use_empty())
667     return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
668 
669   if (Dst == Src) { // stpcpy(x,x)  -> x+strlen(x)
670     Value *StrLen = emitStrLen(Src, B, DL, TLI);
671     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
672   }
673 
674   // See if we can get the length of the input string.
675   uint64_t Len = GetStringLength(Src);
676   if (Len)
677     annotateDereferenceableBytes(CI, 1, Len);
678   else
679     return nullptr;
680 
681   Type *PT = Callee->getFunctionType()->getParamType(0);
682   Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
683   Value *DstEnd = B.CreateInBoundsGEP(
684       B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
685 
686   // We have enough information to now generate the memcpy call to do the
687   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
688   CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV);
689   NewCI->setAttributes(CI->getAttributes());
690   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
691   copyFlags(*CI, NewCI);
692   return DstEnd;
693 }
694 
695 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilderBase &B) {
696   Function *Callee = CI->getCalledFunction();
697   Value *Dst = CI->getArgOperand(0);
698   Value *Src = CI->getArgOperand(1);
699   Value *Size = CI->getArgOperand(2);
700   annotateNonNullNoUndefBasedOnAccess(CI, 0);
701   if (isKnownNonZero(Size, DL))
702     annotateNonNullNoUndefBasedOnAccess(CI, 1);
703 
704   uint64_t Len;
705   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
706     Len = LengthArg->getZExtValue();
707   else
708     return nullptr;
709 
710   // strncpy(x, y, 0) -> x
711   if (Len == 0)
712     return Dst;
713 
714   // See if we can get the length of the input string.
715   uint64_t SrcLen = GetStringLength(Src);
716   if (SrcLen) {
717     annotateDereferenceableBytes(CI, 1, SrcLen);
718     --SrcLen; // Unbias length.
719   } else {
720     return nullptr;
721   }
722 
723   if (SrcLen == 0) {
724     // strncpy(x, "", y) -> memset(x, '\0', y)
725     Align MemSetAlign =
726         CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne();
727     CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign);
728     AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0));
729     NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
730         CI->getContext(), 0, ArgAttrs));
731     copyFlags(*CI, NewCI);
732     return Dst;
733   }
734 
735   // strncpy(a, "a", 4) - > memcpy(a, "a\0\0\0", 4)
736   if (Len > SrcLen + 1) {
737     if (Len <= 128) {
738       StringRef Str;
739       if (!getConstantStringInfo(Src, Str))
740         return nullptr;
741       std::string SrcStr = Str.str();
742       SrcStr.resize(Len, '\0');
743       Src = B.CreateGlobalString(SrcStr, "str");
744     } else {
745       return nullptr;
746     }
747   }
748 
749   Type *PT = Callee->getFunctionType()->getParamType(0);
750   // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
751   CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
752                                    ConstantInt::get(DL.getIntPtrType(PT), Len));
753   NewCI->setAttributes(CI->getAttributes());
754   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
755   copyFlags(*CI, NewCI);
756   return Dst;
757 }
758 
759 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B,
760                                                unsigned CharSize,
761                                                Value *Bound) {
762   Value *Src = CI->getArgOperand(0);
763   Type *CharTy = B.getIntNTy(CharSize);
764 
765   if (isOnlyUsedInZeroEqualityComparison(CI) &&
766       (!Bound || isKnownNonZero(Bound, DL))) {
767     // Fold strlen:
768     //   strlen(x) != 0 --> *x != 0
769     //   strlen(x) == 0 --> *x == 0
770     // and likewise strnlen with constant N > 0:
771     //   strnlen(x, N) != 0 --> *x != 0
772     //   strnlen(x, N) == 0 --> *x == 0
773     return B.CreateZExt(B.CreateLoad(CharTy, Src, "char0"),
774                         CI->getType());
775   }
776 
777   if (Bound) {
778     if (ConstantInt *BoundCst = dyn_cast<ConstantInt>(Bound)) {
779       if (BoundCst->isZero())
780         // Fold strnlen(s, 0) -> 0 for any s, constant or otherwise.
781         return ConstantInt::get(CI->getType(), 0);
782 
783       if (BoundCst->isOne()) {
784         // Fold strnlen(s, 1) -> *s ? 1 : 0 for any s.
785         Value *CharVal = B.CreateLoad(CharTy, Src, "strnlen.char0");
786         Value *ZeroChar = ConstantInt::get(CharTy, 0);
787         Value *Cmp = B.CreateICmpNE(CharVal, ZeroChar, "strnlen.char0cmp");
788         return B.CreateZExt(Cmp, CI->getType());
789       }
790     }
791   }
792 
793   if (uint64_t Len = GetStringLength(Src, CharSize)) {
794     Value *LenC = ConstantInt::get(CI->getType(), Len - 1);
795     // Fold strlen("xyz") -> 3 and strnlen("xyz", 2) -> 2
796     // and strnlen("xyz", Bound) -> min(3, Bound) for nonconstant Bound.
797     if (Bound)
798       return B.CreateBinaryIntrinsic(Intrinsic::umin, LenC, Bound);
799     return LenC;
800   }
801 
802   if (Bound)
803     // Punt for strnlen for now.
804     return nullptr;
805 
806   // If s is a constant pointer pointing to a string literal, we can fold
807   // strlen(s + x) to strlen(s) - x, when x is known to be in the range
808   // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
809   // We only try to simplify strlen when the pointer s points to an array
810   // of i8. Otherwise, we would need to scale the offset x before doing the
811   // subtraction. This will make the optimization more complex, and it's not
812   // very useful because calling strlen for a pointer of other types is
813   // very uncommon.
814   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
815     // TODO: Handle subobjects.
816     if (!isGEPBasedOnPointerToString(GEP, CharSize))
817       return nullptr;
818 
819     ConstantDataArraySlice Slice;
820     if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
821       uint64_t NullTermIdx;
822       if (Slice.Array == nullptr) {
823         NullTermIdx = 0;
824       } else {
825         NullTermIdx = ~((uint64_t)0);
826         for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
827           if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
828             NullTermIdx = I;
829             break;
830           }
831         }
832         // If the string does not have '\0', leave it to strlen to compute
833         // its length.
834         if (NullTermIdx == ~((uint64_t)0))
835           return nullptr;
836       }
837 
838       Value *Offset = GEP->getOperand(2);
839       KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
840       uint64_t ArrSize =
841              cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
842 
843       // If Offset is not provably in the range [0, NullTermIdx], we can still
844       // optimize if we can prove that the program has undefined behavior when
845       // Offset is outside that range. That is the case when GEP->getOperand(0)
846       // is a pointer to an object whose memory extent is NullTermIdx+1.
847       if ((Known.isNonNegative() && Known.getMaxValue().ule(NullTermIdx)) ||
848           (isa<GlobalVariable>(GEP->getOperand(0)) &&
849            NullTermIdx == ArrSize - 1)) {
850         Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
851         return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
852                            Offset);
853       }
854     }
855   }
856 
857   // strlen(x?"foo":"bars") --> x ? 3 : 4
858   if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
859     uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
860     uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
861     if (LenTrue && LenFalse) {
862       ORE.emit([&]() {
863         return OptimizationRemark("instcombine", "simplify-libcalls", CI)
864                << "folded strlen(select) to select of constants";
865       });
866       return B.CreateSelect(SI->getCondition(),
867                             ConstantInt::get(CI->getType(), LenTrue - 1),
868                             ConstantInt::get(CI->getType(), LenFalse - 1));
869     }
870   }
871 
872   return nullptr;
873 }
874 
875 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) {
876   if (Value *V = optimizeStringLength(CI, B, 8))
877     return V;
878   annotateNonNullNoUndefBasedOnAccess(CI, 0);
879   return nullptr;
880 }
881 
882 Value *LibCallSimplifier::optimizeStrNLen(CallInst *CI, IRBuilderBase &B) {
883   Value *Bound = CI->getArgOperand(1);
884   if (Value *V = optimizeStringLength(CI, B, 8, Bound))
885     return V;
886 
887   if (isKnownNonZero(Bound, DL))
888     annotateNonNullNoUndefBasedOnAccess(CI, 0);
889   return nullptr;
890 }
891 
892 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) {
893   Module &M = *CI->getModule();
894   unsigned WCharSize = TLI->getWCharSize(M) * 8;
895   // We cannot perform this optimization without wchar_size metadata.
896   if (WCharSize == 0)
897     return nullptr;
898 
899   return optimizeStringLength(CI, B, WCharSize);
900 }
901 
902 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) {
903   StringRef S1, S2;
904   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
905   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
906 
907   // strpbrk(s, "") -> nullptr
908   // strpbrk("", s) -> nullptr
909   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
910     return Constant::getNullValue(CI->getType());
911 
912   // Constant folding.
913   if (HasS1 && HasS2) {
914     size_t I = S1.find_first_of(S2);
915     if (I == StringRef::npos) // No match.
916       return Constant::getNullValue(CI->getType());
917 
918     return B.CreateInBoundsGEP(B.getInt8Ty(), CI->getArgOperand(0),
919                                B.getInt64(I), "strpbrk");
920   }
921 
922   // strpbrk(s, "a") -> strchr(s, 'a')
923   if (HasS2 && S2.size() == 1)
924     return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI));
925 
926   return nullptr;
927 }
928 
929 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) {
930   Value *EndPtr = CI->getArgOperand(1);
931   if (isa<ConstantPointerNull>(EndPtr)) {
932     // With a null EndPtr, this function won't capture the main argument.
933     // It would be readonly too, except that it still may write to errno.
934     CI->addParamAttr(0, Attribute::NoCapture);
935   }
936 
937   return nullptr;
938 }
939 
940 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) {
941   StringRef S1, S2;
942   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
943   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
944 
945   // strspn(s, "") -> 0
946   // strspn("", s) -> 0
947   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
948     return Constant::getNullValue(CI->getType());
949 
950   // Constant folding.
951   if (HasS1 && HasS2) {
952     size_t Pos = S1.find_first_not_of(S2);
953     if (Pos == StringRef::npos)
954       Pos = S1.size();
955     return ConstantInt::get(CI->getType(), Pos);
956   }
957 
958   return nullptr;
959 }
960 
961 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) {
962   StringRef S1, S2;
963   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
964   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
965 
966   // strcspn("", s) -> 0
967   if (HasS1 && S1.empty())
968     return Constant::getNullValue(CI->getType());
969 
970   // Constant folding.
971   if (HasS1 && HasS2) {
972     size_t Pos = S1.find_first_of(S2);
973     if (Pos == StringRef::npos)
974       Pos = S1.size();
975     return ConstantInt::get(CI->getType(), Pos);
976   }
977 
978   // strcspn(s, "") -> strlen(s)
979   if (HasS2 && S2.empty())
980     return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI));
981 
982   return nullptr;
983 }
984 
985 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) {
986   // fold strstr(x, x) -> x.
987   if (CI->getArgOperand(0) == CI->getArgOperand(1))
988     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
989 
990   // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
991   if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
992     Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
993     if (!StrLen)
994       return nullptr;
995     Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
996                                  StrLen, B, DL, TLI);
997     if (!StrNCmp)
998       return nullptr;
999     for (User *U : llvm::make_early_inc_range(CI->users())) {
1000       ICmpInst *Old = cast<ICmpInst>(U);
1001       Value *Cmp =
1002           B.CreateICmp(Old->getPredicate(), StrNCmp,
1003                        ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
1004       replaceAllUsesWith(Old, Cmp);
1005     }
1006     return CI;
1007   }
1008 
1009   // See if either input string is a constant string.
1010   StringRef SearchStr, ToFindStr;
1011   bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
1012   bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
1013 
1014   // fold strstr(x, "") -> x.
1015   if (HasStr2 && ToFindStr.empty())
1016     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
1017 
1018   // If both strings are known, constant fold it.
1019   if (HasStr1 && HasStr2) {
1020     size_t Offset = SearchStr.find(ToFindStr);
1021 
1022     if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
1023       return Constant::getNullValue(CI->getType());
1024 
1025     // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
1026     Value *Result = castToCStr(CI->getArgOperand(0), B);
1027     Result =
1028         B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
1029     return B.CreateBitCast(Result, CI->getType());
1030   }
1031 
1032   // fold strstr(x, "y") -> strchr(x, 'y').
1033   if (HasStr2 && ToFindStr.size() == 1) {
1034     Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
1035     return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
1036   }
1037 
1038   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
1039   return nullptr;
1040 }
1041 
1042 Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) {
1043   Value *SrcStr = CI->getArgOperand(0);
1044   Value *Size = CI->getArgOperand(2);
1045   annotateNonNullAndDereferenceable(CI, 0, Size, DL);
1046   Value *CharVal = CI->getArgOperand(1);
1047   ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1048   Value *NullPtr = Constant::getNullValue(CI->getType());
1049 
1050   if (LenC) {
1051     if (LenC->isZero())
1052       // Fold memrchr(x, y, 0) --> null.
1053       return NullPtr;
1054 
1055     if (LenC->isOne()) {
1056       // Fold memrchr(x, y, 1) --> *x == y ? x : null for any x and y,
1057       // constant or otherwise.
1058       Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memrchr.char0");
1059       // Slice off the character's high end bits.
1060       CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1061       Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memrchr.char0cmp");
1062       return B.CreateSelect(Cmp, SrcStr, NullPtr, "memrchr.sel");
1063     }
1064   }
1065 
1066   StringRef Str;
1067   if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
1068     return nullptr;
1069 
1070   if (Str.size() == 0)
1071     // If the array is empty fold memrchr(A, C, N) to null for any value
1072     // of C and N on the basis that the only valid value of N is zero
1073     // (otherwise the call is undefined).
1074     return NullPtr;
1075 
1076   uint64_t EndOff = UINT64_MAX;
1077   if (LenC) {
1078     EndOff = LenC->getZExtValue();
1079     if (Str.size() < EndOff)
1080       // Punt out-of-bounds accesses to sanitizers and/or libc.
1081       return nullptr;
1082   }
1083 
1084   if (ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal)) {
1085     // Fold memrchr(S, C, N) for a constant C.
1086     size_t Pos = Str.rfind(CharC->getZExtValue(), EndOff);
1087     if (Pos == StringRef::npos)
1088       // When the character is not in the source array fold the result
1089       // to null regardless of Size.
1090       return NullPtr;
1091 
1092     if (LenC)
1093       // Fold memrchr(s, c, N) --> s + Pos for constant N > Pos.
1094       return B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos));
1095 
1096     if (Str.find(Str[Pos]) == Pos) {
1097       // When there is just a single occurrence of C in S, i.e., the one
1098       // in Str[Pos], fold
1099       //   memrchr(s, c, N) --> N <= Pos ? null : s + Pos
1100       // for nonconstant N.
1101       Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1102                                    "memrchr.cmp");
1103       Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr,
1104                                            B.getInt64(Pos), "memrchr.ptr_plus");
1105       return B.CreateSelect(Cmp, NullPtr, SrcPlus, "memrchr.sel");
1106     }
1107   }
1108 
1109   // Truncate the string to search at most EndOff characters.
1110   Str = Str.substr(0, EndOff);
1111   if (Str.find_first_not_of(Str[0]) != StringRef::npos)
1112     return nullptr;
1113 
1114   // If the source array consists of all equal characters, then for any
1115   // C and N (whether in bounds or not), fold memrchr(S, C, N) to
1116   //   N != 0 && *S == C ? S + N - 1 : null
1117   Type *SizeTy = Size->getType();
1118   Type *Int8Ty = B.getInt8Ty();
1119   Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1120   // Slice off the sought character's high end bits.
1121   CharVal = B.CreateTrunc(CharVal, Int8Ty);
1122   Value *CEqS0 = B.CreateICmpEQ(ConstantInt::get(Int8Ty, Str[0]), CharVal);
1123   Value *And = B.CreateLogicalAnd(NNeZ, CEqS0);
1124   Value *SizeM1 = B.CreateSub(Size, ConstantInt::get(SizeTy, 1));
1125   Value *SrcPlus =
1126       B.CreateInBoundsGEP(Int8Ty, SrcStr, SizeM1, "memrchr.ptr_plus");
1127   return B.CreateSelect(And, SrcPlus, NullPtr, "memrchr.sel");
1128 }
1129 
1130 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) {
1131   Value *SrcStr = CI->getArgOperand(0);
1132   Value *Size = CI->getArgOperand(2);
1133 
1134   if (isKnownNonZero(Size, DL)) {
1135     annotateNonNullNoUndefBasedOnAccess(CI, 0);
1136     if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1137       return memChrToCharCompare(CI, Size, B, DL);
1138   }
1139 
1140   Value *CharVal = CI->getArgOperand(1);
1141   ConstantInt *CharC = dyn_cast<ConstantInt>(CharVal);
1142   ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1143   Value *NullPtr = Constant::getNullValue(CI->getType());
1144 
1145   // memchr(x, y, 0) -> null
1146   if (LenC) {
1147     if (LenC->isZero())
1148       return NullPtr;
1149 
1150     if (LenC->isOne()) {
1151       // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y,
1152       // constant or otherwise.
1153       Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0");
1154       // Slice off the character's high end bits.
1155       CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1156       Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp");
1157       return B.CreateSelect(Cmp, SrcStr, NullPtr, "memchr.sel");
1158     }
1159   }
1160 
1161   StringRef Str;
1162   if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
1163     return nullptr;
1164 
1165   if (CharC) {
1166     size_t Pos = Str.find(CharC->getZExtValue());
1167     if (Pos == StringRef::npos)
1168       // When the character is not in the source array fold the result
1169       // to null regardless of Size.
1170       return NullPtr;
1171 
1172     // Fold memchr(s, c, n) -> n <= Pos ? null : s + Pos
1173     // When the constant Size is less than or equal to the character
1174     // position also fold the result to null.
1175     Value *Cmp = B.CreateICmpULE(Size, ConstantInt::get(Size->getType(), Pos),
1176                                  "memchr.cmp");
1177     Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos),
1178                                          "memchr.ptr");
1179     return B.CreateSelect(Cmp, NullPtr, SrcPlus);
1180   }
1181 
1182   if (Str.size() == 0)
1183     // If the array is empty fold memchr(A, C, N) to null for any value
1184     // of C and N on the basis that the only valid value of N is zero
1185     // (otherwise the call is undefined).
1186     return NullPtr;
1187 
1188   if (LenC)
1189     Str = substr(Str, LenC->getZExtValue());
1190 
1191   size_t Pos = Str.find_first_not_of(Str[0]);
1192   if (Pos == StringRef::npos
1193       || Str.find_first_not_of(Str[Pos], Pos) == StringRef::npos) {
1194     // If the source array consists of at most two consecutive sequences
1195     // of the same characters, then for any C and N (whether in bounds or
1196     // not), fold memchr(S, C, N) to
1197     //   N != 0 && *S == C ? S : null
1198     // or for the two sequences to:
1199     //   N != 0 && *S == C ? S : (N > Pos && S[Pos] == C ? S + Pos : null)
1200     //   ^Sel2                   ^Sel1 are denoted above.
1201     // The latter makes it also possible to fold strchr() calls with strings
1202     // of the same characters.
1203     Type *SizeTy = Size->getType();
1204     Type *Int8Ty = B.getInt8Ty();
1205 
1206     // Slice off the sought character's high end bits.
1207     CharVal = B.CreateTrunc(CharVal, Int8Ty);
1208 
1209     Value *Sel1 = NullPtr;
1210     if (Pos != StringRef::npos) {
1211       // Handle two consecutive sequences of the same characters.
1212       Value *PosVal = ConstantInt::get(SizeTy, Pos);
1213       Value *StrPos = ConstantInt::get(Int8Ty, Str[Pos]);
1214       Value *CEqSPos = B.CreateICmpEQ(CharVal, StrPos);
1215       Value *NGtPos = B.CreateICmp(ICmpInst::ICMP_UGT, Size, PosVal);
1216       Value *And = B.CreateAnd(CEqSPos, NGtPos);
1217       Value *SrcPlus = B.CreateInBoundsGEP(B.getInt8Ty(), SrcStr, PosVal);
1218       Sel1 = B.CreateSelect(And, SrcPlus, NullPtr, "memchr.sel1");
1219     }
1220 
1221     Value *Str0 = ConstantInt::get(Int8Ty, Str[0]);
1222     Value *CEqS0 = B.CreateICmpEQ(Str0, CharVal);
1223     Value *NNeZ = B.CreateICmpNE(Size, ConstantInt::get(SizeTy, 0));
1224     Value *And = B.CreateAnd(NNeZ, CEqS0);
1225     return B.CreateSelect(And, SrcStr, Sel1, "memchr.sel2");
1226   }
1227 
1228   if (!LenC) {
1229     if (isOnlyUsedInEqualityComparison(CI, SrcStr))
1230       // S is dereferenceable so it's safe to load from it and fold
1231       //   memchr(S, C, N) == S to N && *S == C for any C and N.
1232       // TODO: This is safe even even for nonconstant S.
1233       return memChrToCharCompare(CI, Size, B, DL);
1234 
1235     // From now on we need a constant length and constant array.
1236     return nullptr;
1237   }
1238 
1239   // If the char is variable but the input str and length are not we can turn
1240   // this memchr call into a simple bit field test. Of course this only works
1241   // when the return value is only checked against null.
1242   //
1243   // It would be really nice to reuse switch lowering here but we can't change
1244   // the CFG at this point.
1245   //
1246   // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
1247   // != 0
1248   //   after bounds check.
1249   if (Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI))
1250     return nullptr;
1251 
1252   unsigned char Max =
1253       *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
1254                         reinterpret_cast<const unsigned char *>(Str.end()));
1255 
1256   // Make sure the bit field we're about to create fits in a register on the
1257   // target.
1258   // FIXME: On a 64 bit architecture this prevents us from using the
1259   // interesting range of alpha ascii chars. We could do better by emitting
1260   // two bitfields or shifting the range by 64 if no lower chars are used.
1261   if (!DL.fitsInLegalInteger(Max + 1))
1262     return nullptr;
1263 
1264   // For the bit field use a power-of-2 type with at least 8 bits to avoid
1265   // creating unnecessary illegal types.
1266   unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
1267 
1268   // Now build the bit field.
1269   APInt Bitfield(Width, 0);
1270   for (char C : Str)
1271     Bitfield.setBit((unsigned char)C);
1272   Value *BitfieldC = B.getInt(Bitfield);
1273 
1274   // Adjust width of "C" to the bitfield width, then mask off the high bits.
1275   Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType());
1276   C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
1277 
1278   // First check that the bit field access is within bounds.
1279   Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
1280                                "memchr.bounds");
1281 
1282   // Create code that checks if the given bit is set in the field.
1283   Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
1284   Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
1285 
1286   // Finally merge both checks and cast to pointer type. The inttoptr
1287   // implicitly zexts the i1 to intptr type.
1288   return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"),
1289                           CI->getType());
1290 }
1291 
1292 // Optimize a memcmp or, when StrNCmp is true, strncmp call CI with constant
1293 // arrays LHS and RHS and nonconstant Size.
1294 static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS,
1295                                     Value *Size, bool StrNCmp,
1296                                     IRBuilderBase &B, const DataLayout &DL) {
1297   if (LHS == RHS) // memcmp(s,s,x) -> 0
1298     return Constant::getNullValue(CI->getType());
1299 
1300   StringRef LStr, RStr;
1301   if (!getConstantStringInfo(LHS, LStr, 0, /*TrimAtNul=*/false) ||
1302       !getConstantStringInfo(RHS, RStr, 0, /*TrimAtNul=*/false))
1303     return nullptr;
1304 
1305   // If the contents of both constant arrays are known, fold a call to
1306   // memcmp(A, B, N) to
1307   //   N <= Pos ? 0 : (A < B ? -1 : B < A ? +1 : 0)
1308   // where Pos is the first mismatch between A and B, determined below.
1309 
1310   uint64_t Pos = 0;
1311   Value *Zero = ConstantInt::get(CI->getType(), 0);
1312   for (uint64_t MinSize = std::min(LStr.size(), RStr.size()); ; ++Pos) {
1313     if (Pos == MinSize ||
1314         (StrNCmp && (LStr[Pos] == '\0' && RStr[Pos] == '\0'))) {
1315       // One array is a leading part of the other of equal or greater
1316       // size, or for strncmp, the arrays are equal strings.
1317       // Fold the result to zero.  Size is assumed to be in bounds, since
1318       // otherwise the call would be undefined.
1319       return Zero;
1320     }
1321 
1322     if (LStr[Pos] != RStr[Pos])
1323       break;
1324   }
1325 
1326   // Normalize the result.
1327   typedef unsigned char UChar;
1328   int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
1329   Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
1330   Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
1331   Value *Res = ConstantInt::get(CI->getType(), IRes);
1332   return B.CreateSelect(Cmp, Zero, Res);
1333 }
1334 
1335 // Optimize a memcmp call CI with constant size Len.
1336 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
1337                                          uint64_t Len, IRBuilderBase &B,
1338                                          const DataLayout &DL) {
1339   if (Len == 0) // memcmp(s1,s2,0) -> 0
1340     return Constant::getNullValue(CI->getType());
1341 
1342   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1343   if (Len == 1) {
1344     Value *LHSV =
1345         B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
1346                      CI->getType(), "lhsv");
1347     Value *RHSV =
1348         B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
1349                      CI->getType(), "rhsv");
1350     return B.CreateSub(LHSV, RHSV, "chardiff");
1351   }
1352 
1353   // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
1354   // TODO: The case where both inputs are constants does not need to be limited
1355   // to legal integers or equality comparison. See block below this.
1356   if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
1357     IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1358     unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
1359 
1360     // First, see if we can fold either argument to a constant.
1361     Value *LHSV = nullptr;
1362     if (auto *LHSC = dyn_cast<Constant>(LHS)) {
1363       LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
1364       LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1365     }
1366     Value *RHSV = nullptr;
1367     if (auto *RHSC = dyn_cast<Constant>(RHS)) {
1368       RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
1369       RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1370     }
1371 
1372     // Don't generate unaligned loads. If either source is constant data,
1373     // alignment doesn't matter for that source because there is no load.
1374     if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1375         (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1376       if (!LHSV) {
1377         Type *LHSPtrTy =
1378             IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
1379         LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
1380       }
1381       if (!RHSV) {
1382         Type *RHSPtrTy =
1383             IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
1384         RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
1385       }
1386       return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
1387     }
1388   }
1389 
1390   return nullptr;
1391 }
1392 
1393 // Most simplifications for memcmp also apply to bcmp.
1394 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1395                                                    IRBuilderBase &B) {
1396   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1397   Value *Size = CI->getArgOperand(2);
1398 
1399   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1400 
1401   if (Value *Res = optimizeMemCmpVarSize(CI, LHS, RHS, Size, false, B, DL))
1402     return Res;
1403 
1404   // Handle constant Size.
1405   ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1406   if (!LenC)
1407     return nullptr;
1408 
1409   return optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL);
1410 }
1411 
1412 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
1413   Module *M = CI->getModule();
1414   if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1415     return V;
1416 
1417   // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
1418   // bcmp can be more efficient than memcmp because it only has to know that
1419   // there is a difference, not how different one is to the other.
1420   if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) &&
1421       isOnlyUsedInZeroEqualityComparison(CI)) {
1422     Value *LHS = CI->getArgOperand(0);
1423     Value *RHS = CI->getArgOperand(1);
1424     Value *Size = CI->getArgOperand(2);
1425     return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
1426   }
1427 
1428   return nullptr;
1429 }
1430 
1431 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
1432   return optimizeMemCmpBCmpCommon(CI, B);
1433 }
1434 
1435 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
1436   Value *Size = CI->getArgOperand(2);
1437   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1438   if (isa<IntrinsicInst>(CI))
1439     return nullptr;
1440 
1441   // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
1442   CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
1443                                    CI->getArgOperand(1), Align(1), Size);
1444   NewCI->setAttributes(CI->getAttributes());
1445   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1446   copyFlags(*CI, NewCI);
1447   return CI->getArgOperand(0);
1448 }
1449 
1450 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
1451   Value *Dst = CI->getArgOperand(0);
1452   Value *Src = CI->getArgOperand(1);
1453   ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1454   ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
1455   StringRef SrcStr;
1456   if (CI->use_empty() && Dst == Src)
1457     return Dst;
1458   // memccpy(d, s, c, 0) -> nullptr
1459   if (N) {
1460     if (N->isNullValue())
1461       return Constant::getNullValue(CI->getType());
1462     if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0,
1463                                /*TrimAtNul=*/false) ||
1464         // TODO: Handle zeroinitializer.
1465         !StopChar)
1466       return nullptr;
1467   } else {
1468     return nullptr;
1469   }
1470 
1471   // Wrap arg 'c' of type int to char
1472   size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
1473   if (Pos == StringRef::npos) {
1474     if (N->getZExtValue() <= SrcStr.size()) {
1475       copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
1476                                     CI->getArgOperand(3)));
1477       return Constant::getNullValue(CI->getType());
1478     }
1479     return nullptr;
1480   }
1481 
1482   Value *NewN =
1483       ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
1484   // memccpy -> llvm.memcpy
1485   copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
1486   return Pos + 1 <= N->getZExtValue()
1487              ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
1488              : Constant::getNullValue(CI->getType());
1489 }
1490 
1491 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
1492   Value *Dst = CI->getArgOperand(0);
1493   Value *N = CI->getArgOperand(2);
1494   // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1495   CallInst *NewCI =
1496       B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
1497   // Propagate attributes, but memcpy has no return value, so make sure that
1498   // any return attributes are compliant.
1499   // TODO: Attach return value attributes to the 1st operand to preserve them?
1500   NewCI->setAttributes(CI->getAttributes());
1501   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1502   copyFlags(*CI, NewCI);
1503   return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1504 }
1505 
1506 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
1507   Value *Size = CI->getArgOperand(2);
1508   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1509   if (isa<IntrinsicInst>(CI))
1510     return nullptr;
1511 
1512   // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1513   CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
1514                                     CI->getArgOperand(1), Align(1), Size);
1515   NewCI->setAttributes(CI->getAttributes());
1516   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1517   copyFlags(*CI, NewCI);
1518   return CI->getArgOperand(0);
1519 }
1520 
1521 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
1522   Value *Size = CI->getArgOperand(2);
1523   annotateNonNullAndDereferenceable(CI, 0, Size, DL);
1524   if (isa<IntrinsicInst>(CI))
1525     return nullptr;
1526 
1527   // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1528   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1529   CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
1530   NewCI->setAttributes(CI->getAttributes());
1531   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1532   copyFlags(*CI, NewCI);
1533   return CI->getArgOperand(0);
1534 }
1535 
1536 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
1537   if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1538     return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI));
1539 
1540   return nullptr;
1541 }
1542 
1543 //===----------------------------------------------------------------------===//
1544 // Math Library Optimizations
1545 //===----------------------------------------------------------------------===//
1546 
1547 // Replace a libcall \p CI with a call to intrinsic \p IID
1548 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B,
1549                                Intrinsic::ID IID) {
1550   // Propagate fast-math flags from the existing call to the new call.
1551   IRBuilderBase::FastMathFlagGuard Guard(B);
1552   B.setFastMathFlags(CI->getFastMathFlags());
1553 
1554   Module *M = CI->getModule();
1555   Value *V = CI->getArgOperand(0);
1556   Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1557   CallInst *NewCall = B.CreateCall(F, V);
1558   NewCall->takeName(CI);
1559   return copyFlags(*CI, NewCall);
1560 }
1561 
1562 /// Return a variant of Val with float type.
1563 /// Currently this works in two cases: If Val is an FPExtension of a float
1564 /// value to something bigger, simply return the operand.
1565 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1566 /// loss of precision do so.
1567 static Value *valueHasFloatPrecision(Value *Val) {
1568   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1569     Value *Op = Cast->getOperand(0);
1570     if (Op->getType()->isFloatTy())
1571       return Op;
1572   }
1573   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1574     APFloat F = Const->getValueAPF();
1575     bool losesInfo;
1576     (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
1577                     &losesInfo);
1578     if (!losesInfo)
1579       return ConstantFP::get(Const->getContext(), F);
1580   }
1581   return nullptr;
1582 }
1583 
1584 /// Shrink double -> float functions.
1585 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B,
1586                                bool isBinary, const TargetLibraryInfo *TLI,
1587                                bool isPrecise = false) {
1588   Function *CalleeFn = CI->getCalledFunction();
1589   if (!CI->getType()->isDoubleTy() || !CalleeFn)
1590     return nullptr;
1591 
1592   // If not all the uses of the function are converted to float, then bail out.
1593   // This matters if the precision of the result is more important than the
1594   // precision of the arguments.
1595   if (isPrecise)
1596     for (User *U : CI->users()) {
1597       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1598       if (!Cast || !Cast->getType()->isFloatTy())
1599         return nullptr;
1600     }
1601 
1602   // If this is something like 'g((double) float)', convert to 'gf(float)'.
1603   Value *V[2];
1604   V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1605   V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1606   if (!V[0] || (isBinary && !V[1]))
1607     return nullptr;
1608 
1609   // If call isn't an intrinsic, check that it isn't within a function with the
1610   // same name as the float version of this call, otherwise the result is an
1611   // infinite loop.  For example, from MinGW-w64:
1612   //
1613   // float expf(float val) { return (float) exp((double) val); }
1614   StringRef CalleeName = CalleeFn->getName();
1615   bool IsIntrinsic = CalleeFn->isIntrinsic();
1616   if (!IsIntrinsic) {
1617     StringRef CallerName = CI->getFunction()->getName();
1618     if (!CallerName.empty() && CallerName.back() == 'f' &&
1619         CallerName.size() == (CalleeName.size() + 1) &&
1620         CallerName.startswith(CalleeName))
1621       return nullptr;
1622   }
1623 
1624   // Propagate the math semantics from the current function to the new function.
1625   IRBuilderBase::FastMathFlagGuard Guard(B);
1626   B.setFastMathFlags(CI->getFastMathFlags());
1627 
1628   // g((double) float) -> (double) gf(float)
1629   Value *R;
1630   if (IsIntrinsic) {
1631     Module *M = CI->getModule();
1632     Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1633     Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1634     R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
1635   } else {
1636     AttributeList CalleeAttrs = CalleeFn->getAttributes();
1637     R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B,
1638                                          CalleeAttrs)
1639                  : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs);
1640   }
1641   return B.CreateFPExt(R, B.getDoubleTy());
1642 }
1643 
1644 /// Shrink double -> float for unary functions.
1645 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B,
1646                                     const TargetLibraryInfo *TLI,
1647                                     bool isPrecise = false) {
1648   return optimizeDoubleFP(CI, B, false, TLI, isPrecise);
1649 }
1650 
1651 /// Shrink double -> float for binary functions.
1652 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B,
1653                                      const TargetLibraryInfo *TLI,
1654                                      bool isPrecise = false) {
1655   return optimizeDoubleFP(CI, B, true, TLI, isPrecise);
1656 }
1657 
1658 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1659 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
1660   if (!CI->isFast())
1661     return nullptr;
1662 
1663   // Propagate fast-math flags from the existing call to new instructions.
1664   IRBuilderBase::FastMathFlagGuard Guard(B);
1665   B.setFastMathFlags(CI->getFastMathFlags());
1666 
1667   Value *Real, *Imag;
1668   if (CI->arg_size() == 1) {
1669     Value *Op = CI->getArgOperand(0);
1670     assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1671     Real = B.CreateExtractValue(Op, 0, "real");
1672     Imag = B.CreateExtractValue(Op, 1, "imag");
1673   } else {
1674     assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
1675     Real = CI->getArgOperand(0);
1676     Imag = CI->getArgOperand(1);
1677   }
1678 
1679   Value *RealReal = B.CreateFMul(Real, Real);
1680   Value *ImagImag = B.CreateFMul(Imag, Imag);
1681 
1682   Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1683                                               CI->getType());
1684   return copyFlags(
1685       *CI, B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"));
1686 }
1687 
1688 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1689                                       IRBuilderBase &B) {
1690   if (!isa<FPMathOperator>(Call))
1691     return nullptr;
1692 
1693   IRBuilderBase::FastMathFlagGuard Guard(B);
1694   B.setFastMathFlags(Call->getFastMathFlags());
1695 
1696   // TODO: Can this be shared to also handle LLVM intrinsics?
1697   Value *X;
1698   switch (Func) {
1699   case LibFunc_sin:
1700   case LibFunc_sinf:
1701   case LibFunc_sinl:
1702   case LibFunc_tan:
1703   case LibFunc_tanf:
1704   case LibFunc_tanl:
1705     // sin(-X) --> -sin(X)
1706     // tan(-X) --> -tan(X)
1707     if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
1708       return B.CreateFNeg(
1709           copyFlags(*Call, B.CreateCall(Call->getCalledFunction(), X)));
1710     break;
1711   case LibFunc_cos:
1712   case LibFunc_cosf:
1713   case LibFunc_cosl:
1714     // cos(-X) --> cos(X)
1715     if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1716       return copyFlags(*Call,
1717                        B.CreateCall(Call->getCalledFunction(), X, "cos"));
1718     break;
1719   default:
1720     break;
1721   }
1722   return nullptr;
1723 }
1724 
1725 // Return a properly extended integer (DstWidth bits wide) if the operation is
1726 // an itofp.
1727 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
1728   if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
1729     Value *Op = cast<Instruction>(I2F)->getOperand(0);
1730     // Make sure that the exponent fits inside an "int" of size DstWidth,
1731     // thus avoiding any range issues that FP has not.
1732     unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
1733     if (BitWidth < DstWidth ||
1734         (BitWidth == DstWidth && isa<SIToFPInst>(I2F)))
1735       return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getIntNTy(DstWidth))
1736                                   : B.CreateZExt(Op, B.getIntNTy(DstWidth));
1737   }
1738 
1739   return nullptr;
1740 }
1741 
1742 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
1743 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
1744 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
1745 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
1746   Module *M = Pow->getModule();
1747   Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1748   AttributeList Attrs; // Attributes are only meaningful on the original call
1749   Module *Mod = Pow->getModule();
1750   Type *Ty = Pow->getType();
1751   bool Ignored;
1752 
1753   // Evaluate special cases related to a nested function as the base.
1754 
1755   // pow(exp(x), y) -> exp(x * y)
1756   // pow(exp2(x), y) -> exp2(x * y)
1757   // If exp{,2}() is used only once, it is better to fold two transcendental
1758   // math functions into one.  If used again, exp{,2}() would still have to be
1759   // called with the original argument, then keep both original transcendental
1760   // functions.  However, this transformation is only safe with fully relaxed
1761   // math semantics, since, besides rounding differences, it changes overflow
1762   // and underflow behavior quite dramatically.  For example:
1763   //   pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1764   // Whereas:
1765   //   exp(1000 * 0.001) = exp(1)
1766   // TODO: Loosen the requirement for fully relaxed math semantics.
1767   // TODO: Handle exp10() when more targets have it available.
1768   CallInst *BaseFn = dyn_cast<CallInst>(Base);
1769   if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
1770     LibFunc LibFn;
1771 
1772     Function *CalleeFn = BaseFn->getCalledFunction();
1773     if (CalleeFn &&
1774         TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
1775         isLibFuncEmittable(M, TLI, LibFn)) {
1776       StringRef ExpName;
1777       Intrinsic::ID ID;
1778       Value *ExpFn;
1779       LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
1780 
1781       switch (LibFn) {
1782       default:
1783         return nullptr;
1784       case LibFunc_expf:  case LibFunc_exp:  case LibFunc_expl:
1785         ExpName = TLI->getName(LibFunc_exp);
1786         ID = Intrinsic::exp;
1787         LibFnFloat = LibFunc_expf;
1788         LibFnDouble = LibFunc_exp;
1789         LibFnLongDouble = LibFunc_expl;
1790         break;
1791       case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
1792         ExpName = TLI->getName(LibFunc_exp2);
1793         ID = Intrinsic::exp2;
1794         LibFnFloat = LibFunc_exp2f;
1795         LibFnDouble = LibFunc_exp2;
1796         LibFnLongDouble = LibFunc_exp2l;
1797         break;
1798       }
1799 
1800       // Create new exp{,2}() with the product as its argument.
1801       Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1802       ExpFn = BaseFn->doesNotAccessMemory()
1803               ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1804                              FMul, ExpName)
1805               : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1806                                      LibFnLongDouble, B,
1807                                      BaseFn->getAttributes());
1808 
1809       // Since the new exp{,2}() is different from the original one, dead code
1810       // elimination cannot be trusted to remove it, since it may have side
1811       // effects (e.g., errno).  When the only consumer for the original
1812       // exp{,2}() is pow(), then it has to be explicitly erased.
1813       substituteInParent(BaseFn, ExpFn);
1814       return ExpFn;
1815     }
1816   }
1817 
1818   // Evaluate special cases related to a constant base.
1819 
1820   const APFloat *BaseF;
1821   if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1822     return nullptr;
1823 
1824   // pow(2.0, itofp(x)) -> ldexp(1.0, x)
1825   if (match(Base, m_SpecificFP(2.0)) &&
1826       (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
1827       hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1828     if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
1829       return copyFlags(*Pow,
1830                        emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI,
1831                                              TLI, LibFunc_ldexp, LibFunc_ldexpf,
1832                                              LibFunc_ldexpl, B, Attrs));
1833   }
1834 
1835   // pow(2.0 ** n, x) -> exp2(n * x)
1836   if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1837     APFloat BaseR = APFloat(1.0);
1838     BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1839     BaseR = BaseR / *BaseF;
1840     bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
1841     const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1842     APSInt NI(64, false);
1843     if ((IsInteger || IsReciprocal) &&
1844         NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1845             APFloat::opOK &&
1846         NI > 1 && NI.isPowerOf2()) {
1847       double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1848       Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1849       if (Pow->doesNotAccessMemory())
1850         return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
1851                                                 Mod, Intrinsic::exp2, Ty),
1852                                             FMul, "exp2"));
1853       else
1854         return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
1855                                                     LibFunc_exp2f,
1856                                                     LibFunc_exp2l, B, Attrs));
1857     }
1858   }
1859 
1860   // pow(10.0, x) -> exp10(x)
1861   // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1862   if (match(Base, m_SpecificFP(10.0)) &&
1863       hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1864     return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
1865                                                 LibFunc_exp10f, LibFunc_exp10l,
1866                                                 B, Attrs));
1867 
1868   // pow(x, y) -> exp2(log2(x) * y)
1869   if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
1870       !BaseF->isNegative()) {
1871     // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
1872     // Luckily optimizePow has already handled the x == 1 case.
1873     assert(!match(Base, m_FPOne()) &&
1874            "pow(1.0, y) should have been simplified earlier!");
1875 
1876     Value *Log = nullptr;
1877     if (Ty->isFloatTy())
1878       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1879     else if (Ty->isDoubleTy())
1880       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1881 
1882     if (Log) {
1883       Value *FMul = B.CreateFMul(Log, Expo, "mul");
1884       if (Pow->doesNotAccessMemory())
1885         return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
1886                                                 Mod, Intrinsic::exp2, Ty),
1887                                             FMul, "exp2"));
1888       else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f,
1889                           LibFunc_exp2l))
1890         return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
1891                                                     LibFunc_exp2f,
1892                                                     LibFunc_exp2l, B, Attrs));
1893     }
1894   }
1895 
1896   return nullptr;
1897 }
1898 
1899 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1900                           Module *M, IRBuilderBase &B,
1901                           const TargetLibraryInfo *TLI) {
1902   // If errno is never set, then use the intrinsic for sqrt().
1903   if (NoErrno) {
1904     Function *SqrtFn =
1905         Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1906     return B.CreateCall(SqrtFn, V, "sqrt");
1907   }
1908 
1909   // Otherwise, use the libcall for sqrt().
1910   if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1911                  LibFunc_sqrtl))
1912     // TODO: We also should check that the target can in fact lower the sqrt()
1913     // libcall. We currently have no way to ask this question, so we ask if
1914     // the target has a sqrt() libcall, which is not exactly the same.
1915     return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1916                                 LibFunc_sqrtl, B, Attrs);
1917 
1918   return nullptr;
1919 }
1920 
1921 /// Use square root in place of pow(x, +/-0.5).
1922 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
1923   Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1924   AttributeList Attrs; // Attributes are only meaningful on the original call
1925   Module *Mod = Pow->getModule();
1926   Type *Ty = Pow->getType();
1927 
1928   const APFloat *ExpoF;
1929   if (!match(Expo, m_APFloat(ExpoF)) ||
1930       (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1931     return nullptr;
1932 
1933   // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
1934   // so that requires fast-math-flags (afn or reassoc).
1935   if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
1936     return nullptr;
1937 
1938   // If we have a pow() library call (accesses memory) and we can't guarantee
1939   // that the base is not an infinity, give up:
1940   // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
1941   // errno), but sqrt(-Inf) is required by various standards to set errno.
1942   if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
1943       !isKnownNeverInfinity(Base, TLI))
1944     return nullptr;
1945 
1946   Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1947   if (!Sqrt)
1948     return nullptr;
1949 
1950   // Handle signed zero base by expanding to fabs(sqrt(x)).
1951   if (!Pow->hasNoSignedZeros()) {
1952     Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1953     Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1954   }
1955 
1956   Sqrt = copyFlags(*Pow, Sqrt);
1957 
1958   // Handle non finite base by expanding to
1959   // (x == -infinity ? +infinity : sqrt(x)).
1960   if (!Pow->hasNoInfs()) {
1961     Value *PosInf = ConstantFP::getInfinity(Ty),
1962           *NegInf = ConstantFP::getInfinity(Ty, true);
1963     Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1964     Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1965   }
1966 
1967   // If the exponent is negative, then get the reciprocal.
1968   if (ExpoF->isNegative())
1969     Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1970 
1971   return Sqrt;
1972 }
1973 
1974 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1975                                            IRBuilderBase &B) {
1976   Value *Args[] = {Base, Expo};
1977   Type *Types[] = {Base->getType(), Expo->getType()};
1978   Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Types);
1979   return B.CreateCall(F, Args);
1980 }
1981 
1982 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
1983   Value *Base = Pow->getArgOperand(0);
1984   Value *Expo = Pow->getArgOperand(1);
1985   Function *Callee = Pow->getCalledFunction();
1986   StringRef Name = Callee->getName();
1987   Type *Ty = Pow->getType();
1988   Module *M = Pow->getModule();
1989   bool AllowApprox = Pow->hasApproxFunc();
1990   bool Ignored;
1991 
1992   // Propagate the math semantics from the call to any created instructions.
1993   IRBuilderBase::FastMathFlagGuard Guard(B);
1994   B.setFastMathFlags(Pow->getFastMathFlags());
1995   // Evaluate special cases related to the base.
1996 
1997   // pow(1.0, x) -> 1.0
1998   if (match(Base, m_FPOne()))
1999     return Base;
2000 
2001   if (Value *Exp = replacePowWithExp(Pow, B))
2002     return Exp;
2003 
2004   // Evaluate special cases related to the exponent.
2005 
2006   // pow(x, -1.0) -> 1.0 / x
2007   if (match(Expo, m_SpecificFP(-1.0)))
2008     return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
2009 
2010   // pow(x, +/-0.0) -> 1.0
2011   if (match(Expo, m_AnyZeroFP()))
2012     return ConstantFP::get(Ty, 1.0);
2013 
2014   // pow(x, 1.0) -> x
2015   if (match(Expo, m_FPOne()))
2016     return Base;
2017 
2018   // pow(x, 2.0) -> x * x
2019   if (match(Expo, m_SpecificFP(2.0)))
2020     return B.CreateFMul(Base, Base, "square");
2021 
2022   if (Value *Sqrt = replacePowWithSqrt(Pow, B))
2023     return Sqrt;
2024 
2025   // If we can approximate pow:
2026   // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction
2027   // pow(x, n) -> powi(x, n) if n is a constant signed integer value
2028   const APFloat *ExpoF;
2029   if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
2030       !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
2031     APFloat ExpoA(abs(*ExpoF));
2032     APFloat ExpoI(*ExpoF);
2033     Value *Sqrt = nullptr;
2034     if (!ExpoA.isInteger()) {
2035       APFloat Expo2 = ExpoA;
2036       // To check if ExpoA is an integer + 0.5, we add it to itself. If there
2037       // is no floating point exception and the result is an integer, then
2038       // ExpoA == integer + 0.5
2039       if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
2040         return nullptr;
2041 
2042       if (!Expo2.isInteger())
2043         return nullptr;
2044 
2045       if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) !=
2046           APFloat::opInexact)
2047         return nullptr;
2048       if (!ExpoI.isInteger())
2049         return nullptr;
2050       ExpoF = &ExpoI;
2051 
2052       Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
2053                          Pow->doesNotAccessMemory(), M, B, TLI);
2054       if (!Sqrt)
2055         return nullptr;
2056     }
2057 
2058     // 0.5 fraction is now optionally handled.
2059     // Do pow -> powi for remaining integer exponent
2060     APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
2061     if (ExpoF->isInteger() &&
2062         ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
2063             APFloat::opOK) {
2064       Value *PowI = copyFlags(
2065           *Pow,
2066           createPowWithIntegerExponent(
2067               Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
2068               M, B));
2069 
2070       if (PowI && Sqrt)
2071         return B.CreateFMul(PowI, Sqrt);
2072 
2073       return PowI;
2074     }
2075   }
2076 
2077   // powf(x, itofp(y)) -> powi(x, y)
2078   if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
2079     if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
2080       return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
2081   }
2082 
2083   // Shrink pow() to powf() if the arguments are single precision,
2084   // unless the result is expected to be double precision.
2085   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
2086       hasFloatVersion(M, Name)) {
2087     if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
2088       return Shrunk;
2089   }
2090 
2091   return nullptr;
2092 }
2093 
2094 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
2095   Module *M = CI->getModule();
2096   Function *Callee = CI->getCalledFunction();
2097   AttributeList Attrs; // Attributes are only meaningful on the original call
2098   StringRef Name = Callee->getName();
2099   Value *Ret = nullptr;
2100   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
2101       hasFloatVersion(M, Name))
2102     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2103 
2104   Type *Ty = CI->getType();
2105   Value *Op = CI->getArgOperand(0);
2106 
2107   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= IntSize
2108   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < IntSize
2109   if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
2110       hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
2111     if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize()))
2112       return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
2113                                    LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
2114                                    B, Attrs);
2115   }
2116 
2117   return Ret;
2118 }
2119 
2120 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) {
2121   Module *M = CI->getModule();
2122 
2123   // If we can shrink the call to a float function rather than a double
2124   // function, do that first.
2125   Function *Callee = CI->getCalledFunction();
2126   StringRef Name = Callee->getName();
2127   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name))
2128     if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI))
2129       return Ret;
2130 
2131   // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
2132   // the intrinsics for improved optimization (for example, vectorization).
2133   // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
2134   // From the C standard draft WG14/N1256:
2135   // "Ideally, fmax would be sensitive to the sign of zero, for example
2136   // fmax(-0.0, +0.0) would return +0; however, implementation in software
2137   // might be impractical."
2138   IRBuilderBase::FastMathFlagGuard Guard(B);
2139   FastMathFlags FMF = CI->getFastMathFlags();
2140   FMF.setNoSignedZeros();
2141   B.setFastMathFlags(FMF);
2142 
2143   Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
2144                                                            : Intrinsic::maxnum;
2145   Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
2146   return copyFlags(
2147       *CI, B.CreateCall(F, {CI->getArgOperand(0), CI->getArgOperand(1)}));
2148 }
2149 
2150 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
2151   Function *LogFn = Log->getCalledFunction();
2152   AttributeList Attrs; // Attributes are only meaningful on the original call
2153   StringRef LogNm = LogFn->getName();
2154   Intrinsic::ID LogID = LogFn->getIntrinsicID();
2155   Module *Mod = Log->getModule();
2156   Type *Ty = Log->getType();
2157   Value *Ret = nullptr;
2158 
2159   if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm))
2160     Ret = optimizeUnaryDoubleFP(Log, B, TLI, true);
2161 
2162   // The earlier call must also be 'fast' in order to do these transforms.
2163   CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2164   if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2165     return Ret;
2166 
2167   LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2168 
2169   // This is only applicable to log(), log2(), log10().
2170   if (TLI->getLibFunc(LogNm, LogLb))
2171     switch (LogLb) {
2172     case LibFunc_logf:
2173       LogID = Intrinsic::log;
2174       ExpLb = LibFunc_expf;
2175       Exp2Lb = LibFunc_exp2f;
2176       Exp10Lb = LibFunc_exp10f;
2177       PowLb = LibFunc_powf;
2178       break;
2179     case LibFunc_log:
2180       LogID = Intrinsic::log;
2181       ExpLb = LibFunc_exp;
2182       Exp2Lb = LibFunc_exp2;
2183       Exp10Lb = LibFunc_exp10;
2184       PowLb = LibFunc_pow;
2185       break;
2186     case LibFunc_logl:
2187       LogID = Intrinsic::log;
2188       ExpLb = LibFunc_expl;
2189       Exp2Lb = LibFunc_exp2l;
2190       Exp10Lb = LibFunc_exp10l;
2191       PowLb = LibFunc_powl;
2192       break;
2193     case LibFunc_log2f:
2194       LogID = Intrinsic::log2;
2195       ExpLb = LibFunc_expf;
2196       Exp2Lb = LibFunc_exp2f;
2197       Exp10Lb = LibFunc_exp10f;
2198       PowLb = LibFunc_powf;
2199       break;
2200     case LibFunc_log2:
2201       LogID = Intrinsic::log2;
2202       ExpLb = LibFunc_exp;
2203       Exp2Lb = LibFunc_exp2;
2204       Exp10Lb = LibFunc_exp10;
2205       PowLb = LibFunc_pow;
2206       break;
2207     case LibFunc_log2l:
2208       LogID = Intrinsic::log2;
2209       ExpLb = LibFunc_expl;
2210       Exp2Lb = LibFunc_exp2l;
2211       Exp10Lb = LibFunc_exp10l;
2212       PowLb = LibFunc_powl;
2213       break;
2214     case LibFunc_log10f:
2215       LogID = Intrinsic::log10;
2216       ExpLb = LibFunc_expf;
2217       Exp2Lb = LibFunc_exp2f;
2218       Exp10Lb = LibFunc_exp10f;
2219       PowLb = LibFunc_powf;
2220       break;
2221     case LibFunc_log10:
2222       LogID = Intrinsic::log10;
2223       ExpLb = LibFunc_exp;
2224       Exp2Lb = LibFunc_exp2;
2225       Exp10Lb = LibFunc_exp10;
2226       PowLb = LibFunc_pow;
2227       break;
2228     case LibFunc_log10l:
2229       LogID = Intrinsic::log10;
2230       ExpLb = LibFunc_expl;
2231       Exp2Lb = LibFunc_exp2l;
2232       Exp10Lb = LibFunc_exp10l;
2233       PowLb = LibFunc_powl;
2234       break;
2235     default:
2236       return Ret;
2237     }
2238   else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2239            LogID == Intrinsic::log10) {
2240     if (Ty->getScalarType()->isFloatTy()) {
2241       ExpLb = LibFunc_expf;
2242       Exp2Lb = LibFunc_exp2f;
2243       Exp10Lb = LibFunc_exp10f;
2244       PowLb = LibFunc_powf;
2245     } else if (Ty->getScalarType()->isDoubleTy()) {
2246       ExpLb = LibFunc_exp;
2247       Exp2Lb = LibFunc_exp2;
2248       Exp10Lb = LibFunc_exp10;
2249       PowLb = LibFunc_pow;
2250     } else
2251       return Ret;
2252   } else
2253     return Ret;
2254 
2255   IRBuilderBase::FastMathFlagGuard Guard(B);
2256   B.setFastMathFlags(FastMathFlags::getFast());
2257 
2258   Intrinsic::ID ArgID = Arg->getIntrinsicID();
2259   LibFunc ArgLb = NotLibFunc;
2260   TLI->getLibFunc(*Arg, ArgLb);
2261 
2262   // log(pow(x,y)) -> y*log(x)
2263   if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
2264     Value *LogX =
2265         Log->doesNotAccessMemory()
2266             ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2267                            Arg->getOperand(0), "log")
2268             : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, Attrs);
2269     Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
2270     // Since pow() may have side effects, e.g. errno,
2271     // dead code elimination may not be trusted to remove it.
2272     substituteInParent(Arg, MulY);
2273     return MulY;
2274   }
2275 
2276   // log(exp{,2,10}(y)) -> y*log({e,2,10})
2277   // TODO: There is no exp10() intrinsic yet.
2278   if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2279            ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2280     Constant *Eul;
2281     if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2282       // FIXME: Add more precise value of e for long double.
2283       Eul = ConstantFP::get(Log->getType(), numbers::e);
2284     else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2285       Eul = ConstantFP::get(Log->getType(), 2.0);
2286     else
2287       Eul = ConstantFP::get(Log->getType(), 10.0);
2288     Value *LogE = Log->doesNotAccessMemory()
2289                       ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2290                                      Eul, "log")
2291                       : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, Attrs);
2292     Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2293     // Since exp() may have side effects, e.g. errno,
2294     // dead code elimination may not be trusted to remove it.
2295     substituteInParent(Arg, MulY);
2296     return MulY;
2297   }
2298 
2299   return Ret;
2300 }
2301 
2302 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2303   Module *M = CI->getModule();
2304   Function *Callee = CI->getCalledFunction();
2305   Value *Ret = nullptr;
2306   // TODO: Once we have a way (other than checking for the existince of the
2307   // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2308   // condition below.
2309   if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2310       (Callee->getName() == "sqrt" ||
2311        Callee->getIntrinsicID() == Intrinsic::sqrt))
2312     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2313 
2314   if (!CI->isFast())
2315     return Ret;
2316 
2317   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
2318   if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2319     return Ret;
2320 
2321   // We're looking for a repeated factor in a multiplication tree,
2322   // so we can do this fold: sqrt(x * x) -> fabs(x);
2323   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2324   Value *Op0 = I->getOperand(0);
2325   Value *Op1 = I->getOperand(1);
2326   Value *RepeatOp = nullptr;
2327   Value *OtherOp = nullptr;
2328   if (Op0 == Op1) {
2329     // Simple match: the operands of the multiply are identical.
2330     RepeatOp = Op0;
2331   } else {
2332     // Look for a more complicated pattern: one of the operands is itself
2333     // a multiply, so search for a common factor in that multiply.
2334     // Note: We don't bother looking any deeper than this first level or for
2335     // variations of this pattern because instcombine's visitFMUL and/or the
2336     // reassociation pass should give us this form.
2337     Value *OtherMul0, *OtherMul1;
2338     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
2339       // Pattern: sqrt((x * y) * z)
2340       if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
2341         // Matched: sqrt((x * x) * z)
2342         RepeatOp = OtherMul0;
2343         OtherOp = Op1;
2344       }
2345     }
2346   }
2347   if (!RepeatOp)
2348     return Ret;
2349 
2350   // Fast math flags for any created instructions should match the sqrt
2351   // and multiply.
2352   IRBuilderBase::FastMathFlagGuard Guard(B);
2353   B.setFastMathFlags(I->getFastMathFlags());
2354 
2355   // If we found a repeated factor, hoist it out of the square root and
2356   // replace it with the fabs of that factor.
2357   Type *ArgType = I->getType();
2358   Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
2359   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
2360   if (OtherOp) {
2361     // If we found a non-repeated factor, we still need to get its square
2362     // root. We then multiply that by the value that was simplified out
2363     // of the square root calculation.
2364     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
2365     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
2366     return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall));
2367   }
2368   return copyFlags(*CI, FabsCall);
2369 }
2370 
2371 // TODO: Generalize to handle any trig function and its inverse.
2372 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) {
2373   Module *M = CI->getModule();
2374   Function *Callee = CI->getCalledFunction();
2375   Value *Ret = nullptr;
2376   StringRef Name = Callee->getName();
2377   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(M, Name))
2378     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2379 
2380   Value *Op1 = CI->getArgOperand(0);
2381   auto *OpC = dyn_cast<CallInst>(Op1);
2382   if (!OpC)
2383     return Ret;
2384 
2385   // Both calls must be 'fast' in order to remove them.
2386   if (!CI->isFast() || !OpC->isFast())
2387     return Ret;
2388 
2389   // tan(atan(x)) -> x
2390   // tanf(atanf(x)) -> x
2391   // tanl(atanl(x)) -> x
2392   LibFunc Func;
2393   Function *F = OpC->getCalledFunction();
2394   if (F && TLI->getLibFunc(F->getName(), Func) &&
2395       isLibFuncEmittable(M, TLI, Func) &&
2396       ((Func == LibFunc_atan && Callee->getName() == "tan") ||
2397        (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
2398        (Func == LibFunc_atanl && Callee->getName() == "tanl")))
2399     Ret = OpC->getArgOperand(0);
2400   return Ret;
2401 }
2402 
2403 static bool isTrigLibCall(CallInst *CI) {
2404   // We can only hope to do anything useful if we can ignore things like errno
2405   // and floating-point exceptions.
2406   // We already checked the prototype.
2407   return CI->hasFnAttr(Attribute::NoUnwind) &&
2408          CI->hasFnAttr(Attribute::ReadNone);
2409 }
2410 
2411 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
2412                              bool UseFloat, Value *&Sin, Value *&Cos,
2413                              Value *&SinCos, const TargetLibraryInfo *TLI) {
2414   Module *M = OrigCallee->getParent();
2415   Type *ArgTy = Arg->getType();
2416   Type *ResTy;
2417   StringRef Name;
2418 
2419   Triple T(OrigCallee->getParent()->getTargetTriple());
2420   if (UseFloat) {
2421     Name = "__sincospif_stret";
2422 
2423     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
2424     // x86_64 can't use {float, float} since that would be returned in both
2425     // xmm0 and xmm1, which isn't what a real struct would do.
2426     ResTy = T.getArch() == Triple::x86_64
2427                 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
2428                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
2429   } else {
2430     Name = "__sincospi_stret";
2431     ResTy = StructType::get(ArgTy, ArgTy);
2432   }
2433 
2434   if (!isLibFuncEmittable(M, TLI, Name))
2435     return false;
2436   LibFunc TheLibFunc;
2437   TLI->getLibFunc(Name, TheLibFunc);
2438   FunctionCallee Callee = getOrInsertLibFunc(
2439       M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
2440 
2441   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
2442     // If the argument is an instruction, it must dominate all uses so put our
2443     // sincos call there.
2444     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
2445   } else {
2446     // Otherwise (e.g. for a constant) the beginning of the function is as
2447     // good a place as any.
2448     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
2449     B.SetInsertPoint(&EntryBB, EntryBB.begin());
2450   }
2451 
2452   SinCos = B.CreateCall(Callee, Arg, "sincospi");
2453 
2454   if (SinCos->getType()->isStructTy()) {
2455     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
2456     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
2457   } else {
2458     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
2459                                  "sinpi");
2460     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
2461                                  "cospi");
2462   }
2463 
2464   return true;
2465 }
2466 
2467 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) {
2468   // Make sure the prototype is as expected, otherwise the rest of the
2469   // function is probably invalid and likely to abort.
2470   if (!isTrigLibCall(CI))
2471     return nullptr;
2472 
2473   Value *Arg = CI->getArgOperand(0);
2474   SmallVector<CallInst *, 1> SinCalls;
2475   SmallVector<CallInst *, 1> CosCalls;
2476   SmallVector<CallInst *, 1> SinCosCalls;
2477 
2478   bool IsFloat = Arg->getType()->isFloatTy();
2479 
2480   // Look for all compatible sinpi, cospi and sincospi calls with the same
2481   // argument. If there are enough (in some sense) we can make the
2482   // substitution.
2483   Function *F = CI->getFunction();
2484   for (User *U : Arg->users())
2485     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
2486 
2487   // It's only worthwhile if both sinpi and cospi are actually used.
2488   if (SinCalls.empty() || CosCalls.empty())
2489     return nullptr;
2490 
2491   Value *Sin, *Cos, *SinCos;
2492   if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
2493                         SinCos, TLI))
2494     return nullptr;
2495 
2496   auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
2497                                  Value *Res) {
2498     for (CallInst *C : Calls)
2499       replaceAllUsesWith(C, Res);
2500   };
2501 
2502   replaceTrigInsts(SinCalls, Sin);
2503   replaceTrigInsts(CosCalls, Cos);
2504   replaceTrigInsts(SinCosCalls, SinCos);
2505 
2506   return nullptr;
2507 }
2508 
2509 void LibCallSimplifier::classifyArgUse(
2510     Value *Val, Function *F, bool IsFloat,
2511     SmallVectorImpl<CallInst *> &SinCalls,
2512     SmallVectorImpl<CallInst *> &CosCalls,
2513     SmallVectorImpl<CallInst *> &SinCosCalls) {
2514   CallInst *CI = dyn_cast<CallInst>(Val);
2515   Module *M = CI->getModule();
2516 
2517   if (!CI || CI->use_empty())
2518     return;
2519 
2520   // Don't consider calls in other functions.
2521   if (CI->getFunction() != F)
2522     return;
2523 
2524   Function *Callee = CI->getCalledFunction();
2525   LibFunc Func;
2526   if (!Callee || !TLI->getLibFunc(*Callee, Func) ||
2527       !isLibFuncEmittable(M, TLI, Func) ||
2528       !isTrigLibCall(CI))
2529     return;
2530 
2531   if (IsFloat) {
2532     if (Func == LibFunc_sinpif)
2533       SinCalls.push_back(CI);
2534     else if (Func == LibFunc_cospif)
2535       CosCalls.push_back(CI);
2536     else if (Func == LibFunc_sincospif_stret)
2537       SinCosCalls.push_back(CI);
2538   } else {
2539     if (Func == LibFunc_sinpi)
2540       SinCalls.push_back(CI);
2541     else if (Func == LibFunc_cospi)
2542       CosCalls.push_back(CI);
2543     else if (Func == LibFunc_sincospi_stret)
2544       SinCosCalls.push_back(CI);
2545   }
2546 }
2547 
2548 //===----------------------------------------------------------------------===//
2549 // Integer Library Call Optimizations
2550 //===----------------------------------------------------------------------===//
2551 
2552 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
2553   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
2554   Value *Op = CI->getArgOperand(0);
2555   Type *ArgType = Op->getType();
2556   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2557                                           Intrinsic::cttz, ArgType);
2558   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
2559   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
2560   V = B.CreateIntCast(V, B.getInt32Ty(), false);
2561 
2562   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
2563   return B.CreateSelect(Cond, V, B.getInt32(0));
2564 }
2565 
2566 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
2567   // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
2568   Value *Op = CI->getArgOperand(0);
2569   Type *ArgType = Op->getType();
2570   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2571                                           Intrinsic::ctlz, ArgType);
2572   Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2573   V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2574                   V);
2575   return B.CreateIntCast(V, CI->getType(), false);
2576 }
2577 
2578 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
2579   // abs(x) -> x <s 0 ? -x : x
2580   // The negation has 'nsw' because abs of INT_MIN is undefined.
2581   Value *X = CI->getArgOperand(0);
2582   Value *IsNeg = B.CreateIsNeg(X);
2583   Value *NegX = B.CreateNSWNeg(X, "neg");
2584   return B.CreateSelect(IsNeg, NegX, X);
2585 }
2586 
2587 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
2588   // isdigit(c) -> (c-'0') <u 10
2589   Value *Op = CI->getArgOperand(0);
2590   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2591   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2592   return B.CreateZExt(Op, CI->getType());
2593 }
2594 
2595 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
2596   // isascii(c) -> c <u 128
2597   Value *Op = CI->getArgOperand(0);
2598   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2599   return B.CreateZExt(Op, CI->getType());
2600 }
2601 
2602 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
2603   // toascii(c) -> c & 0x7f
2604   return B.CreateAnd(CI->getArgOperand(0),
2605                      ConstantInt::get(CI->getType(), 0x7F));
2606 }
2607 
2608 // Fold calls to atoi, atol, and atoll.
2609 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
2610   CI->addParamAttr(0, Attribute::NoCapture);
2611 
2612   StringRef Str;
2613   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2614     return nullptr;
2615 
2616   return convertStrToInt(CI, Str, nullptr, 10, /*AsSigned=*/true, B);
2617 }
2618 
2619 // Fold calls to strtol, strtoll, strtoul, and strtoull.
2620 Value *LibCallSimplifier::optimizeStrToInt(CallInst *CI, IRBuilderBase &B,
2621                                            bool AsSigned) {
2622   Value *EndPtr = CI->getArgOperand(1);
2623   if (isa<ConstantPointerNull>(EndPtr)) {
2624     // With a null EndPtr, this function won't capture the main argument.
2625     // It would be readonly too, except that it still may write to errno.
2626     CI->addParamAttr(0, Attribute::NoCapture);
2627     EndPtr = nullptr;
2628   } else if (!isKnownNonZero(EndPtr, DL))
2629     return nullptr;
2630 
2631   StringRef Str;
2632   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2633     return nullptr;
2634 
2635   if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2636     return convertStrToInt(CI, Str, EndPtr, CInt->getSExtValue(), AsSigned, B);
2637   }
2638 
2639   return nullptr;
2640 }
2641 
2642 //===----------------------------------------------------------------------===//
2643 // Formatting and IO Library Call Optimizations
2644 //===----------------------------------------------------------------------===//
2645 
2646 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
2647 
2648 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
2649                                                  int StreamArg) {
2650   Function *Callee = CI->getCalledFunction();
2651   // Error reporting calls should be cold, mark them as such.
2652   // This applies even to non-builtin calls: it is only a hint and applies to
2653   // functions that the frontend might not understand as builtins.
2654 
2655   // This heuristic was suggested in:
2656   // Improving Static Branch Prediction in a Compiler
2657   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2658   // Proceedings of PACT'98, Oct. 1998, IEEE
2659   if (!CI->hasFnAttr(Attribute::Cold) &&
2660       isReportingError(Callee, CI, StreamArg)) {
2661     CI->addFnAttr(Attribute::Cold);
2662   }
2663 
2664   return nullptr;
2665 }
2666 
2667 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
2668   if (!Callee || !Callee->isDeclaration())
2669     return false;
2670 
2671   if (StreamArg < 0)
2672     return true;
2673 
2674   // These functions might be considered cold, but only if their stream
2675   // argument is stderr.
2676 
2677   if (StreamArg >= (int)CI->arg_size())
2678     return false;
2679   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2680   if (!LI)
2681     return false;
2682   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2683   if (!GV || !GV->isDeclaration())
2684     return false;
2685   return GV->getName() == "stderr";
2686 }
2687 
2688 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
2689   // Check for a fixed format string.
2690   StringRef FormatStr;
2691   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
2692     return nullptr;
2693 
2694   // Empty format string -> noop.
2695   if (FormatStr.empty()) // Tolerate printf's declared void.
2696     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
2697 
2698   // Do not do any of the following transformations if the printf return value
2699   // is used, in general the printf return value is not compatible with either
2700   // putchar() or puts().
2701   if (!CI->use_empty())
2702     return nullptr;
2703 
2704   // printf("x") -> putchar('x'), even for "%" and "%%".
2705   if (FormatStr.size() == 1 || FormatStr == "%%")
2706     return copyFlags(*CI, emitPutChar(B.getInt32(FormatStr[0]), B, TLI));
2707 
2708   // Try to remove call or emit putchar/puts.
2709   if (FormatStr == "%s" && CI->arg_size() > 1) {
2710     StringRef OperandStr;
2711     if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
2712       return nullptr;
2713     // printf("%s", "") --> NOP
2714     if (OperandStr.empty())
2715       return (Value *)CI;
2716     // printf("%s", "a") --> putchar('a')
2717     if (OperandStr.size() == 1)
2718       return copyFlags(*CI, emitPutChar(B.getInt32(OperandStr[0]), B, TLI));
2719     // printf("%s", str"\n") --> puts(str)
2720     if (OperandStr.back() == '\n') {
2721       OperandStr = OperandStr.drop_back();
2722       Value *GV = B.CreateGlobalString(OperandStr, "str");
2723       return copyFlags(*CI, emitPutS(GV, B, TLI));
2724     }
2725     return nullptr;
2726   }
2727 
2728   // printf("foo\n") --> puts("foo")
2729   if (FormatStr.back() == '\n' &&
2730       !FormatStr.contains('%')) { // No format characters.
2731     // Create a string literal with no \n on it.  We expect the constant merge
2732     // pass to be run after this pass, to merge duplicate strings.
2733     FormatStr = FormatStr.drop_back();
2734     Value *GV = B.CreateGlobalString(FormatStr, "str");
2735     return copyFlags(*CI, emitPutS(GV, B, TLI));
2736   }
2737 
2738   // Optimize specific format strings.
2739   // printf("%c", chr) --> putchar(chr)
2740   if (FormatStr == "%c" && CI->arg_size() > 1 &&
2741       CI->getArgOperand(1)->getType()->isIntegerTy())
2742     return copyFlags(*CI, emitPutChar(CI->getArgOperand(1), B, TLI));
2743 
2744   // printf("%s\n", str) --> puts(str)
2745   if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
2746       CI->getArgOperand(1)->getType()->isPointerTy())
2747     return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
2748   return nullptr;
2749 }
2750 
2751 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
2752 
2753   Module *M = CI->getModule();
2754   Function *Callee = CI->getCalledFunction();
2755   FunctionType *FT = Callee->getFunctionType();
2756   if (Value *V = optimizePrintFString(CI, B)) {
2757     return V;
2758   }
2759 
2760   // printf(format, ...) -> iprintf(format, ...) if no floating point
2761   // arguments.
2762   if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
2763       !callHasFloatingPointArgument(CI)) {
2764     FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
2765                                                   Callee->getAttributes());
2766     CallInst *New = cast<CallInst>(CI->clone());
2767     New->setCalledFunction(IPrintFFn);
2768     B.Insert(New);
2769     return New;
2770   }
2771 
2772   // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2773   // arguments.
2774   if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
2775       !callHasFP128Argument(CI)) {
2776     auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
2777                                             Callee->getAttributes());
2778     CallInst *New = cast<CallInst>(CI->clone());
2779     New->setCalledFunction(SmallPrintFFn);
2780     B.Insert(New);
2781     return New;
2782   }
2783 
2784   annotateNonNullNoUndefBasedOnAccess(CI, 0);
2785   return nullptr;
2786 }
2787 
2788 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
2789                                                 IRBuilderBase &B) {
2790   // Check for a fixed format string.
2791   StringRef FormatStr;
2792   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2793     return nullptr;
2794 
2795   // If we just have a format string (nothing else crazy) transform it.
2796   Value *Dest = CI->getArgOperand(0);
2797   if (CI->arg_size() == 2) {
2798     // Make sure there's no % in the constant array.  We could try to handle
2799     // %% -> % in the future if we cared.
2800     if (FormatStr.contains('%'))
2801       return nullptr; // we found a format specifier, bail out.
2802 
2803     // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2804     B.CreateMemCpy(
2805         Dest, Align(1), CI->getArgOperand(1), Align(1),
2806         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2807                          FormatStr.size() + 1)); // Copy the null byte.
2808     return ConstantInt::get(CI->getType(), FormatStr.size());
2809   }
2810 
2811   // The remaining optimizations require the format string to be "%s" or "%c"
2812   // and have an extra operand.
2813   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
2814     return nullptr;
2815 
2816   // Decode the second character of the format string.
2817   if (FormatStr[1] == 'c') {
2818     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2819     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2820       return nullptr;
2821     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2822     Value *Ptr = castToCStr(Dest, B);
2823     B.CreateStore(V, Ptr);
2824     Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2825     B.CreateStore(B.getInt8(0), Ptr);
2826 
2827     return ConstantInt::get(CI->getType(), 1);
2828   }
2829 
2830   if (FormatStr[1] == 's') {
2831     // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2832     // strlen(str)+1)
2833     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2834       return nullptr;
2835 
2836     if (CI->use_empty())
2837       // sprintf(dest, "%s", str) -> strcpy(dest, str)
2838       return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
2839 
2840     uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
2841     if (SrcLen) {
2842       B.CreateMemCpy(
2843           Dest, Align(1), CI->getArgOperand(2), Align(1),
2844           ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen));
2845       // Returns total number of characters written without null-character.
2846       return ConstantInt::get(CI->getType(), SrcLen - 1);
2847     } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
2848       // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
2849       // Handle mismatched pointer types (goes away with typeless pointers?).
2850       V = B.CreatePointerCast(V, B.getInt8PtrTy());
2851       Dest = B.CreatePointerCast(Dest, B.getInt8PtrTy());
2852       Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest);
2853       return B.CreateIntCast(PtrDiff, CI->getType(), false);
2854     }
2855 
2856     bool OptForSize = CI->getFunction()->hasOptSize() ||
2857                       llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
2858                                                   PGSOQueryType::IRPass);
2859     if (OptForSize)
2860       return nullptr;
2861 
2862     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
2863     if (!Len)
2864       return nullptr;
2865     Value *IncLen =
2866         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2867     B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
2868 
2869     // The sprintf result is the unincremented number of bytes in the string.
2870     return B.CreateIntCast(Len, CI->getType(), false);
2871   }
2872   return nullptr;
2873 }
2874 
2875 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
2876   Module *M = CI->getModule();
2877   Function *Callee = CI->getCalledFunction();
2878   FunctionType *FT = Callee->getFunctionType();
2879   if (Value *V = optimizeSPrintFString(CI, B)) {
2880     return V;
2881   }
2882 
2883   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2884   // point arguments.
2885   if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
2886       !callHasFloatingPointArgument(CI)) {
2887     FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
2888                                                    FT, Callee->getAttributes());
2889     CallInst *New = cast<CallInst>(CI->clone());
2890     New->setCalledFunction(SIPrintFFn);
2891     B.Insert(New);
2892     return New;
2893   }
2894 
2895   // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2896   // floating point arguments.
2897   if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
2898       !callHasFP128Argument(CI)) {
2899     auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
2900                                              Callee->getAttributes());
2901     CallInst *New = cast<CallInst>(CI->clone());
2902     New->setCalledFunction(SmallSPrintFFn);
2903     B.Insert(New);
2904     return New;
2905   }
2906 
2907   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
2908   return nullptr;
2909 }
2910 
2911 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
2912                                                  IRBuilderBase &B) {
2913   // Check for size
2914   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2915   if (!Size)
2916     return nullptr;
2917 
2918   uint64_t N = Size->getZExtValue();
2919   // Check for a fixed format string.
2920   StringRef FormatStr;
2921   if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2922     return nullptr;
2923 
2924   // If we just have a format string (nothing else crazy) transform it.
2925   if (CI->arg_size() == 3) {
2926     // Make sure there's no % in the constant array.  We could try to handle
2927     // %% -> % in the future if we cared.
2928     if (FormatStr.contains('%'))
2929       return nullptr; // we found a format specifier, bail out.
2930 
2931     if (N == 0)
2932       return ConstantInt::get(CI->getType(), FormatStr.size());
2933     else if (N < FormatStr.size() + 1)
2934       return nullptr;
2935 
2936     // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
2937     // strlen(fmt)+1)
2938     copyFlags(
2939         *CI,
2940         B.CreateMemCpy(
2941             CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1),
2942             ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2943                              FormatStr.size() + 1))); // Copy the null byte.
2944     return ConstantInt::get(CI->getType(), FormatStr.size());
2945   }
2946 
2947   // The remaining optimizations require the format string to be "%s" or "%c"
2948   // and have an extra operand.
2949   if (FormatStr.size() == 2 && FormatStr[0] == '%' && CI->arg_size() == 4) {
2950 
2951     // Decode the second character of the format string.
2952     if (FormatStr[1] == 'c') {
2953       if (N == 0)
2954         return ConstantInt::get(CI->getType(), 1);
2955       else if (N == 1)
2956         return nullptr;
2957 
2958       // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2959       if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2960         return nullptr;
2961       Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2962       Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2963       B.CreateStore(V, Ptr);
2964       Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2965       B.CreateStore(B.getInt8(0), Ptr);
2966 
2967       return ConstantInt::get(CI->getType(), 1);
2968     }
2969 
2970     if (FormatStr[1] == 's') {
2971       // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2972       StringRef Str;
2973       if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2974         return nullptr;
2975 
2976       if (N == 0)
2977         return ConstantInt::get(CI->getType(), Str.size());
2978       else if (N < Str.size() + 1)
2979         return nullptr;
2980 
2981       copyFlags(
2982           *CI, B.CreateMemCpy(CI->getArgOperand(0), Align(1),
2983                               CI->getArgOperand(3), Align(1),
2984                               ConstantInt::get(CI->getType(), Str.size() + 1)));
2985 
2986       // The snprintf result is the unincremented number of bytes in the string.
2987       return ConstantInt::get(CI->getType(), Str.size());
2988     }
2989   }
2990   return nullptr;
2991 }
2992 
2993 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
2994   if (Value *V = optimizeSnPrintFString(CI, B)) {
2995     return V;
2996   }
2997 
2998   if (isKnownNonZero(CI->getOperand(1), DL))
2999     annotateNonNullNoUndefBasedOnAccess(CI, 0);
3000   return nullptr;
3001 }
3002 
3003 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
3004                                                 IRBuilderBase &B) {
3005   optimizeErrorReporting(CI, B, 0);
3006 
3007   // All the optimizations depend on the format string.
3008   StringRef FormatStr;
3009   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
3010     return nullptr;
3011 
3012   // Do not do any of the following transformations if the fprintf return
3013   // value is used, in general the fprintf return value is not compatible
3014   // with fwrite(), fputc() or fputs().
3015   if (!CI->use_empty())
3016     return nullptr;
3017 
3018   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
3019   if (CI->arg_size() == 2) {
3020     // Could handle %% -> % if we cared.
3021     if (FormatStr.contains('%'))
3022       return nullptr; // We found a format specifier.
3023 
3024     return copyFlags(
3025         *CI, emitFWrite(CI->getArgOperand(1),
3026                         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
3027                                          FormatStr.size()),
3028                         CI->getArgOperand(0), B, DL, TLI));
3029   }
3030 
3031   // The remaining optimizations require the format string to be "%s" or "%c"
3032   // and have an extra operand.
3033   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
3034     return nullptr;
3035 
3036   // Decode the second character of the format string.
3037   if (FormatStr[1] == 'c') {
3038     // fprintf(F, "%c", chr) --> fputc(chr, F)
3039     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
3040       return nullptr;
3041     return copyFlags(
3042         *CI, emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
3043   }
3044 
3045   if (FormatStr[1] == 's') {
3046     // fprintf(F, "%s", str) --> fputs(str, F)
3047     if (!CI->getArgOperand(2)->getType()->isPointerTy())
3048       return nullptr;
3049     return copyFlags(
3050         *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
3051   }
3052   return nullptr;
3053 }
3054 
3055 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
3056   Module *M = CI->getModule();
3057   Function *Callee = CI->getCalledFunction();
3058   FunctionType *FT = Callee->getFunctionType();
3059   if (Value *V = optimizeFPrintFString(CI, B)) {
3060     return V;
3061   }
3062 
3063   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
3064   // floating point arguments.
3065   if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
3066       !callHasFloatingPointArgument(CI)) {
3067     FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
3068                                                    FT, Callee->getAttributes());
3069     CallInst *New = cast<CallInst>(CI->clone());
3070     New->setCalledFunction(FIPrintFFn);
3071     B.Insert(New);
3072     return New;
3073   }
3074 
3075   // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
3076   // 128-bit floating point arguments.
3077   if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
3078       !callHasFP128Argument(CI)) {
3079     auto SmallFPrintFFn =
3080         getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
3081                            Callee->getAttributes());
3082     CallInst *New = cast<CallInst>(CI->clone());
3083     New->setCalledFunction(SmallFPrintFFn);
3084     B.Insert(New);
3085     return New;
3086   }
3087 
3088   return nullptr;
3089 }
3090 
3091 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
3092   optimizeErrorReporting(CI, B, 3);
3093 
3094   // Get the element size and count.
3095   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3096   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
3097   if (SizeC && CountC) {
3098     uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
3099 
3100     // If this is writing zero records, remove the call (it's a noop).
3101     if (Bytes == 0)
3102       return ConstantInt::get(CI->getType(), 0);
3103 
3104     // If this is writing one byte, turn it into fputc.
3105     // This optimisation is only valid, if the return value is unused.
3106     if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
3107       Value *Char = B.CreateLoad(B.getInt8Ty(),
3108                                  castToCStr(CI->getArgOperand(0), B), "char");
3109       Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
3110       return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
3111     }
3112   }
3113 
3114   return nullptr;
3115 }
3116 
3117 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
3118   optimizeErrorReporting(CI, B, 1);
3119 
3120   // Don't rewrite fputs to fwrite when optimising for size because fwrite
3121   // requires more arguments and thus extra MOVs are required.
3122   bool OptForSize = CI->getFunction()->hasOptSize() ||
3123                     llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3124                                                 PGSOQueryType::IRPass);
3125   if (OptForSize)
3126     return nullptr;
3127 
3128   // We can't optimize if return value is used.
3129   if (!CI->use_empty())
3130     return nullptr;
3131 
3132   // fputs(s,F) --> fwrite(s,strlen(s),1,F)
3133   uint64_t Len = GetStringLength(CI->getArgOperand(0));
3134   if (!Len)
3135     return nullptr;
3136 
3137   // Known to have no uses (see above).
3138   return copyFlags(
3139       *CI,
3140       emitFWrite(CI->getArgOperand(0),
3141                  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
3142                  CI->getArgOperand(1), B, DL, TLI));
3143 }
3144 
3145 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
3146   annotateNonNullNoUndefBasedOnAccess(CI, 0);
3147   if (!CI->use_empty())
3148     return nullptr;
3149 
3150   // Check for a constant string.
3151   // puts("") -> putchar('\n')
3152   StringRef Str;
3153   if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
3154     return copyFlags(*CI, emitPutChar(B.getInt32('\n'), B, TLI));
3155 
3156   return nullptr;
3157 }
3158 
3159 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
3160   // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
3161   return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
3162                                         CI->getArgOperand(0), Align(1),
3163                                         CI->getArgOperand(2)));
3164 }
3165 
3166 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
3167   SmallString<20> FloatFuncName = FuncName;
3168   FloatFuncName += 'f';
3169   return isLibFuncEmittable(M, TLI, FloatFuncName);
3170 }
3171 
3172 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
3173                                                       IRBuilderBase &Builder) {
3174   Module *M = CI->getModule();
3175   LibFunc Func;
3176   Function *Callee = CI->getCalledFunction();
3177   // Check for string/memory library functions.
3178   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3179     // Make sure we never change the calling convention.
3180     assert(
3181         (ignoreCallingConv(Func) ||
3182          TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) &&
3183         "Optimizing string/memory libcall would change the calling convention");
3184     switch (Func) {
3185     case LibFunc_strcat:
3186       return optimizeStrCat(CI, Builder);
3187     case LibFunc_strncat:
3188       return optimizeStrNCat(CI, Builder);
3189     case LibFunc_strchr:
3190       return optimizeStrChr(CI, Builder);
3191     case LibFunc_strrchr:
3192       return optimizeStrRChr(CI, Builder);
3193     case LibFunc_strcmp:
3194       return optimizeStrCmp(CI, Builder);
3195     case LibFunc_strncmp:
3196       return optimizeStrNCmp(CI, Builder);
3197     case LibFunc_strcpy:
3198       return optimizeStrCpy(CI, Builder);
3199     case LibFunc_stpcpy:
3200       return optimizeStpCpy(CI, Builder);
3201     case LibFunc_strncpy:
3202       return optimizeStrNCpy(CI, Builder);
3203     case LibFunc_strlen:
3204       return optimizeStrLen(CI, Builder);
3205     case LibFunc_strnlen:
3206       return optimizeStrNLen(CI, Builder);
3207     case LibFunc_strpbrk:
3208       return optimizeStrPBrk(CI, Builder);
3209     case LibFunc_strndup:
3210       return optimizeStrNDup(CI, Builder);
3211     case LibFunc_strtol:
3212     case LibFunc_strtod:
3213     case LibFunc_strtof:
3214     case LibFunc_strtoul:
3215     case LibFunc_strtoll:
3216     case LibFunc_strtold:
3217     case LibFunc_strtoull:
3218       return optimizeStrTo(CI, Builder);
3219     case LibFunc_strspn:
3220       return optimizeStrSpn(CI, Builder);
3221     case LibFunc_strcspn:
3222       return optimizeStrCSpn(CI, Builder);
3223     case LibFunc_strstr:
3224       return optimizeStrStr(CI, Builder);
3225     case LibFunc_memchr:
3226       return optimizeMemChr(CI, Builder);
3227     case LibFunc_memrchr:
3228       return optimizeMemRChr(CI, Builder);
3229     case LibFunc_bcmp:
3230       return optimizeBCmp(CI, Builder);
3231     case LibFunc_memcmp:
3232       return optimizeMemCmp(CI, Builder);
3233     case LibFunc_memcpy:
3234       return optimizeMemCpy(CI, Builder);
3235     case LibFunc_memccpy:
3236       return optimizeMemCCpy(CI, Builder);
3237     case LibFunc_mempcpy:
3238       return optimizeMemPCpy(CI, Builder);
3239     case LibFunc_memmove:
3240       return optimizeMemMove(CI, Builder);
3241     case LibFunc_memset:
3242       return optimizeMemSet(CI, Builder);
3243     case LibFunc_realloc:
3244       return optimizeRealloc(CI, Builder);
3245     case LibFunc_wcslen:
3246       return optimizeWcslen(CI, Builder);
3247     case LibFunc_bcopy:
3248       return optimizeBCopy(CI, Builder);
3249     default:
3250       break;
3251     }
3252   }
3253   return nullptr;
3254 }
3255 
3256 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
3257                                                        LibFunc Func,
3258                                                        IRBuilderBase &Builder) {
3259   const Module *M = CI->getModule();
3260 
3261   // Don't optimize calls that require strict floating point semantics.
3262   if (CI->isStrictFP())
3263     return nullptr;
3264 
3265   if (Value *V = optimizeTrigReflections(CI, Func, Builder))
3266     return V;
3267 
3268   switch (Func) {
3269   case LibFunc_sinpif:
3270   case LibFunc_sinpi:
3271   case LibFunc_cospif:
3272   case LibFunc_cospi:
3273     return optimizeSinCosPi(CI, Builder);
3274   case LibFunc_powf:
3275   case LibFunc_pow:
3276   case LibFunc_powl:
3277     return optimizePow(CI, Builder);
3278   case LibFunc_exp2l:
3279   case LibFunc_exp2:
3280   case LibFunc_exp2f:
3281     return optimizeExp2(CI, Builder);
3282   case LibFunc_fabsf:
3283   case LibFunc_fabs:
3284   case LibFunc_fabsl:
3285     return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
3286   case LibFunc_sqrtf:
3287   case LibFunc_sqrt:
3288   case LibFunc_sqrtl:
3289     return optimizeSqrt(CI, Builder);
3290   case LibFunc_logf:
3291   case LibFunc_log:
3292   case LibFunc_logl:
3293   case LibFunc_log10f:
3294   case LibFunc_log10:
3295   case LibFunc_log10l:
3296   case LibFunc_log1pf:
3297   case LibFunc_log1p:
3298   case LibFunc_log1pl:
3299   case LibFunc_log2f:
3300   case LibFunc_log2:
3301   case LibFunc_log2l:
3302   case LibFunc_logbf:
3303   case LibFunc_logb:
3304   case LibFunc_logbl:
3305     return optimizeLog(CI, Builder);
3306   case LibFunc_tan:
3307   case LibFunc_tanf:
3308   case LibFunc_tanl:
3309     return optimizeTan(CI, Builder);
3310   case LibFunc_ceil:
3311     return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
3312   case LibFunc_floor:
3313     return replaceUnaryCall(CI, Builder, Intrinsic::floor);
3314   case LibFunc_round:
3315     return replaceUnaryCall(CI, Builder, Intrinsic::round);
3316   case LibFunc_roundeven:
3317     return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
3318   case LibFunc_nearbyint:
3319     return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
3320   case LibFunc_rint:
3321     return replaceUnaryCall(CI, Builder, Intrinsic::rint);
3322   case LibFunc_trunc:
3323     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
3324   case LibFunc_acos:
3325   case LibFunc_acosh:
3326   case LibFunc_asin:
3327   case LibFunc_asinh:
3328   case LibFunc_atan:
3329   case LibFunc_atanh:
3330   case LibFunc_cbrt:
3331   case LibFunc_cosh:
3332   case LibFunc_exp:
3333   case LibFunc_exp10:
3334   case LibFunc_expm1:
3335   case LibFunc_cos:
3336   case LibFunc_sin:
3337   case LibFunc_sinh:
3338   case LibFunc_tanh:
3339     if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
3340       return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
3341     return nullptr;
3342   case LibFunc_copysign:
3343     if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
3344       return optimizeBinaryDoubleFP(CI, Builder, TLI);
3345     return nullptr;
3346   case LibFunc_fminf:
3347   case LibFunc_fmin:
3348   case LibFunc_fminl:
3349   case LibFunc_fmaxf:
3350   case LibFunc_fmax:
3351   case LibFunc_fmaxl:
3352     return optimizeFMinFMax(CI, Builder);
3353   case LibFunc_cabs:
3354   case LibFunc_cabsf:
3355   case LibFunc_cabsl:
3356     return optimizeCAbs(CI, Builder);
3357   default:
3358     return nullptr;
3359   }
3360 }
3361 
3362 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) {
3363   Module *M = CI->getModule();
3364   assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
3365 
3366   // TODO: Split out the code below that operates on FP calls so that
3367   //       we can all non-FP calls with the StrictFP attribute to be
3368   //       optimized.
3369   if (CI->isNoBuiltin())
3370     return nullptr;
3371 
3372   LibFunc Func;
3373   Function *Callee = CI->getCalledFunction();
3374   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3375 
3376   SmallVector<OperandBundleDef, 2> OpBundles;
3377   CI->getOperandBundlesAsDefs(OpBundles);
3378 
3379   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3380   Builder.setDefaultOperandBundles(OpBundles);
3381 
3382   // Command-line parameter overrides instruction attribute.
3383   // This can't be moved to optimizeFloatingPointLibCall() because it may be
3384   // used by the intrinsic optimizations.
3385   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
3386     UnsafeFPShrink = EnableUnsafeFPShrink;
3387   else if (isa<FPMathOperator>(CI) && CI->isFast())
3388     UnsafeFPShrink = true;
3389 
3390   // First, check for intrinsics.
3391   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
3392     if (!IsCallingConvC)
3393       return nullptr;
3394     // The FP intrinsics have corresponding constrained versions so we don't
3395     // need to check for the StrictFP attribute here.
3396     switch (II->getIntrinsicID()) {
3397     case Intrinsic::pow:
3398       return optimizePow(CI, Builder);
3399     case Intrinsic::exp2:
3400       return optimizeExp2(CI, Builder);
3401     case Intrinsic::log:
3402     case Intrinsic::log2:
3403     case Intrinsic::log10:
3404       return optimizeLog(CI, Builder);
3405     case Intrinsic::sqrt:
3406       return optimizeSqrt(CI, Builder);
3407     case Intrinsic::memset:
3408       return optimizeMemSet(CI, Builder);
3409     case Intrinsic::memcpy:
3410       return optimizeMemCpy(CI, Builder);
3411     case Intrinsic::memmove:
3412       return optimizeMemMove(CI, Builder);
3413     default:
3414       return nullptr;
3415     }
3416   }
3417 
3418   // Also try to simplify calls to fortified library functions.
3419   if (Value *SimplifiedFortifiedCI =
3420           FortifiedSimplifier.optimizeCall(CI, Builder)) {
3421     // Try to further simplify the result.
3422     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
3423     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
3424       // Ensure that SimplifiedCI's uses are complete, since some calls have
3425       // their uses analyzed.
3426       replaceAllUsesWith(CI, SimplifiedCI);
3427 
3428       // Set insertion point to SimplifiedCI to guarantee we reach all uses
3429       // we might replace later on.
3430       IRBuilderBase::InsertPointGuard Guard(Builder);
3431       Builder.SetInsertPoint(SimplifiedCI);
3432       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
3433         // If we were able to further simplify, remove the now redundant call.
3434         substituteInParent(SimplifiedCI, V);
3435         return V;
3436       }
3437     }
3438     return SimplifiedFortifiedCI;
3439   }
3440 
3441   // Then check for known library functions.
3442   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3443     // We never change the calling convention.
3444     if (!ignoreCallingConv(Func) && !IsCallingConvC)
3445       return nullptr;
3446     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
3447       return V;
3448     if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
3449       return V;
3450     switch (Func) {
3451     case LibFunc_ffs:
3452     case LibFunc_ffsl:
3453     case LibFunc_ffsll:
3454       return optimizeFFS(CI, Builder);
3455     case LibFunc_fls:
3456     case LibFunc_flsl:
3457     case LibFunc_flsll:
3458       return optimizeFls(CI, Builder);
3459     case LibFunc_abs:
3460     case LibFunc_labs:
3461     case LibFunc_llabs:
3462       return optimizeAbs(CI, Builder);
3463     case LibFunc_isdigit:
3464       return optimizeIsDigit(CI, Builder);
3465     case LibFunc_isascii:
3466       return optimizeIsAscii(CI, Builder);
3467     case LibFunc_toascii:
3468       return optimizeToAscii(CI, Builder);
3469     case LibFunc_atoi:
3470     case LibFunc_atol:
3471     case LibFunc_atoll:
3472       return optimizeAtoi(CI, Builder);
3473     case LibFunc_strtol:
3474     case LibFunc_strtoll:
3475       return optimizeStrToInt(CI, Builder, /*AsSigned=*/true);
3476     case LibFunc_strtoul:
3477     case LibFunc_strtoull:
3478       return optimizeStrToInt(CI, Builder, /*AsSigned=*/false);
3479     case LibFunc_printf:
3480       return optimizePrintF(CI, Builder);
3481     case LibFunc_sprintf:
3482       return optimizeSPrintF(CI, Builder);
3483     case LibFunc_snprintf:
3484       return optimizeSnPrintF(CI, Builder);
3485     case LibFunc_fprintf:
3486       return optimizeFPrintF(CI, Builder);
3487     case LibFunc_fwrite:
3488       return optimizeFWrite(CI, Builder);
3489     case LibFunc_fputs:
3490       return optimizeFPuts(CI, Builder);
3491     case LibFunc_puts:
3492       return optimizePuts(CI, Builder);
3493     case LibFunc_perror:
3494       return optimizeErrorReporting(CI, Builder);
3495     case LibFunc_vfprintf:
3496     case LibFunc_fiprintf:
3497       return optimizeErrorReporting(CI, Builder, 0);
3498     default:
3499       return nullptr;
3500     }
3501   }
3502   return nullptr;
3503 }
3504 
3505 LibCallSimplifier::LibCallSimplifier(
3506     const DataLayout &DL, const TargetLibraryInfo *TLI,
3507     OptimizationRemarkEmitter &ORE,
3508     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
3509     function_ref<void(Instruction *, Value *)> Replacer,
3510     function_ref<void(Instruction *)> Eraser)
3511     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
3512       Replacer(Replacer), Eraser(Eraser) {}
3513 
3514 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
3515   // Indirect through the replacer used in this instance.
3516   Replacer(I, With);
3517 }
3518 
3519 void LibCallSimplifier::eraseFromParent(Instruction *I) {
3520   Eraser(I);
3521 }
3522 
3523 // TODO:
3524 //   Additional cases that we need to add to this file:
3525 //
3526 // cbrt:
3527 //   * cbrt(expN(X))  -> expN(x/3)
3528 //   * cbrt(sqrt(x))  -> pow(x,1/6)
3529 //   * cbrt(cbrt(x))  -> pow(x,1/9)
3530 //
3531 // exp, expf, expl:
3532 //   * exp(log(x))  -> x
3533 //
3534 // log, logf, logl:
3535 //   * log(exp(x))   -> x
3536 //   * log(exp(y))   -> y*log(e)
3537 //   * log(exp10(y)) -> y*log(10)
3538 //   * log(sqrt(x))  -> 0.5*log(x)
3539 //
3540 // pow, powf, powl:
3541 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
3542 //   * pow(pow(x,y),z)-> pow(x,y*z)
3543 //
3544 // signbit:
3545 //   * signbit(cnst) -> cnst'
3546 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
3547 //
3548 // sqrt, sqrtf, sqrtl:
3549 //   * sqrt(expN(x))  -> expN(x*0.5)
3550 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
3551 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
3552 //
3553 
3554 //===----------------------------------------------------------------------===//
3555 // Fortified Library Call Optimizations
3556 //===----------------------------------------------------------------------===//
3557 
3558 bool
3559 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
3560                                                     unsigned ObjSizeOp,
3561                                                     Optional<unsigned> SizeOp,
3562                                                     Optional<unsigned> StrOp,
3563                                                     Optional<unsigned> FlagOp) {
3564   // If this function takes a flag argument, the implementation may use it to
3565   // perform extra checks. Don't fold into the non-checking variant.
3566   if (FlagOp) {
3567     ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
3568     if (!Flag || !Flag->isZero())
3569       return false;
3570   }
3571 
3572   if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
3573     return true;
3574 
3575   if (ConstantInt *ObjSizeCI =
3576           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
3577     if (ObjSizeCI->isMinusOne())
3578       return true;
3579     // If the object size wasn't -1 (unknown), bail out if we were asked to.
3580     if (OnlyLowerUnknownSize)
3581       return false;
3582     if (StrOp) {
3583       uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
3584       // If the length is 0 we don't know how long it is and so we can't
3585       // remove the check.
3586       if (Len)
3587         annotateDereferenceableBytes(CI, *StrOp, Len);
3588       else
3589         return false;
3590       return ObjSizeCI->getZExtValue() >= Len;
3591     }
3592 
3593     if (SizeOp) {
3594       if (ConstantInt *SizeCI =
3595               dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
3596         return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
3597     }
3598   }
3599   return false;
3600 }
3601 
3602 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
3603                                                      IRBuilderBase &B) {
3604   if (isFortifiedCallFoldable(CI, 3, 2)) {
3605     CallInst *NewCI =
3606         B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3607                        Align(1), CI->getArgOperand(2));
3608     NewCI->setAttributes(CI->getAttributes());
3609     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3610     copyFlags(*CI, NewCI);
3611     return CI->getArgOperand(0);
3612   }
3613   return nullptr;
3614 }
3615 
3616 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
3617                                                       IRBuilderBase &B) {
3618   if (isFortifiedCallFoldable(CI, 3, 2)) {
3619     CallInst *NewCI =
3620         B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3621                         Align(1), CI->getArgOperand(2));
3622     NewCI->setAttributes(CI->getAttributes());
3623     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3624     copyFlags(*CI, NewCI);
3625     return CI->getArgOperand(0);
3626   }
3627   return nullptr;
3628 }
3629 
3630 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
3631                                                      IRBuilderBase &B) {
3632   if (isFortifiedCallFoldable(CI, 3, 2)) {
3633     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
3634     CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
3635                                      CI->getArgOperand(2), Align(1));
3636     NewCI->setAttributes(CI->getAttributes());
3637     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3638     copyFlags(*CI, NewCI);
3639     return CI->getArgOperand(0);
3640   }
3641   return nullptr;
3642 }
3643 
3644 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
3645                                                       IRBuilderBase &B) {
3646   const DataLayout &DL = CI->getModule()->getDataLayout();
3647   if (isFortifiedCallFoldable(CI, 3, 2))
3648     if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3649                                   CI->getArgOperand(2), B, DL, TLI)) {
3650       CallInst *NewCI = cast<CallInst>(Call);
3651       NewCI->setAttributes(CI->getAttributes());
3652       NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3653       return copyFlags(*CI, NewCI);
3654     }
3655   return nullptr;
3656 }
3657 
3658 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3659                                                       IRBuilderBase &B,
3660                                                       LibFunc Func) {
3661   const DataLayout &DL = CI->getModule()->getDataLayout();
3662   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3663         *ObjSize = CI->getArgOperand(2);
3664 
3665   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
3666   if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
3667     Value *StrLen = emitStrLen(Src, B, DL, TLI);
3668     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
3669   }
3670 
3671   // If a) we don't have any length information, or b) we know this will
3672   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3673   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3674   // TODO: It might be nice to get a maximum length out of the possible
3675   // string lengths for varying.
3676   if (isFortifiedCallFoldable(CI, 2, None, 1)) {
3677     if (Func == LibFunc_strcpy_chk)
3678       return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
3679     else
3680       return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
3681   }
3682 
3683   if (OnlyLowerUnknownSize)
3684     return nullptr;
3685 
3686   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
3687   uint64_t Len = GetStringLength(Src);
3688   if (Len)
3689     annotateDereferenceableBytes(CI, 1, Len);
3690   else
3691     return nullptr;
3692 
3693   // FIXME: There is really no guarantee that sizeof(size_t) is equal to
3694   // sizeof(int*) for every target. So the assumption used here to derive the
3695   // SizeTBits based on the size of an integer pointer in address space zero
3696   // isn't always valid.
3697   Type *SizeTTy = DL.getIntPtrType(CI->getContext(), /*AddressSpace=*/0);
3698   Value *LenV = ConstantInt::get(SizeTTy, Len);
3699   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
3700   // If the function was an __stpcpy_chk, and we were able to fold it into
3701   // a __memcpy_chk, we still need to return the correct end pointer.
3702   if (Ret && Func == LibFunc_stpcpy_chk)
3703     return B.CreateInBoundsGEP(B.getInt8Ty(), Dst,
3704                                ConstantInt::get(SizeTTy, Len - 1));
3705   return copyFlags(*CI, cast<CallInst>(Ret));
3706 }
3707 
3708 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
3709                                                      IRBuilderBase &B) {
3710   if (isFortifiedCallFoldable(CI, 1, None, 0))
3711     return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
3712                                      CI->getModule()->getDataLayout(), TLI));
3713   return nullptr;
3714 }
3715 
3716 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3717                                                        IRBuilderBase &B,
3718                                                        LibFunc Func) {
3719   if (isFortifiedCallFoldable(CI, 3, 2)) {
3720     if (Func == LibFunc_strncpy_chk)
3721       return copyFlags(*CI,
3722                        emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3723                                    CI->getArgOperand(2), B, TLI));
3724     else
3725       return copyFlags(*CI,
3726                        emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3727                                    CI->getArgOperand(2), B, TLI));
3728   }
3729 
3730   return nullptr;
3731 }
3732 
3733 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3734                                                       IRBuilderBase &B) {
3735   if (isFortifiedCallFoldable(CI, 4, 3))
3736     return copyFlags(
3737         *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3738                          CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
3739 
3740   return nullptr;
3741 }
3742 
3743 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3744                                                        IRBuilderBase &B) {
3745   if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3746     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
3747     return copyFlags(*CI,
3748                      emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3749                                   CI->getArgOperand(4), VariadicArgs, B, TLI));
3750   }
3751 
3752   return nullptr;
3753 }
3754 
3755 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3756                                                       IRBuilderBase &B) {
3757   if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3758     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
3759     return copyFlags(*CI,
3760                      emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3761                                  VariadicArgs, B, TLI));
3762   }
3763 
3764   return nullptr;
3765 }
3766 
3767 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3768                                                      IRBuilderBase &B) {
3769   if (isFortifiedCallFoldable(CI, 2))
3770     return copyFlags(
3771         *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
3772 
3773   return nullptr;
3774 }
3775 
3776 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3777                                                    IRBuilderBase &B) {
3778   if (isFortifiedCallFoldable(CI, 3))
3779     return copyFlags(*CI,
3780                      emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3781                                  CI->getArgOperand(2), B, TLI));
3782 
3783   return nullptr;
3784 }
3785 
3786 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3787                                                       IRBuilderBase &B) {
3788   if (isFortifiedCallFoldable(CI, 3))
3789     return copyFlags(*CI,
3790                      emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3791                                  CI->getArgOperand(2), B, TLI));
3792 
3793   return nullptr;
3794 }
3795 
3796 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3797                                                       IRBuilderBase &B) {
3798   if (isFortifiedCallFoldable(CI, 3))
3799     return copyFlags(*CI,
3800                      emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3801                                  CI->getArgOperand(2), B, TLI));
3802 
3803   return nullptr;
3804 }
3805 
3806 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3807                                                         IRBuilderBase &B) {
3808   if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3809     return copyFlags(
3810         *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3811                            CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
3812 
3813   return nullptr;
3814 }
3815 
3816 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3817                                                        IRBuilderBase &B) {
3818   if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3819     return copyFlags(*CI,
3820                      emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3821                                   CI->getArgOperand(4), B, TLI));
3822 
3823   return nullptr;
3824 }
3825 
3826 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI,
3827                                                 IRBuilderBase &Builder) {
3828   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3829   // Some clang users checked for _chk libcall availability using:
3830   //   __has_builtin(__builtin___memcpy_chk)
3831   // When compiling with -fno-builtin, this is always true.
3832   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3833   // end up with fortified libcalls, which isn't acceptable in a freestanding
3834   // environment which only provides their non-fortified counterparts.
3835   //
3836   // Until we change clang and/or teach external users to check for availability
3837   // differently, disregard the "nobuiltin" attribute and TLI::has.
3838   //
3839   // PR23093.
3840 
3841   LibFunc Func;
3842   Function *Callee = CI->getCalledFunction();
3843   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3844 
3845   SmallVector<OperandBundleDef, 2> OpBundles;
3846   CI->getOperandBundlesAsDefs(OpBundles);
3847 
3848   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3849   Builder.setDefaultOperandBundles(OpBundles);
3850 
3851   // First, check that this is a known library functions and that the prototype
3852   // is correct.
3853   if (!TLI->getLibFunc(*Callee, Func))
3854     return nullptr;
3855 
3856   // We never change the calling convention.
3857   if (!ignoreCallingConv(Func) && !IsCallingConvC)
3858     return nullptr;
3859 
3860   switch (Func) {
3861   case LibFunc_memcpy_chk:
3862     return optimizeMemCpyChk(CI, Builder);
3863   case LibFunc_mempcpy_chk:
3864     return optimizeMemPCpyChk(CI, Builder);
3865   case LibFunc_memmove_chk:
3866     return optimizeMemMoveChk(CI, Builder);
3867   case LibFunc_memset_chk:
3868     return optimizeMemSetChk(CI, Builder);
3869   case LibFunc_stpcpy_chk:
3870   case LibFunc_strcpy_chk:
3871     return optimizeStrpCpyChk(CI, Builder, Func);
3872   case LibFunc_strlen_chk:
3873     return optimizeStrLenChk(CI, Builder);
3874   case LibFunc_stpncpy_chk:
3875   case LibFunc_strncpy_chk:
3876     return optimizeStrpNCpyChk(CI, Builder, Func);
3877   case LibFunc_memccpy_chk:
3878     return optimizeMemCCpyChk(CI, Builder);
3879   case LibFunc_snprintf_chk:
3880     return optimizeSNPrintfChk(CI, Builder);
3881   case LibFunc_sprintf_chk:
3882     return optimizeSPrintfChk(CI, Builder);
3883   case LibFunc_strcat_chk:
3884     return optimizeStrCatChk(CI, Builder);
3885   case LibFunc_strlcat_chk:
3886     return optimizeStrLCat(CI, Builder);
3887   case LibFunc_strncat_chk:
3888     return optimizeStrNCatChk(CI, Builder);
3889   case LibFunc_strlcpy_chk:
3890     return optimizeStrLCpyChk(CI, Builder);
3891   case LibFunc_vsnprintf_chk:
3892     return optimizeVSNPrintfChk(CI, Builder);
3893   case LibFunc_vsprintf_chk:
3894     return optimizeVSPrintfChk(CI, Builder);
3895   default:
3896     break;
3897   }
3898   return nullptr;
3899 }
3900 
3901 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3902     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
3903     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
3904