1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/DataLayout.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Function.h"
22 #include "llvm/IRBuilder.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Target/TargetLibraryInfo.h"
25 #include "llvm/Transforms/Utils/BuildLibCalls.h"
29 /// This class is the abstract base class for the set of optimizations that
30 /// corresponds to one library call.
32 class LibCallOptimization {
36 const TargetLibraryInfo *TLI;
37 const LibCallSimplifier *LCS;
40 LibCallOptimization() { }
41 virtual ~LibCallOptimization() {}
43 /// callOptimizer - This pure virtual method is implemented by base classes to
44 /// do various optimizations. If this returns null then no transformation was
45 /// performed. If it returns CI, then it transformed the call and CI is to be
46 /// deleted. If it returns something else, replace CI with the new value and
48 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
51 Value *optimizeCall(CallInst *CI, const DataLayout *TD,
52 const TargetLibraryInfo *TLI,
53 const LibCallSimplifier *LCS, IRBuilder<> &B) {
54 Caller = CI->getParent()->getParent();
58 if (CI->getCalledFunction())
59 Context = &CI->getCalledFunction()->getContext();
61 // We never change the calling convention.
62 if (CI->getCallingConv() != llvm::CallingConv::C)
65 return callOptimizer(CI->getCalledFunction(), CI, B);
69 //===----------------------------------------------------------------------===//
71 //===----------------------------------------------------------------------===//
73 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
74 /// value is equal or not-equal to zero.
75 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
76 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
78 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
80 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
83 // Unknown instruction.
89 //===----------------------------------------------------------------------===//
90 // Fortified Library Call Optimizations
91 //===----------------------------------------------------------------------===//
93 struct FortifiedLibCallOptimization : public LibCallOptimization {
95 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
96 bool isString) const = 0;
99 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
102 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
103 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
105 if (ConstantInt *SizeCI =
106 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
107 if (SizeCI->isAllOnesValue())
110 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
111 // If the length is 0 we don't know how long it is and so we can't
113 if (Len == 0) return false;
114 return SizeCI->getZExtValue() >= Len;
116 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
117 CI->getArgOperand(SizeArgOp)))
118 return SizeCI->getZExtValue() >= Arg->getZExtValue();
124 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
125 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
127 FunctionType *FT = Callee->getFunctionType();
128 LLVMContext &Context = CI->getParent()->getContext();
130 // Check if this has the right signature.
131 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
132 !FT->getParamType(0)->isPointerTy() ||
133 !FT->getParamType(1)->isPointerTy() ||
134 FT->getParamType(2) != TD->getIntPtrType(Context) ||
135 FT->getParamType(3) != TD->getIntPtrType(Context))
138 if (isFoldable(3, 2, false)) {
139 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
140 CI->getArgOperand(2), 1);
141 return CI->getArgOperand(0);
147 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
148 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
150 FunctionType *FT = Callee->getFunctionType();
151 LLVMContext &Context = CI->getParent()->getContext();
153 // Check if this has the right signature.
154 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
155 !FT->getParamType(0)->isPointerTy() ||
156 !FT->getParamType(1)->isPointerTy() ||
157 FT->getParamType(2) != TD->getIntPtrType(Context) ||
158 FT->getParamType(3) != TD->getIntPtrType(Context))
161 if (isFoldable(3, 2, false)) {
162 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
163 CI->getArgOperand(2), 1);
164 return CI->getArgOperand(0);
170 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
171 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
173 FunctionType *FT = Callee->getFunctionType();
174 LLVMContext &Context = CI->getParent()->getContext();
176 // Check if this has the right signature.
177 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
178 !FT->getParamType(0)->isPointerTy() ||
179 !FT->getParamType(1)->isIntegerTy() ||
180 FT->getParamType(2) != TD->getIntPtrType(Context) ||
181 FT->getParamType(3) != TD->getIntPtrType(Context))
184 if (isFoldable(3, 2, false)) {
185 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
187 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
188 return CI->getArgOperand(0);
194 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
195 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
197 StringRef Name = Callee->getName();
198 FunctionType *FT = Callee->getFunctionType();
199 LLVMContext &Context = CI->getParent()->getContext();
201 // Check if this has the right signature.
202 if (FT->getNumParams() != 3 ||
203 FT->getReturnType() != FT->getParamType(0) ||
204 FT->getParamType(0) != FT->getParamType(1) ||
205 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
206 FT->getParamType(2) != TD->getIntPtrType(Context))
209 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
210 if (Dst == Src) // __strcpy_chk(x,x) -> x
213 // If a) we don't have any length information, or b) we know this will
214 // fit then just lower to a plain strcpy. Otherwise we'll keep our
215 // strcpy_chk call which may fail at runtime if the size is too long.
216 // TODO: It might be nice to get a maximum length out of the possible
217 // string lengths for varying.
218 if (isFoldable(2, 1, true)) {
219 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
222 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
223 uint64_t Len = GetStringLength(Src);
224 if (Len == 0) return 0;
226 // This optimization require DataLayout.
230 EmitMemCpyChk(Dst, Src,
231 ConstantInt::get(TD->getIntPtrType(Context), Len),
232 CI->getArgOperand(2), B, TD, TLI);
239 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
240 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
242 StringRef Name = Callee->getName();
243 FunctionType *FT = Callee->getFunctionType();
244 LLVMContext &Context = CI->getParent()->getContext();
246 // Check if this has the right signature.
247 if (FT->getNumParams() != 3 ||
248 FT->getReturnType() != FT->getParamType(0) ||
249 FT->getParamType(0) != FT->getParamType(1) ||
250 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
251 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
254 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
255 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
256 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
257 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
260 // If a) we don't have any length information, or b) we know this will
261 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
262 // stpcpy_chk call which may fail at runtime if the size is too long.
263 // TODO: It might be nice to get a maximum length out of the possible
264 // string lengths for varying.
265 if (isFoldable(2, 1, true)) {
266 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
269 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
270 uint64_t Len = GetStringLength(Src);
271 if (Len == 0) return 0;
273 // This optimization require DataLayout.
276 Type *PT = FT->getParamType(0);
277 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
278 Value *DstEnd = B.CreateGEP(Dst,
279 ConstantInt::get(TD->getIntPtrType(PT),
281 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
289 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
290 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
292 StringRef Name = Callee->getName();
293 FunctionType *FT = Callee->getFunctionType();
294 LLVMContext &Context = CI->getParent()->getContext();
296 // Check if this has the right signature.
297 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
298 FT->getParamType(0) != FT->getParamType(1) ||
299 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
300 !FT->getParamType(2)->isIntegerTy() ||
301 FT->getParamType(3) != TD->getIntPtrType(Context))
304 if (isFoldable(3, 2, false)) {
305 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
306 CI->getArgOperand(2), B, TD, TLI,
314 //===----------------------------------------------------------------------===//
315 // String and Memory Library Call Optimizations
316 //===----------------------------------------------------------------------===//
318 struct StrCatOpt : public LibCallOptimization {
319 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
320 // Verify the "strcat" function prototype.
321 FunctionType *FT = Callee->getFunctionType();
322 if (FT->getNumParams() != 2 ||
323 FT->getReturnType() != B.getInt8PtrTy() ||
324 FT->getParamType(0) != FT->getReturnType() ||
325 FT->getParamType(1) != FT->getReturnType())
328 // Extract some information from the instruction
329 Value *Dst = CI->getArgOperand(0);
330 Value *Src = CI->getArgOperand(1);
332 // See if we can get the length of the input string.
333 uint64_t Len = GetStringLength(Src);
334 if (Len == 0) return 0;
335 --Len; // Unbias length.
337 // Handle the simple, do-nothing case: strcat(x, "") -> x
341 // These optimizations require DataLayout.
344 return emitStrLenMemCpy(Src, Dst, Len, B);
347 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
349 // We need to find the end of the destination string. That's where the
350 // memory is to be moved to. We just generate a call to strlen.
351 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
355 // Now that we have the destination's length, we must index into the
356 // destination's pointer to get the actual memcpy destination (end of
357 // the string .. we're concatenating).
358 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
360 // We have enough information to now generate the memcpy call to do the
361 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
362 B.CreateMemCpy(CpyDst, Src,
363 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
368 struct StrNCatOpt : public StrCatOpt {
369 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
370 // Verify the "strncat" function prototype.
371 FunctionType *FT = Callee->getFunctionType();
372 if (FT->getNumParams() != 3 ||
373 FT->getReturnType() != B.getInt8PtrTy() ||
374 FT->getParamType(0) != FT->getReturnType() ||
375 FT->getParamType(1) != FT->getReturnType() ||
376 !FT->getParamType(2)->isIntegerTy())
379 // Extract some information from the instruction
380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
384 // We don't do anything if length is not constant
385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
386 Len = LengthArg->getZExtValue();
390 // See if we can get the length of the input string.
391 uint64_t SrcLen = GetStringLength(Src);
392 if (SrcLen == 0) return 0;
393 --SrcLen; // Unbias length.
395 // Handle the simple, do-nothing cases:
396 // strncat(x, "", c) -> x
397 // strncat(x, c, 0) -> x
398 if (SrcLen == 0 || Len == 0) return Dst;
400 // These optimizations require DataLayout.
403 // We don't optimize this case
404 if (Len < SrcLen) return 0;
406 // strncat(x, s, c) -> strcat(x, s)
407 // s is constant so the strcat can be optimized further
408 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
412 struct StrChrOpt : public LibCallOptimization {
413 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
414 // Verify the "strchr" function prototype.
415 FunctionType *FT = Callee->getFunctionType();
416 if (FT->getNumParams() != 2 ||
417 FT->getReturnType() != B.getInt8PtrTy() ||
418 FT->getParamType(0) != FT->getReturnType() ||
419 !FT->getParamType(1)->isIntegerTy(32))
422 Value *SrcStr = CI->getArgOperand(0);
424 // If the second operand is non-constant, see if we can compute the length
425 // of the input string and turn this into memchr.
426 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
428 // These optimizations require DataLayout.
431 uint64_t Len = GetStringLength(SrcStr);
432 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
435 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
436 ConstantInt::get(TD->getIntPtrType(*Context), Len),
440 // Otherwise, the character is a constant, see if the first argument is
441 // a string literal. If so, we can constant fold.
443 if (!getConstantStringInfo(SrcStr, Str))
446 // Compute the offset, make sure to handle the case when we're searching for
447 // zero (a weird way to spell strlen).
448 size_t I = CharC->getSExtValue() == 0 ?
449 Str.size() : Str.find(CharC->getSExtValue());
450 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
451 return Constant::getNullValue(CI->getType());
453 // strchr(s+n,c) -> gep(s+n+i,c)
454 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
458 struct StrRChrOpt : public LibCallOptimization {
459 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
460 // Verify the "strrchr" function prototype.
461 FunctionType *FT = Callee->getFunctionType();
462 if (FT->getNumParams() != 2 ||
463 FT->getReturnType() != B.getInt8PtrTy() ||
464 FT->getParamType(0) != FT->getReturnType() ||
465 !FT->getParamType(1)->isIntegerTy(32))
468 Value *SrcStr = CI->getArgOperand(0);
469 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
471 // Cannot fold anything if we're not looking for a constant.
476 if (!getConstantStringInfo(SrcStr, Str)) {
477 // strrchr(s, 0) -> strchr(s, 0)
478 if (TD && CharC->isZero())
479 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
483 // Compute the offset.
484 size_t I = CharC->getSExtValue() == 0 ?
485 Str.size() : Str.rfind(CharC->getSExtValue());
486 if (I == StringRef::npos) // Didn't find the char. Return null.
487 return Constant::getNullValue(CI->getType());
489 // strrchr(s+n,c) -> gep(s+n+i,c)
490 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
494 struct StrCmpOpt : public LibCallOptimization {
495 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
496 // Verify the "strcmp" function prototype.
497 FunctionType *FT = Callee->getFunctionType();
498 if (FT->getNumParams() != 2 ||
499 !FT->getReturnType()->isIntegerTy(32) ||
500 FT->getParamType(0) != FT->getParamType(1) ||
501 FT->getParamType(0) != B.getInt8PtrTy())
504 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
505 if (Str1P == Str2P) // strcmp(x,x) -> 0
506 return ConstantInt::get(CI->getType(), 0);
508 StringRef Str1, Str2;
509 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
510 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
512 // strcmp(x, y) -> cnst (if both x and y are constant strings)
513 if (HasStr1 && HasStr2)
514 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
516 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
517 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
520 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
521 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
523 // strcmp(P, "x") -> memcmp(P, "x", 2)
524 uint64_t Len1 = GetStringLength(Str1P);
525 uint64_t Len2 = GetStringLength(Str2P);
527 // These optimizations require DataLayout.
530 return EmitMemCmp(Str1P, Str2P,
531 ConstantInt::get(TD->getIntPtrType(*Context),
532 std::min(Len1, Len2)), B, TD, TLI);
539 struct StrNCmpOpt : public LibCallOptimization {
540 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
541 // Verify the "strncmp" function prototype.
542 FunctionType *FT = Callee->getFunctionType();
543 if (FT->getNumParams() != 3 ||
544 !FT->getReturnType()->isIntegerTy(32) ||
545 FT->getParamType(0) != FT->getParamType(1) ||
546 FT->getParamType(0) != B.getInt8PtrTy() ||
547 !FT->getParamType(2)->isIntegerTy())
550 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
551 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
552 return ConstantInt::get(CI->getType(), 0);
554 // Get the length argument if it is constant.
556 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
557 Length = LengthArg->getZExtValue();
561 if (Length == 0) // strncmp(x,y,0) -> 0
562 return ConstantInt::get(CI->getType(), 0);
564 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
565 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
567 StringRef Str1, Str2;
568 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
569 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
571 // strncmp(x, y) -> cnst (if both x and y are constant strings)
572 if (HasStr1 && HasStr2) {
573 StringRef SubStr1 = Str1.substr(0, Length);
574 StringRef SubStr2 = Str2.substr(0, Length);
575 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
578 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
579 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
582 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
583 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
589 struct StrCpyOpt : public LibCallOptimization {
590 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
591 // Verify the "strcpy" function prototype.
592 FunctionType *FT = Callee->getFunctionType();
593 if (FT->getNumParams() != 2 ||
594 FT->getReturnType() != FT->getParamType(0) ||
595 FT->getParamType(0) != FT->getParamType(1) ||
596 FT->getParamType(0) != B.getInt8PtrTy())
599 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
600 if (Dst == Src) // strcpy(x,x) -> x
603 // These optimizations require DataLayout.
606 // See if we can get the length of the input string.
607 uint64_t Len = GetStringLength(Src);
608 if (Len == 0) return 0;
610 // We have enough information to now generate the memcpy call to do the
611 // copy for us. Make a memcpy to copy the nul byte with align = 1.
612 B.CreateMemCpy(Dst, Src,
613 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
618 struct StpCpyOpt: public LibCallOptimization {
619 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
620 // Verify the "stpcpy" function prototype.
621 FunctionType *FT = Callee->getFunctionType();
622 if (FT->getNumParams() != 2 ||
623 FT->getReturnType() != FT->getParamType(0) ||
624 FT->getParamType(0) != FT->getParamType(1) ||
625 FT->getParamType(0) != B.getInt8PtrTy())
628 // These optimizations require DataLayout.
631 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
632 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
633 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
634 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
637 // See if we can get the length of the input string.
638 uint64_t Len = GetStringLength(Src);
639 if (Len == 0) return 0;
641 Type *PT = FT->getParamType(0);
642 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
643 Value *DstEnd = B.CreateGEP(Dst,
644 ConstantInt::get(TD->getIntPtrType(PT),
647 // We have enough information to now generate the memcpy call to do the
648 // copy for us. Make a memcpy to copy the nul byte with align = 1.
649 B.CreateMemCpy(Dst, Src, LenV, 1);
654 struct StrNCpyOpt : public LibCallOptimization {
655 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
656 FunctionType *FT = Callee->getFunctionType();
657 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
658 FT->getParamType(0) != FT->getParamType(1) ||
659 FT->getParamType(0) != B.getInt8PtrTy() ||
660 !FT->getParamType(2)->isIntegerTy())
663 Value *Dst = CI->getArgOperand(0);
664 Value *Src = CI->getArgOperand(1);
665 Value *LenOp = CI->getArgOperand(2);
667 // See if we can get the length of the input string.
668 uint64_t SrcLen = GetStringLength(Src);
669 if (SrcLen == 0) return 0;
673 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
674 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
679 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
680 Len = LengthArg->getZExtValue();
684 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
686 // These optimizations require DataLayout.
689 // Let strncpy handle the zero padding
690 if (Len > SrcLen+1) return 0;
692 Type *PT = FT->getParamType(0);
693 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
694 B.CreateMemCpy(Dst, Src,
695 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
701 struct StrLenOpt : public LibCallOptimization {
702 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
703 FunctionType *FT = Callee->getFunctionType();
704 if (FT->getNumParams() != 1 ||
705 FT->getParamType(0) != B.getInt8PtrTy() ||
706 !FT->getReturnType()->isIntegerTy())
709 Value *Src = CI->getArgOperand(0);
711 // Constant folding: strlen("xyz") -> 3
712 if (uint64_t Len = GetStringLength(Src))
713 return ConstantInt::get(CI->getType(), Len-1);
715 // strlen(x) != 0 --> *x != 0
716 // strlen(x) == 0 --> *x == 0
717 if (isOnlyUsedInZeroEqualityComparison(CI))
718 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
723 struct StrPBrkOpt : public LibCallOptimization {
724 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
725 FunctionType *FT = Callee->getFunctionType();
726 if (FT->getNumParams() != 2 ||
727 FT->getParamType(0) != B.getInt8PtrTy() ||
728 FT->getParamType(1) != FT->getParamType(0) ||
729 FT->getReturnType() != FT->getParamType(0))
733 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
734 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
736 // strpbrk(s, "") -> NULL
737 // strpbrk("", s) -> NULL
738 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
739 return Constant::getNullValue(CI->getType());
742 if (HasS1 && HasS2) {
743 size_t I = S1.find_first_of(S2);
744 if (I == std::string::npos) // No match.
745 return Constant::getNullValue(CI->getType());
747 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
750 // strpbrk(s, "a") -> strchr(s, 'a')
751 if (TD && HasS2 && S2.size() == 1)
752 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
758 struct StrToOpt : public LibCallOptimization {
759 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
760 FunctionType *FT = Callee->getFunctionType();
761 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
762 !FT->getParamType(0)->isPointerTy() ||
763 !FT->getParamType(1)->isPointerTy())
766 Value *EndPtr = CI->getArgOperand(1);
767 if (isa<ConstantPointerNull>(EndPtr)) {
768 // With a null EndPtr, this function won't capture the main argument.
769 // It would be readonly too, except that it still may write to errno.
770 CI->addAttribute(1, Attributes::get(Callee->getContext(),
771 Attributes::NoCapture));
778 struct StrSpnOpt : public LibCallOptimization {
779 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
780 FunctionType *FT = Callee->getFunctionType();
781 if (FT->getNumParams() != 2 ||
782 FT->getParamType(0) != B.getInt8PtrTy() ||
783 FT->getParamType(1) != FT->getParamType(0) ||
784 !FT->getReturnType()->isIntegerTy())
788 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
789 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
791 // strspn(s, "") -> 0
792 // strspn("", s) -> 0
793 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
794 return Constant::getNullValue(CI->getType());
797 if (HasS1 && HasS2) {
798 size_t Pos = S1.find_first_not_of(S2);
799 if (Pos == StringRef::npos) Pos = S1.size();
800 return ConstantInt::get(CI->getType(), Pos);
807 struct StrCSpnOpt : public LibCallOptimization {
808 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
809 FunctionType *FT = Callee->getFunctionType();
810 if (FT->getNumParams() != 2 ||
811 FT->getParamType(0) != B.getInt8PtrTy() ||
812 FT->getParamType(1) != FT->getParamType(0) ||
813 !FT->getReturnType()->isIntegerTy())
817 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
818 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
820 // strcspn("", s) -> 0
821 if (HasS1 && S1.empty())
822 return Constant::getNullValue(CI->getType());
825 if (HasS1 && HasS2) {
826 size_t Pos = S1.find_first_of(S2);
827 if (Pos == StringRef::npos) Pos = S1.size();
828 return ConstantInt::get(CI->getType(), Pos);
831 // strcspn(s, "") -> strlen(s)
832 if (TD && HasS2 && S2.empty())
833 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
839 } // End anonymous namespace.
843 class LibCallSimplifierImpl {
844 const DataLayout *TD;
845 const TargetLibraryInfo *TLI;
846 const LibCallSimplifier *LCS;
847 StringMap<LibCallOptimization*> Optimizations;
849 // Fortified library call optimizations.
850 MemCpyChkOpt MemCpyChk;
851 MemMoveChkOpt MemMoveChk;
852 MemSetChkOpt MemSetChk;
853 StrCpyChkOpt StrCpyChk;
854 StpCpyChkOpt StpCpyChk;
855 StrNCpyChkOpt StrNCpyChk;
857 // String and memory library call optimizations.
873 void initOptimizations();
874 void addOpt(LibFunc::Func F, LibCallOptimization* Opt);
876 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
877 const LibCallSimplifier *LCS) {
883 Value *optimizeCall(CallInst *CI);
886 void LibCallSimplifierImpl::initOptimizations() {
887 // Fortified library call optimizations.
888 Optimizations["__memcpy_chk"] = &MemCpyChk;
889 Optimizations["__memmove_chk"] = &MemMoveChk;
890 Optimizations["__memset_chk"] = &MemSetChk;
891 Optimizations["__strcpy_chk"] = &StrCpyChk;
892 Optimizations["__stpcpy_chk"] = &StpCpyChk;
893 Optimizations["__strncpy_chk"] = &StrNCpyChk;
894 Optimizations["__stpncpy_chk"] = &StrNCpyChk;
896 // String and memory library call optimizations.
897 addOpt(LibFunc::strcat, &StrCat);
898 addOpt(LibFunc::strncat, &StrNCat);
899 addOpt(LibFunc::strchr, &StrChr);
900 addOpt(LibFunc::strrchr, &StrRChr);
901 addOpt(LibFunc::strcmp, &StrCmp);
902 addOpt(LibFunc::strncmp, &StrNCmp);
903 addOpt(LibFunc::strcpy, &StrCpy);
904 addOpt(LibFunc::stpcpy, &StpCpy);
905 addOpt(LibFunc::strncpy, &StrNCpy);
906 addOpt(LibFunc::strlen, &StrLen);
907 addOpt(LibFunc::strpbrk, &StrPBrk);
908 addOpt(LibFunc::strtol, &StrTo);
909 addOpt(LibFunc::strtod, &StrTo);
910 addOpt(LibFunc::strtof, &StrTo);
911 addOpt(LibFunc::strtoul, &StrTo);
912 addOpt(LibFunc::strtoll, &StrTo);
913 addOpt(LibFunc::strtold, &StrTo);
914 addOpt(LibFunc::strtoull, &StrTo);
915 addOpt(LibFunc::strspn, &StrSpn);
916 addOpt(LibFunc::strcspn, &StrCSpn);
919 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
920 if (Optimizations.empty())
923 Function *Callee = CI->getCalledFunction();
924 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
926 IRBuilder<> Builder(CI);
927 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
932 void LibCallSimplifierImpl::addOpt(LibFunc::Func F, LibCallOptimization* Opt) {
934 Optimizations[TLI->getName(F)] = Opt;
937 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
938 const TargetLibraryInfo *TLI) {
939 Impl = new LibCallSimplifierImpl(TD, TLI, this);
942 LibCallSimplifier::~LibCallSimplifier() {
946 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
947 return Impl->optimizeCall(CI);
950 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
951 I->replaceAllUsesWith(With);
952 I->eraseFromParent();