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