SemaChecking.cpp revision 728a1fb4fd6c1bcb200b5eed398e982fe1856ee1
18b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 28b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// 38b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// The LLVM Compiler Infrastructure 48b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// 58b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// This file is distributed under the University of Illinois Open Source 68b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// License. See LICENSE.TXT for details. 78b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// 88b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project//===----------------------------------------------------------------------===// 98b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// 108b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// This file implements extra semantic analysis beyond what is enforced 118b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// by the C type system. 128b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project// 138b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project//===----------------------------------------------------------------------===// 148b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 158b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Sema/SemaInternal.h" 168b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/ASTContext.h" 178b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/CharUnits.h" 188b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/DeclCXX.h" 198b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/DeclObjC.h" 208b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/EvaluatedExprVisitor.h" 218b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/Expr.h" 228b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/ExprCXX.h" 238b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/ExprObjC.h" 248b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/StmtCXX.h" 258b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/AST/StmtObjC.h" 268b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Analysis/Analyses/FormatString.h" 278b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Basic/CharInfo.h" 288b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Basic/TargetBuiltins.h" 298b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Basic/TargetInfo.h" 308b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Lex/Preprocessor.h" 318b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Sema/Initialization.h" 328b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Sema/Lookup.h" 338b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Sema/ScopeInfo.h" 348b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "clang/Sema/Sema.h" 358b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "llvm/ADT/SmallBitVector.h" 368b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "llvm/ADT/SmallString.h" 378b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "llvm/ADT/STLExtras.h" 388b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "llvm/Support/ConvertUTF.h" 398b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include "llvm/Support/raw_ostream.h" 408b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project#include <limits> 418b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Projectusing namespace clang; 428b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Projectusing namespace sema; 438b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 448b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source ProjectSourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 458b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project unsigned ByteNo) const { 468b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 478b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project PP.getLangOpts(), PP.getTargetInfo()); 488b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project} 498b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 508b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project/// Checks that a call expression's argument count is the desired number. 518b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project/// This is useful when doing custom type-checking. Returns true on error. 528b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Projectstatic bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 538b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project unsigned argCount = call->getNumArgs(); 548b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (argCount == desiredArgCount) return false; 558b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 568b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (argCount < desiredArgCount) 578b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 588b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project << 0 /*function call*/ << desiredArgCount << argCount 598b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project << call->getSourceRange(); 608b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 618b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project // Highlight all the excess arguments. 628b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 635d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner call->getArg(argCount - 1)->getLocEnd()); 645d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 655d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 665d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner << 0 /*function call*/ << desiredArgCount << argCount 675d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner << call->getArg(1)->getSourceRange(); 685d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner} 695d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 705d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner/// Check that the first argument to __builtin_annotation is an integer 715d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner/// and the second argument is a non-wide string literal. 725d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turnerstatic bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 735d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (checkArgCount(S, TheCall, 2)) 745d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return true; 755d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 768b8768b9e2f1f0c77a315c04995a35fcb9861b72David 'Digit' Turner // First argument should be an integer. 775d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner Expr *ValArg = TheCall->getArg(0); 785d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner QualType Ty = ValArg->getType(); 795d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (!Ty->isIntegerType()) { 805d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 815d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner << ValArg->getSourceRange(); 825d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return true; 835d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner } 845d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 855d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner // Second argument should be a constant string. 865d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 875d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 885d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (!Literal || !Literal->isAscii()) { 895d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 905d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner << StrArg->getSourceRange(); 915d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return true; 925d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner } 935d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 945d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner TheCall->setType(Ty); 955d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return false; 965d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner} 975d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 985d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner/// Check that the argument to __builtin_addressof is a glvalue, and set the 995d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner/// result type to the corresponding pointer type. 1005d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turnerstatic bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 1018b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (checkArgCount(S, TheCall, 1)) 1028b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return true; 1038b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1048b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project ExprResult Arg(S.Owned(TheCall->getArg(0))); 1058b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 1068b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (ResultType.isNull()) 1078b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return true; 1088b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1098b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project TheCall->setArg(0, Arg.take()); 1108b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project TheCall->setType(ResultType); 1118b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return false; 1128b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project} 1138b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1148b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source ProjectExprResult 1158b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source ProjectSema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1168b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project ExprResult TheCallResult(Owned(TheCall)); 1178b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1188b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project // Find out if any arguments are required to be integer constant expressions. 1198b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project unsigned ICEArguments = 0; 1208b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project ASTContext::GetBuiltinTypeError Error; 1218b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1228b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (Error != ASTContext::GE_None) 1238b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1248b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1258b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project // If any arguments are required to be ICE's, check and diagnose. 1268b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1278b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project // Skip arguments not required to be ICE's. 1285d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1295d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 1305d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner llvm::APSInt Result; 1318b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1328b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return true; 1335d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner ICEArguments &= ~(1 << ArgNo); 1345d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner } 1355d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner 1365d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner switch (BuiltinID) { 1375d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin___CFStringMakeConstantString: 1385d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner assert(TheCall->getNumArgs() == 1 && 1395d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner "Wrong # arguments to builtin CFStringMakeConstantString"); 1405d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (CheckObjCString(TheCall->getArg(0))) 1415d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner return ExprError(); 1425d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner break; 1435d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_stdarg_start: 1445d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_va_start: 1455d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (SemaBuiltinVAStart(TheCall)) 1468b8768b9e2f1f0c77a315c04995a35fcb9861b72David 'Digit' Turner return ExprError(); 1478b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1485d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_isgreater: 1498b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_isgreaterequal: 150aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__builtin_isless: 1515d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_islessequal: 1525d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_islessgreater: 1535d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_isunordered: 1548b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (SemaBuiltinUnorderedCompare(TheCall)) 1558b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return ExprError(); 1568b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1578b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_fpclassify: 1588b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (SemaBuiltinFPClassification(TheCall, 6)) 1598b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return ExprError(); 1608b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1615d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_isfinite: 1628b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_isinf: 1638b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_isinf_sign: 164aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__builtin_isnan: 1655d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__builtin_isnormal: 1665d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner if (SemaBuiltinFPClassification(TheCall, 1)) 1678b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return ExprError(); 1688b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1698b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_shufflevector: 1708b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return SemaBuiltinShuffleVector(TheCall); 171aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner // TheCall will be freed by the smart pointer here, but that's fine, since 1728b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1738b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_prefetch: 174aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner if (SemaBuiltinPrefetch(TheCall)) 175aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner return ExprError(); 176aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner break; 1778b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_object_size: 1788b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (SemaBuiltinObjectSize(TheCall)) 1798b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return ExprError(); 1805d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner break; 1818b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_longjmp: 1828b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (SemaBuiltinLongjmp(TheCall)) 1838b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project return ExprError(); 1848b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1858b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project 1868b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_classify_type: 1878b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (checkArgCount(*this, TheCall, 1)) return true; 1885d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner TheCall->setType(Context.IntTy); 1898b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1908b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__builtin_constant_p: 1918b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project if (checkArgCount(*this, TheCall, 1)) return true; 1928b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project TheCall->setType(Context.IntTy); 1938b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project break; 1948b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_add: 1958b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_add_1: 1968b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_add_2: 1975d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_add_4: 1985d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_add_8: 1995d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_add_16: 2005d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub: 2015d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub_1: 2025d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub_2: 2035d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub_4: 2045d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub_8: 2055d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_sub_16: 2065d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or: 2075d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or_1: 2085d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or_2: 2095d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or_4: 2105d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or_8: 2115d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_fetch_and_or_16: 2128b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and: 2138b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and_1: 2148b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and_2: 2158b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and_4: 2168b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and_8: 2178b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_and_16: 2188b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_xor: 2198b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_xor_1: 220aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_fetch_and_xor_2: 2218b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_xor_4: 2228b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_xor_8: 2238b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_fetch_and_xor_16: 2248b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch: 2258b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch_1: 2268b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch_2: 2278b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch_4: 2288b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch_8: 2298b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_add_and_fetch_16: 2308b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch: 2318b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch_1: 2328b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch_2: 2338b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch_4: 2348b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch_8: 2358b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_sub_and_fetch_16: 2368b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_and_and_fetch: 2378b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_and_and_fetch_1: 238aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_and_and_fetch_2: 2398b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_and_and_fetch_4: 2408b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_and_and_fetch_8: 2418b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_and_and_fetch_16: 2428b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_or_and_fetch: 2438b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_or_and_fetch_1: 2448b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_or_and_fetch_2: 2455d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_or_and_fetch_4: 2465d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_or_and_fetch_8: 2475d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_or_and_fetch_16: 2488b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_xor_and_fetch: 2498b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_xor_and_fetch_1: 2508b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_xor_and_fetch_2: 2518b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_xor_and_fetch_4: 2525d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_xor_and_fetch_8: 2538b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_xor_and_fetch_16: 2545d8f37ad78fc66901af50c762029a501561f3b23David 'Digit' Turner case Builtin::BI__sync_val_compare_and_swap: 2558b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_val_compare_and_swap_1: 2568b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_val_compare_and_swap_2: 257aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_val_compare_and_swap_4: 2588b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_val_compare_and_swap_8: 2598b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_val_compare_and_swap_16: 2608b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_bool_compare_and_swap: 261aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_bool_compare_and_swap_1: 2628b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_bool_compare_and_swap_2: 2638b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_bool_compare_and_swap_4: 2648b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_bool_compare_and_swap_8: 2658b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_bool_compare_and_swap_16: 2668b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_lock_test_and_set: 2678b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_lock_test_and_set_1: 268aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_lock_test_and_set_2: 269aa8236dc1b1ea300ab18716db5b8fab42aca3ca7David 'Digit' Turner case Builtin::BI__sync_lock_test_and_set_4: 2708b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_lock_test_and_set_8: 2718b23a6c7e1aee255004dd19098d4c2462b61b849The Android Open Source Project case Builtin::BI__sync_lock_test_and_set_16: 272 case Builtin::BI__sync_lock_release: 273 case Builtin::BI__sync_lock_release_1: 274 case Builtin::BI__sync_lock_release_2: 275 case Builtin::BI__sync_lock_release_4: 276 case Builtin::BI__sync_lock_release_8: 277 case Builtin::BI__sync_lock_release_16: 278 case Builtin::BI__sync_swap: 279 case Builtin::BI__sync_swap_1: 280 case Builtin::BI__sync_swap_2: 281 case Builtin::BI__sync_swap_4: 282 case Builtin::BI__sync_swap_8: 283 case Builtin::BI__sync_swap_16: 284 return SemaBuiltinAtomicOverloaded(TheCallResult); 285#define BUILTIN(ID, TYPE, ATTRS) 286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 287 case Builtin::BI##ID: \ 288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 289#include "clang/Basic/Builtins.def" 290 case Builtin::BI__builtin_annotation: 291 if (SemaBuiltinAnnotation(*this, TheCall)) 292 return ExprError(); 293 break; 294 case Builtin::BI__builtin_addressof: 295 if (SemaBuiltinAddressof(*this, TheCall)) 296 return ExprError(); 297 break; 298 } 299 300 // Since the target specific builtins for each arch overlap, only check those 301 // of the arch we are compiling for. 302 if (BuiltinID >= Builtin::FirstTSBuiltin) { 303 switch (Context.getTargetInfo().getTriple().getArch()) { 304 case llvm::Triple::arm: 305 case llvm::Triple::thumb: 306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 307 return ExprError(); 308 break; 309 case llvm::Triple::aarch64: 310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 311 return ExprError(); 312 break; 313 case llvm::Triple::mips: 314 case llvm::Triple::mipsel: 315 case llvm::Triple::mips64: 316 case llvm::Triple::mips64el: 317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 318 return ExprError(); 319 break; 320 default: 321 break; 322 } 323 } 324 325 return TheCallResult; 326} 327 328// Get the valid immediate range for the specified NEON type code. 329static unsigned RFT(unsigned t, bool shift = false) { 330 NeonTypeFlags Type(t); 331 int IsQuad = Type.isQuad(); 332 switch (Type.getEltType()) { 333 case NeonTypeFlags::Int8: 334 case NeonTypeFlags::Poly8: 335 return shift ? 7 : (8 << IsQuad) - 1; 336 case NeonTypeFlags::Int16: 337 case NeonTypeFlags::Poly16: 338 return shift ? 15 : (4 << IsQuad) - 1; 339 case NeonTypeFlags::Int32: 340 return shift ? 31 : (2 << IsQuad) - 1; 341 case NeonTypeFlags::Int64: 342 return shift ? 63 : (1 << IsQuad) - 1; 343 case NeonTypeFlags::Float16: 344 assert(!shift && "cannot shift float types!"); 345 return (4 << IsQuad) - 1; 346 case NeonTypeFlags::Float32: 347 assert(!shift && "cannot shift float types!"); 348 return (2 << IsQuad) - 1; 349 case NeonTypeFlags::Float64: 350 assert(!shift && "cannot shift float types!"); 351 return (1 << IsQuad) - 1; 352 } 353 llvm_unreachable("Invalid NeonTypeFlag!"); 354} 355 356/// getNeonEltType - Return the QualType corresponding to the elements of 357/// the vector type specified by the NeonTypeFlags. This is used to check 358/// the pointer arguments for Neon load/store intrinsics. 359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 360 switch (Flags.getEltType()) { 361 case NeonTypeFlags::Int8: 362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 363 case NeonTypeFlags::Int16: 364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 365 case NeonTypeFlags::Int32: 366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 367 case NeonTypeFlags::Int64: 368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 369 case NeonTypeFlags::Poly8: 370 return Context.SignedCharTy; 371 case NeonTypeFlags::Poly16: 372 return Context.ShortTy; 373 case NeonTypeFlags::Float16: 374 return Context.UnsignedShortTy; 375 case NeonTypeFlags::Float32: 376 return Context.FloatTy; 377 case NeonTypeFlags::Float64: 378 return Context.DoubleTy; 379 } 380 llvm_unreachable("Invalid NeonTypeFlag!"); 381} 382 383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 384 CallExpr *TheCall) { 385 386 llvm::APSInt Result; 387 388 uint64_t mask = 0; 389 unsigned TV = 0; 390 int PtrArgNum = -1; 391 bool HasConstPtr = false; 392 switch (BuiltinID) { 393#define GET_NEON_AARCH64_OVERLOAD_CHECK 394#include "clang/Basic/arm_neon.inc" 395#undef GET_NEON_AARCH64_OVERLOAD_CHECK 396 } 397 398 // For NEON intrinsics which are overloaded on vector element type, validate 399 // the immediate which specifies which variant to emit. 400 unsigned ImmArg = TheCall->getNumArgs() - 1; 401 if (mask) { 402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 403 return true; 404 405 TV = Result.getLimitedValue(64); 406 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 408 << TheCall->getArg(ImmArg)->getSourceRange(); 409 } 410 411 if (PtrArgNum >= 0) { 412 // Check that pointer arguments have the specified type. 413 Expr *Arg = TheCall->getArg(PtrArgNum); 414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 415 Arg = ICE->getSubExpr(); 416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 417 QualType RHSTy = RHS.get()->getType(); 418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 419 if (HasConstPtr) 420 EltTy = EltTy.withConst(); 421 QualType LHSTy = Context.getPointerType(EltTy); 422 AssignConvertType ConvTy; 423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 424 if (RHS.isInvalid()) 425 return true; 426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 427 RHS.get(), AA_Assigning)) 428 return true; 429 } 430 431 // For NEON intrinsics which take an immediate value as part of the 432 // instruction, range check them here. 433 unsigned i = 0, l = 0, u = 0; 434 switch (BuiltinID) { 435 default: 436 return false; 437#define GET_NEON_AARCH64_IMMEDIATE_CHECK 438#include "clang/Basic/arm_neon.inc" 439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK 440 } 441 ; 442 443 // We can't check the value of a dependent argument. 444 if (TheCall->getArg(i)->isTypeDependent() || 445 TheCall->getArg(i)->isValueDependent()) 446 return false; 447 448 // Check that the immediate argument is actually a constant. 449 if (SemaBuiltinConstantArg(TheCall, i, Result)) 450 return true; 451 452 // Range check against the upper/lower values for this isntruction. 453 unsigned Val = Result.getZExtValue(); 454 if (Val < l || Val > (u + l)) 455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 456 << l << u + l << TheCall->getArg(i)->getSourceRange(); 457 458 return false; 459} 460 461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) { 462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 463 BuiltinID == ARM::BI__builtin_arm_strex) && 464 "unexpected ARM builtin"); 465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex; 466 467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 468 469 // Ensure that we have the proper number of arguments. 470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 471 return true; 472 473 // Inspect the pointer argument of the atomic builtin. This should always be 474 // a pointer type, whose element is an integral scalar or pointer type. 475 // Because it is a pointer type, we don't have to worry about any implicit 476 // casts here. 477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 479 if (PointerArgRes.isInvalid()) 480 return true; 481 PointerArg = PointerArgRes.take(); 482 483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 484 if (!pointerType) { 485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 486 << PointerArg->getType() << PointerArg->getSourceRange(); 487 return true; 488 } 489 490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 491 // task is to insert the appropriate casts into the AST. First work out just 492 // what the appropriate type is. 493 QualType ValType = pointerType->getPointeeType(); 494 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 495 if (IsLdrex) 496 AddrType.addConst(); 497 498 // Issue a warning if the cast is dodgy. 499 CastKind CastNeeded = CK_NoOp; 500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 501 CastNeeded = CK_BitCast; 502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 503 << PointerArg->getType() 504 << Context.getPointerType(AddrType) 505 << AA_Passing << PointerArg->getSourceRange(); 506 } 507 508 // Finally, do the cast and replace the argument with the corrected version. 509 AddrType = Context.getPointerType(AddrType); 510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 511 if (PointerArgRes.isInvalid()) 512 return true; 513 PointerArg = PointerArgRes.take(); 514 515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 516 517 // In general, we allow ints, floats and pointers to be loaded and stored. 518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 521 << PointerArg->getType() << PointerArg->getSourceRange(); 522 return true; 523 } 524 525 // But ARM doesn't have instructions to deal with 128-bit versions. 526 if (Context.getTypeSize(ValType) > 64) { 527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 528 << PointerArg->getType() << PointerArg->getSourceRange(); 529 return true; 530 } 531 532 switch (ValType.getObjCLifetime()) { 533 case Qualifiers::OCL_None: 534 case Qualifiers::OCL_ExplicitNone: 535 // okay 536 break; 537 538 case Qualifiers::OCL_Weak: 539 case Qualifiers::OCL_Strong: 540 case Qualifiers::OCL_Autoreleasing: 541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 542 << ValType << PointerArg->getSourceRange(); 543 return true; 544 } 545 546 547 if (IsLdrex) { 548 TheCall->setType(ValType); 549 return false; 550 } 551 552 // Initialize the argument to be stored. 553 ExprResult ValArg = TheCall->getArg(0); 554 InitializedEntity Entity = InitializedEntity::InitializeParameter( 555 Context, ValType, /*consume*/ false); 556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 557 if (ValArg.isInvalid()) 558 return true; 559 560 TheCall->setArg(0, ValArg.get()); 561 return false; 562} 563 564bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 565 llvm::APSInt Result; 566 567 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 568 BuiltinID == ARM::BI__builtin_arm_strex) { 569 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall); 570 } 571 572 uint64_t mask = 0; 573 unsigned TV = 0; 574 int PtrArgNum = -1; 575 bool HasConstPtr = false; 576 switch (BuiltinID) { 577#define GET_NEON_OVERLOAD_CHECK 578#include "clang/Basic/arm_neon.inc" 579#undef GET_NEON_OVERLOAD_CHECK 580 } 581 582 // For NEON intrinsics which are overloaded on vector element type, validate 583 // the immediate which specifies which variant to emit. 584 unsigned ImmArg = TheCall->getNumArgs()-1; 585 if (mask) { 586 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 587 return true; 588 589 TV = Result.getLimitedValue(64); 590 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 591 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 592 << TheCall->getArg(ImmArg)->getSourceRange(); 593 } 594 595 if (PtrArgNum >= 0) { 596 // Check that pointer arguments have the specified type. 597 Expr *Arg = TheCall->getArg(PtrArgNum); 598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 599 Arg = ICE->getSubExpr(); 600 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 601 QualType RHSTy = RHS.get()->getType(); 602 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 603 if (HasConstPtr) 604 EltTy = EltTy.withConst(); 605 QualType LHSTy = Context.getPointerType(EltTy); 606 AssignConvertType ConvTy; 607 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 608 if (RHS.isInvalid()) 609 return true; 610 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 611 RHS.get(), AA_Assigning)) 612 return true; 613 } 614 615 // For NEON intrinsics which take an immediate value as part of the 616 // instruction, range check them here. 617 unsigned i = 0, l = 0, u = 0; 618 switch (BuiltinID) { 619 default: return false; 620 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 621 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 622 case ARM::BI__builtin_arm_vcvtr_f: 623 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 624#define GET_NEON_IMMEDIATE_CHECK 625#include "clang/Basic/arm_neon.inc" 626#undef GET_NEON_IMMEDIATE_CHECK 627 }; 628 629 // We can't check the value of a dependent argument. 630 if (TheCall->getArg(i)->isTypeDependent() || 631 TheCall->getArg(i)->isValueDependent()) 632 return false; 633 634 // Check that the immediate argument is actually a constant. 635 if (SemaBuiltinConstantArg(TheCall, i, Result)) 636 return true; 637 638 // Range check against the upper/lower values for this isntruction. 639 unsigned Val = Result.getZExtValue(); 640 if (Val < l || Val > (u + l)) 641 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 642 << l << u+l << TheCall->getArg(i)->getSourceRange(); 643 644 // FIXME: VFP Intrinsics should error if VFP not present. 645 return false; 646} 647 648bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 649 unsigned i = 0, l = 0, u = 0; 650 switch (BuiltinID) { 651 default: return false; 652 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 653 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 654 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 655 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 656 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 657 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 658 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 659 }; 660 661 // We can't check the value of a dependent argument. 662 if (TheCall->getArg(i)->isTypeDependent() || 663 TheCall->getArg(i)->isValueDependent()) 664 return false; 665 666 // Check that the immediate argument is actually a constant. 667 llvm::APSInt Result; 668 if (SemaBuiltinConstantArg(TheCall, i, Result)) 669 return true; 670 671 // Range check against the upper/lower values for this instruction. 672 unsigned Val = Result.getZExtValue(); 673 if (Val < l || Val > u) 674 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 675 << l << u << TheCall->getArg(i)->getSourceRange(); 676 677 return false; 678} 679 680/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 681/// parameter with the FormatAttr's correct format_idx and firstDataArg. 682/// Returns true when the format fits the function and the FormatStringInfo has 683/// been populated. 684bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 685 FormatStringInfo *FSI) { 686 FSI->HasVAListArg = Format->getFirstArg() == 0; 687 FSI->FormatIdx = Format->getFormatIdx() - 1; 688 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 689 690 // The way the format attribute works in GCC, the implicit this argument 691 // of member functions is counted. However, it doesn't appear in our own 692 // lists, so decrement format_idx in that case. 693 if (IsCXXMember) { 694 if(FSI->FormatIdx == 0) 695 return false; 696 --FSI->FormatIdx; 697 if (FSI->FirstDataArg != 0) 698 --FSI->FirstDataArg; 699 } 700 return true; 701} 702 703/// Handles the checks for format strings, non-POD arguments to vararg 704/// functions, and NULL arguments passed to non-NULL parameters. 705void Sema::checkCall(NamedDecl *FDecl, 706 ArrayRef<const Expr *> Args, 707 unsigned NumProtoArgs, 708 bool IsMemberFunction, 709 SourceLocation Loc, 710 SourceRange Range, 711 VariadicCallType CallType) { 712 // FIXME: We should check as much as we can in the template definition. 713 if (CurContext->isDependentContext()) 714 return; 715 716 // Printf and scanf checking. 717 llvm::SmallBitVector CheckedVarArgs; 718 if (FDecl) { 719 for (specific_attr_iterator<FormatAttr> 720 I = FDecl->specific_attr_begin<FormatAttr>(), 721 E = FDecl->specific_attr_end<FormatAttr>(); 722 I != E; ++I) { 723 // Only create vector if there are format attributes. 724 CheckedVarArgs.resize(Args.size()); 725 726 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range, 727 CheckedVarArgs); 728 } 729 } 730 731 // Refuse POD arguments that weren't caught by the format string 732 // checks above. 733 if (CallType != VariadicDoesNotApply) { 734 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) { 735 // Args[ArgIdx] can be null in malformed code. 736 if (const Expr *Arg = Args[ArgIdx]) { 737 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 738 checkVariadicArgument(Arg, CallType); 739 } 740 } 741 } 742 743 if (FDecl) { 744 for (specific_attr_iterator<NonNullAttr> 745 I = FDecl->specific_attr_begin<NonNullAttr>(), 746 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) 747 CheckNonNullArguments(*I, Args.data(), Loc); 748 749 // Type safety checking. 750 for (specific_attr_iterator<ArgumentWithTypeTagAttr> 751 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(), 752 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); 753 i != e; ++i) { 754 CheckArgumentWithTypeTag(*i, Args.data()); 755 } 756 } 757} 758 759/// CheckConstructorCall - Check a constructor call for correctness and safety 760/// properties not enforced by the C type system. 761void Sema::CheckConstructorCall(FunctionDecl *FDecl, 762 ArrayRef<const Expr *> Args, 763 const FunctionProtoType *Proto, 764 SourceLocation Loc) { 765 VariadicCallType CallType = 766 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 767 checkCall(FDecl, Args, Proto->getNumArgs(), 768 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 769} 770 771/// CheckFunctionCall - Check a direct function call for various correctness 772/// and safety properties not strictly enforced by the C type system. 773bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 774 const FunctionProtoType *Proto) { 775 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 776 isa<CXXMethodDecl>(FDecl); 777 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 778 IsMemberOperatorCall; 779 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 780 TheCall->getCallee()); 781 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 782 Expr** Args = TheCall->getArgs(); 783 unsigned NumArgs = TheCall->getNumArgs(); 784 if (IsMemberOperatorCall) { 785 // If this is a call to a member operator, hide the first argument 786 // from checkCall. 787 // FIXME: Our choice of AST representation here is less than ideal. 788 ++Args; 789 --NumArgs; 790 } 791 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), 792 NumProtoArgs, 793 IsMemberFunction, TheCall->getRParenLoc(), 794 TheCall->getCallee()->getSourceRange(), CallType); 795 796 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 797 // None of the checks below are needed for functions that don't have 798 // simple names (e.g., C++ conversion functions). 799 if (!FnInfo) 800 return false; 801 802 unsigned CMId = FDecl->getMemoryFunctionKind(); 803 if (CMId == 0) 804 return false; 805 806 // Handle memory setting and copying functions. 807 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 808 CheckStrlcpycatArguments(TheCall, FnInfo); 809 else if (CMId == Builtin::BIstrncat) 810 CheckStrncatArguments(TheCall, FnInfo); 811 else 812 CheckMemaccessArguments(TheCall, CMId, FnInfo); 813 814 return false; 815} 816 817bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 818 ArrayRef<const Expr *> Args) { 819 VariadicCallType CallType = 820 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 821 822 checkCall(Method, Args, Method->param_size(), 823 /*IsMemberFunction=*/false, 824 lbrac, Method->getSourceRange(), CallType); 825 826 return false; 827} 828 829bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 830 const FunctionProtoType *Proto) { 831 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 832 if (!V) 833 return false; 834 835 QualType Ty = V->getType(); 836 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType()) 837 return false; 838 839 VariadicCallType CallType; 840 if (!Proto || !Proto->isVariadic()) { 841 CallType = VariadicDoesNotApply; 842 } else if (Ty->isBlockPointerType()) { 843 CallType = VariadicBlock; 844 } else { // Ty->isFunctionPointerType() 845 CallType = VariadicFunction; 846 } 847 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 848 849 checkCall(NDecl, 850 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(), 851 TheCall->getNumArgs()), 852 NumProtoArgs, /*IsMemberFunction=*/false, 853 TheCall->getRParenLoc(), 854 TheCall->getCallee()->getSourceRange(), CallType); 855 856 return false; 857} 858 859/// Checks function calls when a FunctionDecl or a NamedDecl is not available, 860/// such as function pointers returned from functions. 861bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 862 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto, 863 TheCall->getCallee()); 864 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 865 866 checkCall(/*FDecl=*/0, 867 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(), 868 TheCall->getNumArgs()), 869 NumProtoArgs, /*IsMemberFunction=*/false, 870 TheCall->getRParenLoc(), 871 TheCall->getCallee()->getSourceRange(), CallType); 872 873 return false; 874} 875 876ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 877 AtomicExpr::AtomicOp Op) { 878 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 879 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 880 881 // All these operations take one of the following forms: 882 enum { 883 // C __c11_atomic_init(A *, C) 884 Init, 885 // C __c11_atomic_load(A *, int) 886 Load, 887 // void __atomic_load(A *, CP, int) 888 Copy, 889 // C __c11_atomic_add(A *, M, int) 890 Arithmetic, 891 // C __atomic_exchange_n(A *, CP, int) 892 Xchg, 893 // void __atomic_exchange(A *, C *, CP, int) 894 GNUXchg, 895 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 896 C11CmpXchg, 897 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 898 GNUCmpXchg 899 } Form = Init; 900 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 901 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 902 // where: 903 // C is an appropriate type, 904 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 905 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 906 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 907 // the int parameters are for orderings. 908 909 assert(AtomicExpr::AO__c11_atomic_init == 0 && 910 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 911 && "need to update code for modified C11 atomics"); 912 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 913 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 914 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 915 Op == AtomicExpr::AO__atomic_store_n || 916 Op == AtomicExpr::AO__atomic_exchange_n || 917 Op == AtomicExpr::AO__atomic_compare_exchange_n; 918 bool IsAddSub = false; 919 920 switch (Op) { 921 case AtomicExpr::AO__c11_atomic_init: 922 Form = Init; 923 break; 924 925 case AtomicExpr::AO__c11_atomic_load: 926 case AtomicExpr::AO__atomic_load_n: 927 Form = Load; 928 break; 929 930 case AtomicExpr::AO__c11_atomic_store: 931 case AtomicExpr::AO__atomic_load: 932 case AtomicExpr::AO__atomic_store: 933 case AtomicExpr::AO__atomic_store_n: 934 Form = Copy; 935 break; 936 937 case AtomicExpr::AO__c11_atomic_fetch_add: 938 case AtomicExpr::AO__c11_atomic_fetch_sub: 939 case AtomicExpr::AO__atomic_fetch_add: 940 case AtomicExpr::AO__atomic_fetch_sub: 941 case AtomicExpr::AO__atomic_add_fetch: 942 case AtomicExpr::AO__atomic_sub_fetch: 943 IsAddSub = true; 944 // Fall through. 945 case AtomicExpr::AO__c11_atomic_fetch_and: 946 case AtomicExpr::AO__c11_atomic_fetch_or: 947 case AtomicExpr::AO__c11_atomic_fetch_xor: 948 case AtomicExpr::AO__atomic_fetch_and: 949 case AtomicExpr::AO__atomic_fetch_or: 950 case AtomicExpr::AO__atomic_fetch_xor: 951 case AtomicExpr::AO__atomic_fetch_nand: 952 case AtomicExpr::AO__atomic_and_fetch: 953 case AtomicExpr::AO__atomic_or_fetch: 954 case AtomicExpr::AO__atomic_xor_fetch: 955 case AtomicExpr::AO__atomic_nand_fetch: 956 Form = Arithmetic; 957 break; 958 959 case AtomicExpr::AO__c11_atomic_exchange: 960 case AtomicExpr::AO__atomic_exchange_n: 961 Form = Xchg; 962 break; 963 964 case AtomicExpr::AO__atomic_exchange: 965 Form = GNUXchg; 966 break; 967 968 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 969 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 970 Form = C11CmpXchg; 971 break; 972 973 case AtomicExpr::AO__atomic_compare_exchange: 974 case AtomicExpr::AO__atomic_compare_exchange_n: 975 Form = GNUCmpXchg; 976 break; 977 } 978 979 // Check we have the right number of arguments. 980 if (TheCall->getNumArgs() < NumArgs[Form]) { 981 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 982 << 0 << NumArgs[Form] << TheCall->getNumArgs() 983 << TheCall->getCallee()->getSourceRange(); 984 return ExprError(); 985 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 986 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 987 diag::err_typecheck_call_too_many_args) 988 << 0 << NumArgs[Form] << TheCall->getNumArgs() 989 << TheCall->getCallee()->getSourceRange(); 990 return ExprError(); 991 } 992 993 // Inspect the first argument of the atomic operation. 994 Expr *Ptr = TheCall->getArg(0); 995 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 996 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 997 if (!pointerType) { 998 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 999 << Ptr->getType() << Ptr->getSourceRange(); 1000 return ExprError(); 1001 } 1002 1003 // For a __c11 builtin, this should be a pointer to an _Atomic type. 1004 QualType AtomTy = pointerType->getPointeeType(); // 'A' 1005 QualType ValType = AtomTy; // 'C' 1006 if (IsC11) { 1007 if (!AtomTy->isAtomicType()) { 1008 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 1009 << Ptr->getType() << Ptr->getSourceRange(); 1010 return ExprError(); 1011 } 1012 if (AtomTy.isConstQualified()) { 1013 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 1014 << Ptr->getType() << Ptr->getSourceRange(); 1015 return ExprError(); 1016 } 1017 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 1018 } 1019 1020 // For an arithmetic operation, the implied arithmetic must be well-formed. 1021 if (Form == Arithmetic) { 1022 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 1023 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 1024 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1025 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1026 return ExprError(); 1027 } 1028 if (!IsAddSub && !ValType->isIntegerType()) { 1029 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 1030 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1031 return ExprError(); 1032 } 1033 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 1034 // For __atomic_*_n operations, the value type must be a scalar integral or 1035 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 1036 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1037 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1038 return ExprError(); 1039 } 1040 1041 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 1042 !AtomTy->isScalarType()) { 1043 // For GNU atomics, require a trivially-copyable type. This is not part of 1044 // the GNU atomics specification, but we enforce it for sanity. 1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 1046 << Ptr->getType() << Ptr->getSourceRange(); 1047 return ExprError(); 1048 } 1049 1050 // FIXME: For any builtin other than a load, the ValType must not be 1051 // const-qualified. 1052 1053 switch (ValType.getObjCLifetime()) { 1054 case Qualifiers::OCL_None: 1055 case Qualifiers::OCL_ExplicitNone: 1056 // okay 1057 break; 1058 1059 case Qualifiers::OCL_Weak: 1060 case Qualifiers::OCL_Strong: 1061 case Qualifiers::OCL_Autoreleasing: 1062 // FIXME: Can this happen? By this point, ValType should be known 1063 // to be trivially copyable. 1064 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1065 << ValType << Ptr->getSourceRange(); 1066 return ExprError(); 1067 } 1068 1069 QualType ResultType = ValType; 1070 if (Form == Copy || Form == GNUXchg || Form == Init) 1071 ResultType = Context.VoidTy; 1072 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 1073 ResultType = Context.BoolTy; 1074 1075 // The type of a parameter passed 'by value'. In the GNU atomics, such 1076 // arguments are actually passed as pointers. 1077 QualType ByValType = ValType; // 'CP' 1078 if (!IsC11 && !IsN) 1079 ByValType = Ptr->getType(); 1080 1081 // The first argument --- the pointer --- has a fixed type; we 1082 // deduce the types of the rest of the arguments accordingly. Walk 1083 // the remaining arguments, converting them to the deduced value type. 1084 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 1085 QualType Ty; 1086 if (i < NumVals[Form] + 1) { 1087 switch (i) { 1088 case 1: 1089 // The second argument is the non-atomic operand. For arithmetic, this 1090 // is always passed by value, and for a compare_exchange it is always 1091 // passed by address. For the rest, GNU uses by-address and C11 uses 1092 // by-value. 1093 assert(Form != Load); 1094 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 1095 Ty = ValType; 1096 else if (Form == Copy || Form == Xchg) 1097 Ty = ByValType; 1098 else if (Form == Arithmetic) 1099 Ty = Context.getPointerDiffType(); 1100 else 1101 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 1102 break; 1103 case 2: 1104 // The third argument to compare_exchange / GNU exchange is a 1105 // (pointer to a) desired value. 1106 Ty = ByValType; 1107 break; 1108 case 3: 1109 // The fourth argument to GNU compare_exchange is a 'weak' flag. 1110 Ty = Context.BoolTy; 1111 break; 1112 } 1113 } else { 1114 // The order(s) are always converted to int. 1115 Ty = Context.IntTy; 1116 } 1117 1118 InitializedEntity Entity = 1119 InitializedEntity::InitializeParameter(Context, Ty, false); 1120 ExprResult Arg = TheCall->getArg(i); 1121 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1122 if (Arg.isInvalid()) 1123 return true; 1124 TheCall->setArg(i, Arg.get()); 1125 } 1126 1127 // Permute the arguments into a 'consistent' order. 1128 SmallVector<Expr*, 5> SubExprs; 1129 SubExprs.push_back(Ptr); 1130 switch (Form) { 1131 case Init: 1132 // Note, AtomicExpr::getVal1() has a special case for this atomic. 1133 SubExprs.push_back(TheCall->getArg(1)); // Val1 1134 break; 1135 case Load: 1136 SubExprs.push_back(TheCall->getArg(1)); // Order 1137 break; 1138 case Copy: 1139 case Arithmetic: 1140 case Xchg: 1141 SubExprs.push_back(TheCall->getArg(2)); // Order 1142 SubExprs.push_back(TheCall->getArg(1)); // Val1 1143 break; 1144 case GNUXchg: 1145 // Note, AtomicExpr::getVal2() has a special case for this atomic. 1146 SubExprs.push_back(TheCall->getArg(3)); // Order 1147 SubExprs.push_back(TheCall->getArg(1)); // Val1 1148 SubExprs.push_back(TheCall->getArg(2)); // Val2 1149 break; 1150 case C11CmpXchg: 1151 SubExprs.push_back(TheCall->getArg(3)); // Order 1152 SubExprs.push_back(TheCall->getArg(1)); // Val1 1153 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 1154 SubExprs.push_back(TheCall->getArg(2)); // Val2 1155 break; 1156 case GNUCmpXchg: 1157 SubExprs.push_back(TheCall->getArg(4)); // Order 1158 SubExprs.push_back(TheCall->getArg(1)); // Val1 1159 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 1160 SubExprs.push_back(TheCall->getArg(2)); // Val2 1161 SubExprs.push_back(TheCall->getArg(3)); // Weak 1162 break; 1163 } 1164 1165 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 1166 SubExprs, ResultType, Op, 1167 TheCall->getRParenLoc()); 1168 1169 if ((Op == AtomicExpr::AO__c11_atomic_load || 1170 (Op == AtomicExpr::AO__c11_atomic_store)) && 1171 Context.AtomicUsesUnsupportedLibcall(AE)) 1172 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 1173 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 1174 1175 return Owned(AE); 1176} 1177 1178 1179/// checkBuiltinArgument - Given a call to a builtin function, perform 1180/// normal type-checking on the given argument, updating the call in 1181/// place. This is useful when a builtin function requires custom 1182/// type-checking for some of its arguments but not necessarily all of 1183/// them. 1184/// 1185/// Returns true on error. 1186static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 1187 FunctionDecl *Fn = E->getDirectCallee(); 1188 assert(Fn && "builtin call without direct callee!"); 1189 1190 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 1191 InitializedEntity Entity = 1192 InitializedEntity::InitializeParameter(S.Context, Param); 1193 1194 ExprResult Arg = E->getArg(0); 1195 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 1196 if (Arg.isInvalid()) 1197 return true; 1198 1199 E->setArg(ArgIndex, Arg.take()); 1200 return false; 1201} 1202 1203/// SemaBuiltinAtomicOverloaded - We have a call to a function like 1204/// __sync_fetch_and_add, which is an overloaded function based on the pointer 1205/// type of its first argument. The main ActOnCallExpr routines have already 1206/// promoted the types of arguments because all of these calls are prototyped as 1207/// void(...). 1208/// 1209/// This function goes through and does final semantic checking for these 1210/// builtins, 1211ExprResult 1212Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 1213 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 1214 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1215 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1216 1217 // Ensure that we have at least one argument to do type inference from. 1218 if (TheCall->getNumArgs() < 1) { 1219 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1220 << 0 << 1 << TheCall->getNumArgs() 1221 << TheCall->getCallee()->getSourceRange(); 1222 return ExprError(); 1223 } 1224 1225 // Inspect the first argument of the atomic builtin. This should always be 1226 // a pointer type, whose element is an integral scalar or pointer type. 1227 // Because it is a pointer type, we don't have to worry about any implicit 1228 // casts here. 1229 // FIXME: We don't allow floating point scalars as input. 1230 Expr *FirstArg = TheCall->getArg(0); 1231 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 1232 if (FirstArgResult.isInvalid()) 1233 return ExprError(); 1234 FirstArg = FirstArgResult.take(); 1235 TheCall->setArg(0, FirstArg); 1236 1237 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 1238 if (!pointerType) { 1239 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1240 << FirstArg->getType() << FirstArg->getSourceRange(); 1241 return ExprError(); 1242 } 1243 1244 QualType ValType = pointerType->getPointeeType(); 1245 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1246 !ValType->isBlockPointerType()) { 1247 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 1248 << FirstArg->getType() << FirstArg->getSourceRange(); 1249 return ExprError(); 1250 } 1251 1252 switch (ValType.getObjCLifetime()) { 1253 case Qualifiers::OCL_None: 1254 case Qualifiers::OCL_ExplicitNone: 1255 // okay 1256 break; 1257 1258 case Qualifiers::OCL_Weak: 1259 case Qualifiers::OCL_Strong: 1260 case Qualifiers::OCL_Autoreleasing: 1261 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1262 << ValType << FirstArg->getSourceRange(); 1263 return ExprError(); 1264 } 1265 1266 // Strip any qualifiers off ValType. 1267 ValType = ValType.getUnqualifiedType(); 1268 1269 // The majority of builtins return a value, but a few have special return 1270 // types, so allow them to override appropriately below. 1271 QualType ResultType = ValType; 1272 1273 // We need to figure out which concrete builtin this maps onto. For example, 1274 // __sync_fetch_and_add with a 2 byte object turns into 1275 // __sync_fetch_and_add_2. 1276#define BUILTIN_ROW(x) \ 1277 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 1278 Builtin::BI##x##_8, Builtin::BI##x##_16 } 1279 1280 static const unsigned BuiltinIndices[][5] = { 1281 BUILTIN_ROW(__sync_fetch_and_add), 1282 BUILTIN_ROW(__sync_fetch_and_sub), 1283 BUILTIN_ROW(__sync_fetch_and_or), 1284 BUILTIN_ROW(__sync_fetch_and_and), 1285 BUILTIN_ROW(__sync_fetch_and_xor), 1286 1287 BUILTIN_ROW(__sync_add_and_fetch), 1288 BUILTIN_ROW(__sync_sub_and_fetch), 1289 BUILTIN_ROW(__sync_and_and_fetch), 1290 BUILTIN_ROW(__sync_or_and_fetch), 1291 BUILTIN_ROW(__sync_xor_and_fetch), 1292 1293 BUILTIN_ROW(__sync_val_compare_and_swap), 1294 BUILTIN_ROW(__sync_bool_compare_and_swap), 1295 BUILTIN_ROW(__sync_lock_test_and_set), 1296 BUILTIN_ROW(__sync_lock_release), 1297 BUILTIN_ROW(__sync_swap) 1298 }; 1299#undef BUILTIN_ROW 1300 1301 // Determine the index of the size. 1302 unsigned SizeIndex; 1303 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1304 case 1: SizeIndex = 0; break; 1305 case 2: SizeIndex = 1; break; 1306 case 4: SizeIndex = 2; break; 1307 case 8: SizeIndex = 3; break; 1308 case 16: SizeIndex = 4; break; 1309 default: 1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1311 << FirstArg->getType() << FirstArg->getSourceRange(); 1312 return ExprError(); 1313 } 1314 1315 // Each of these builtins has one pointer argument, followed by some number of 1316 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1317 // that we ignore. Find out which row of BuiltinIndices to read from as well 1318 // as the number of fixed args. 1319 unsigned BuiltinID = FDecl->getBuiltinID(); 1320 unsigned BuiltinIndex, NumFixed = 1; 1321 switch (BuiltinID) { 1322 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1323 case Builtin::BI__sync_fetch_and_add: 1324 case Builtin::BI__sync_fetch_and_add_1: 1325 case Builtin::BI__sync_fetch_and_add_2: 1326 case Builtin::BI__sync_fetch_and_add_4: 1327 case Builtin::BI__sync_fetch_and_add_8: 1328 case Builtin::BI__sync_fetch_and_add_16: 1329 BuiltinIndex = 0; 1330 break; 1331 1332 case Builtin::BI__sync_fetch_and_sub: 1333 case Builtin::BI__sync_fetch_and_sub_1: 1334 case Builtin::BI__sync_fetch_and_sub_2: 1335 case Builtin::BI__sync_fetch_and_sub_4: 1336 case Builtin::BI__sync_fetch_and_sub_8: 1337 case Builtin::BI__sync_fetch_and_sub_16: 1338 BuiltinIndex = 1; 1339 break; 1340 1341 case Builtin::BI__sync_fetch_and_or: 1342 case Builtin::BI__sync_fetch_and_or_1: 1343 case Builtin::BI__sync_fetch_and_or_2: 1344 case Builtin::BI__sync_fetch_and_or_4: 1345 case Builtin::BI__sync_fetch_and_or_8: 1346 case Builtin::BI__sync_fetch_and_or_16: 1347 BuiltinIndex = 2; 1348 break; 1349 1350 case Builtin::BI__sync_fetch_and_and: 1351 case Builtin::BI__sync_fetch_and_and_1: 1352 case Builtin::BI__sync_fetch_and_and_2: 1353 case Builtin::BI__sync_fetch_and_and_4: 1354 case Builtin::BI__sync_fetch_and_and_8: 1355 case Builtin::BI__sync_fetch_and_and_16: 1356 BuiltinIndex = 3; 1357 break; 1358 1359 case Builtin::BI__sync_fetch_and_xor: 1360 case Builtin::BI__sync_fetch_and_xor_1: 1361 case Builtin::BI__sync_fetch_and_xor_2: 1362 case Builtin::BI__sync_fetch_and_xor_4: 1363 case Builtin::BI__sync_fetch_and_xor_8: 1364 case Builtin::BI__sync_fetch_and_xor_16: 1365 BuiltinIndex = 4; 1366 break; 1367 1368 case Builtin::BI__sync_add_and_fetch: 1369 case Builtin::BI__sync_add_and_fetch_1: 1370 case Builtin::BI__sync_add_and_fetch_2: 1371 case Builtin::BI__sync_add_and_fetch_4: 1372 case Builtin::BI__sync_add_and_fetch_8: 1373 case Builtin::BI__sync_add_and_fetch_16: 1374 BuiltinIndex = 5; 1375 break; 1376 1377 case Builtin::BI__sync_sub_and_fetch: 1378 case Builtin::BI__sync_sub_and_fetch_1: 1379 case Builtin::BI__sync_sub_and_fetch_2: 1380 case Builtin::BI__sync_sub_and_fetch_4: 1381 case Builtin::BI__sync_sub_and_fetch_8: 1382 case Builtin::BI__sync_sub_and_fetch_16: 1383 BuiltinIndex = 6; 1384 break; 1385 1386 case Builtin::BI__sync_and_and_fetch: 1387 case Builtin::BI__sync_and_and_fetch_1: 1388 case Builtin::BI__sync_and_and_fetch_2: 1389 case Builtin::BI__sync_and_and_fetch_4: 1390 case Builtin::BI__sync_and_and_fetch_8: 1391 case Builtin::BI__sync_and_and_fetch_16: 1392 BuiltinIndex = 7; 1393 break; 1394 1395 case Builtin::BI__sync_or_and_fetch: 1396 case Builtin::BI__sync_or_and_fetch_1: 1397 case Builtin::BI__sync_or_and_fetch_2: 1398 case Builtin::BI__sync_or_and_fetch_4: 1399 case Builtin::BI__sync_or_and_fetch_8: 1400 case Builtin::BI__sync_or_and_fetch_16: 1401 BuiltinIndex = 8; 1402 break; 1403 1404 case Builtin::BI__sync_xor_and_fetch: 1405 case Builtin::BI__sync_xor_and_fetch_1: 1406 case Builtin::BI__sync_xor_and_fetch_2: 1407 case Builtin::BI__sync_xor_and_fetch_4: 1408 case Builtin::BI__sync_xor_and_fetch_8: 1409 case Builtin::BI__sync_xor_and_fetch_16: 1410 BuiltinIndex = 9; 1411 break; 1412 1413 case Builtin::BI__sync_val_compare_and_swap: 1414 case Builtin::BI__sync_val_compare_and_swap_1: 1415 case Builtin::BI__sync_val_compare_and_swap_2: 1416 case Builtin::BI__sync_val_compare_and_swap_4: 1417 case Builtin::BI__sync_val_compare_and_swap_8: 1418 case Builtin::BI__sync_val_compare_and_swap_16: 1419 BuiltinIndex = 10; 1420 NumFixed = 2; 1421 break; 1422 1423 case Builtin::BI__sync_bool_compare_and_swap: 1424 case Builtin::BI__sync_bool_compare_and_swap_1: 1425 case Builtin::BI__sync_bool_compare_and_swap_2: 1426 case Builtin::BI__sync_bool_compare_and_swap_4: 1427 case Builtin::BI__sync_bool_compare_and_swap_8: 1428 case Builtin::BI__sync_bool_compare_and_swap_16: 1429 BuiltinIndex = 11; 1430 NumFixed = 2; 1431 ResultType = Context.BoolTy; 1432 break; 1433 1434 case Builtin::BI__sync_lock_test_and_set: 1435 case Builtin::BI__sync_lock_test_and_set_1: 1436 case Builtin::BI__sync_lock_test_and_set_2: 1437 case Builtin::BI__sync_lock_test_and_set_4: 1438 case Builtin::BI__sync_lock_test_and_set_8: 1439 case Builtin::BI__sync_lock_test_and_set_16: 1440 BuiltinIndex = 12; 1441 break; 1442 1443 case Builtin::BI__sync_lock_release: 1444 case Builtin::BI__sync_lock_release_1: 1445 case Builtin::BI__sync_lock_release_2: 1446 case Builtin::BI__sync_lock_release_4: 1447 case Builtin::BI__sync_lock_release_8: 1448 case Builtin::BI__sync_lock_release_16: 1449 BuiltinIndex = 13; 1450 NumFixed = 0; 1451 ResultType = Context.VoidTy; 1452 break; 1453 1454 case Builtin::BI__sync_swap: 1455 case Builtin::BI__sync_swap_1: 1456 case Builtin::BI__sync_swap_2: 1457 case Builtin::BI__sync_swap_4: 1458 case Builtin::BI__sync_swap_8: 1459 case Builtin::BI__sync_swap_16: 1460 BuiltinIndex = 14; 1461 break; 1462 } 1463 1464 // Now that we know how many fixed arguments we expect, first check that we 1465 // have at least that many. 1466 if (TheCall->getNumArgs() < 1+NumFixed) { 1467 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1468 << 0 << 1+NumFixed << TheCall->getNumArgs() 1469 << TheCall->getCallee()->getSourceRange(); 1470 return ExprError(); 1471 } 1472 1473 // Get the decl for the concrete builtin from this, we can tell what the 1474 // concrete integer type we should convert to is. 1475 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1476 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1477 FunctionDecl *NewBuiltinDecl; 1478 if (NewBuiltinID == BuiltinID) 1479 NewBuiltinDecl = FDecl; 1480 else { 1481 // Perform builtin lookup to avoid redeclaring it. 1482 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 1483 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 1484 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 1485 assert(Res.getFoundDecl()); 1486 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 1487 if (NewBuiltinDecl == 0) 1488 return ExprError(); 1489 } 1490 1491 // The first argument --- the pointer --- has a fixed type; we 1492 // deduce the types of the rest of the arguments accordingly. Walk 1493 // the remaining arguments, converting them to the deduced value type. 1494 for (unsigned i = 0; i != NumFixed; ++i) { 1495 ExprResult Arg = TheCall->getArg(i+1); 1496 1497 // GCC does an implicit conversion to the pointer or integer ValType. This 1498 // can fail in some cases (1i -> int**), check for this error case now. 1499 // Initialize the argument. 1500 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1501 ValType, /*consume*/ false); 1502 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1503 if (Arg.isInvalid()) 1504 return ExprError(); 1505 1506 // Okay, we have something that *can* be converted to the right type. Check 1507 // to see if there is a potentially weird extension going on here. This can 1508 // happen when you do an atomic operation on something like an char* and 1509 // pass in 42. The 42 gets converted to char. This is even more strange 1510 // for things like 45.123 -> char, etc. 1511 // FIXME: Do this check. 1512 TheCall->setArg(i+1, Arg.take()); 1513 } 1514 1515 ASTContext& Context = this->getASTContext(); 1516 1517 // Create a new DeclRefExpr to refer to the new decl. 1518 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1519 Context, 1520 DRE->getQualifierLoc(), 1521 SourceLocation(), 1522 NewBuiltinDecl, 1523 /*enclosing*/ false, 1524 DRE->getLocation(), 1525 Context.BuiltinFnTy, 1526 DRE->getValueKind()); 1527 1528 // Set the callee in the CallExpr. 1529 // FIXME: This loses syntactic information. 1530 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 1531 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 1532 CK_BuiltinFnToFnPtr); 1533 TheCall->setCallee(PromotedCall.take()); 1534 1535 // Change the result type of the call to match the original value type. This 1536 // is arbitrary, but the codegen for these builtins ins design to handle it 1537 // gracefully. 1538 TheCall->setType(ResultType); 1539 1540 return TheCallResult; 1541} 1542 1543/// CheckObjCString - Checks that the argument to the builtin 1544/// CFString constructor is correct 1545/// Note: It might also make sense to do the UTF-16 conversion here (would 1546/// simplify the backend). 1547bool Sema::CheckObjCString(Expr *Arg) { 1548 Arg = Arg->IgnoreParenCasts(); 1549 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1550 1551 if (!Literal || !Literal->isAscii()) { 1552 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1553 << Arg->getSourceRange(); 1554 return true; 1555 } 1556 1557 if (Literal->containsNonAsciiOrNull()) { 1558 StringRef String = Literal->getString(); 1559 unsigned NumBytes = String.size(); 1560 SmallVector<UTF16, 128> ToBuf(NumBytes); 1561 const UTF8 *FromPtr = (const UTF8 *)String.data(); 1562 UTF16 *ToPtr = &ToBuf[0]; 1563 1564 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1565 &ToPtr, ToPtr + NumBytes, 1566 strictConversion); 1567 // Check for conversion failure. 1568 if (Result != conversionOK) 1569 Diag(Arg->getLocStart(), 1570 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1571 } 1572 return false; 1573} 1574 1575/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1576/// Emit an error and return true on failure, return false on success. 1577bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1578 Expr *Fn = TheCall->getCallee(); 1579 if (TheCall->getNumArgs() > 2) { 1580 Diag(TheCall->getArg(2)->getLocStart(), 1581 diag::err_typecheck_call_too_many_args) 1582 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1583 << Fn->getSourceRange() 1584 << SourceRange(TheCall->getArg(2)->getLocStart(), 1585 (*(TheCall->arg_end()-1))->getLocEnd()); 1586 return true; 1587 } 1588 1589 if (TheCall->getNumArgs() < 2) { 1590 return Diag(TheCall->getLocEnd(), 1591 diag::err_typecheck_call_too_few_args_at_least) 1592 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1593 } 1594 1595 // Type-check the first argument normally. 1596 if (checkBuiltinArgument(*this, TheCall, 0)) 1597 return true; 1598 1599 // Determine whether the current function is variadic or not. 1600 BlockScopeInfo *CurBlock = getCurBlock(); 1601 bool isVariadic; 1602 if (CurBlock) 1603 isVariadic = CurBlock->TheDecl->isVariadic(); 1604 else if (FunctionDecl *FD = getCurFunctionDecl()) 1605 isVariadic = FD->isVariadic(); 1606 else 1607 isVariadic = getCurMethodDecl()->isVariadic(); 1608 1609 if (!isVariadic) { 1610 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1611 return true; 1612 } 1613 1614 // Verify that the second argument to the builtin is the last argument of the 1615 // current function or method. 1616 bool SecondArgIsLastNamedArgument = false; 1617 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1618 1619 // These are valid if SecondArgIsLastNamedArgument is false after the next 1620 // block. 1621 QualType Type; 1622 SourceLocation ParamLoc; 1623 1624 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1625 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1626 // FIXME: This isn't correct for methods (results in bogus warning). 1627 // Get the last formal in the current function. 1628 const ParmVarDecl *LastArg; 1629 if (CurBlock) 1630 LastArg = *(CurBlock->TheDecl->param_end()-1); 1631 else if (FunctionDecl *FD = getCurFunctionDecl()) 1632 LastArg = *(FD->param_end()-1); 1633 else 1634 LastArg = *(getCurMethodDecl()->param_end()-1); 1635 SecondArgIsLastNamedArgument = PV == LastArg; 1636 1637 Type = PV->getType(); 1638 ParamLoc = PV->getLocation(); 1639 } 1640 } 1641 1642 if (!SecondArgIsLastNamedArgument) 1643 Diag(TheCall->getArg(1)->getLocStart(), 1644 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1645 else if (Type->isReferenceType()) { 1646 Diag(Arg->getLocStart(), 1647 diag::warn_va_start_of_reference_type_is_undefined); 1648 Diag(ParamLoc, diag::note_parameter_type) << Type; 1649 } 1650 1651 return false; 1652} 1653 1654/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1655/// friends. This is declared to take (...), so we have to check everything. 1656bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1657 if (TheCall->getNumArgs() < 2) 1658 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1659 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1660 if (TheCall->getNumArgs() > 2) 1661 return Diag(TheCall->getArg(2)->getLocStart(), 1662 diag::err_typecheck_call_too_many_args) 1663 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1664 << SourceRange(TheCall->getArg(2)->getLocStart(), 1665 (*(TheCall->arg_end()-1))->getLocEnd()); 1666 1667 ExprResult OrigArg0 = TheCall->getArg(0); 1668 ExprResult OrigArg1 = TheCall->getArg(1); 1669 1670 // Do standard promotions between the two arguments, returning their common 1671 // type. 1672 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1673 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1674 return true; 1675 1676 // Make sure any conversions are pushed back into the call; this is 1677 // type safe since unordered compare builtins are declared as "_Bool 1678 // foo(...)". 1679 TheCall->setArg(0, OrigArg0.get()); 1680 TheCall->setArg(1, OrigArg1.get()); 1681 1682 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1683 return false; 1684 1685 // If the common type isn't a real floating type, then the arguments were 1686 // invalid for this operation. 1687 if (Res.isNull() || !Res->isRealFloatingType()) 1688 return Diag(OrigArg0.get()->getLocStart(), 1689 diag::err_typecheck_call_invalid_ordered_compare) 1690 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1691 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1692 1693 return false; 1694} 1695 1696/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1697/// __builtin_isnan and friends. This is declared to take (...), so we have 1698/// to check everything. We expect the last argument to be a floating point 1699/// value. 1700bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1701 if (TheCall->getNumArgs() < NumArgs) 1702 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1703 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1704 if (TheCall->getNumArgs() > NumArgs) 1705 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1706 diag::err_typecheck_call_too_many_args) 1707 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1708 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1709 (*(TheCall->arg_end()-1))->getLocEnd()); 1710 1711 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1712 1713 if (OrigArg->isTypeDependent()) 1714 return false; 1715 1716 // This operation requires a non-_Complex floating-point number. 1717 if (!OrigArg->getType()->isRealFloatingType()) 1718 return Diag(OrigArg->getLocStart(), 1719 diag::err_typecheck_call_invalid_unary_fp) 1720 << OrigArg->getType() << OrigArg->getSourceRange(); 1721 1722 // If this is an implicit conversion from float -> double, remove it. 1723 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1724 Expr *CastArg = Cast->getSubExpr(); 1725 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1726 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1727 "promotion from float to double is the only expected cast here"); 1728 Cast->setSubExpr(0); 1729 TheCall->setArg(NumArgs-1, CastArg); 1730 } 1731 } 1732 1733 return false; 1734} 1735 1736/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1737// This is declared to take (...), so we have to check everything. 1738ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1739 if (TheCall->getNumArgs() < 2) 1740 return ExprError(Diag(TheCall->getLocEnd(), 1741 diag::err_typecheck_call_too_few_args_at_least) 1742 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1743 << TheCall->getSourceRange()); 1744 1745 // Determine which of the following types of shufflevector we're checking: 1746 // 1) unary, vector mask: (lhs, mask) 1747 // 2) binary, vector mask: (lhs, rhs, mask) 1748 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1749 QualType resType = TheCall->getArg(0)->getType(); 1750 unsigned numElements = 0; 1751 1752 if (!TheCall->getArg(0)->isTypeDependent() && 1753 !TheCall->getArg(1)->isTypeDependent()) { 1754 QualType LHSType = TheCall->getArg(0)->getType(); 1755 QualType RHSType = TheCall->getArg(1)->getType(); 1756 1757 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 1758 return ExprError(Diag(TheCall->getLocStart(), 1759 diag::err_shufflevector_non_vector) 1760 << SourceRange(TheCall->getArg(0)->getLocStart(), 1761 TheCall->getArg(1)->getLocEnd())); 1762 1763 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1764 unsigned numResElements = TheCall->getNumArgs() - 2; 1765 1766 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1767 // with mask. If so, verify that RHS is an integer vector type with the 1768 // same number of elts as lhs. 1769 if (TheCall->getNumArgs() == 2) { 1770 if (!RHSType->hasIntegerRepresentation() || 1771 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1772 return ExprError(Diag(TheCall->getLocStart(), 1773 diag::err_shufflevector_incompatible_vector) 1774 << SourceRange(TheCall->getArg(1)->getLocStart(), 1775 TheCall->getArg(1)->getLocEnd())); 1776 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1777 return ExprError(Diag(TheCall->getLocStart(), 1778 diag::err_shufflevector_incompatible_vector) 1779 << SourceRange(TheCall->getArg(0)->getLocStart(), 1780 TheCall->getArg(1)->getLocEnd())); 1781 } else if (numElements != numResElements) { 1782 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1783 resType = Context.getVectorType(eltType, numResElements, 1784 VectorType::GenericVector); 1785 } 1786 } 1787 1788 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1789 if (TheCall->getArg(i)->isTypeDependent() || 1790 TheCall->getArg(i)->isValueDependent()) 1791 continue; 1792 1793 llvm::APSInt Result(32); 1794 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1795 return ExprError(Diag(TheCall->getLocStart(), 1796 diag::err_shufflevector_nonconstant_argument) 1797 << TheCall->getArg(i)->getSourceRange()); 1798 1799 // Allow -1 which will be translated to undef in the IR. 1800 if (Result.isSigned() && Result.isAllOnesValue()) 1801 continue; 1802 1803 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1804 return ExprError(Diag(TheCall->getLocStart(), 1805 diag::err_shufflevector_argument_too_large) 1806 << TheCall->getArg(i)->getSourceRange()); 1807 } 1808 1809 SmallVector<Expr*, 32> exprs; 1810 1811 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1812 exprs.push_back(TheCall->getArg(i)); 1813 TheCall->setArg(i, 0); 1814 } 1815 1816 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType, 1817 TheCall->getCallee()->getLocStart(), 1818 TheCall->getRParenLoc())); 1819} 1820 1821/// SemaConvertVectorExpr - Handle __builtin_convertvector 1822ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 1823 SourceLocation BuiltinLoc, 1824 SourceLocation RParenLoc) { 1825 ExprValueKind VK = VK_RValue; 1826 ExprObjectKind OK = OK_Ordinary; 1827 QualType DstTy = TInfo->getType(); 1828 QualType SrcTy = E->getType(); 1829 1830 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 1831 return ExprError(Diag(BuiltinLoc, 1832 diag::err_convertvector_non_vector) 1833 << E->getSourceRange()); 1834 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 1835 return ExprError(Diag(BuiltinLoc, 1836 diag::err_convertvector_non_vector_type)); 1837 1838 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 1839 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 1840 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 1841 if (SrcElts != DstElts) 1842 return ExprError(Diag(BuiltinLoc, 1843 diag::err_convertvector_incompatible_vector) 1844 << E->getSourceRange()); 1845 } 1846 1847 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK, 1848 BuiltinLoc, RParenLoc)); 1849 1850} 1851 1852/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1853// This is declared to take (const void*, ...) and can take two 1854// optional constant int args. 1855bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1856 unsigned NumArgs = TheCall->getNumArgs(); 1857 1858 if (NumArgs > 3) 1859 return Diag(TheCall->getLocEnd(), 1860 diag::err_typecheck_call_too_many_args_at_most) 1861 << 0 /*function call*/ << 3 << NumArgs 1862 << TheCall->getSourceRange(); 1863 1864 // Argument 0 is checked for us and the remaining arguments must be 1865 // constant integers. 1866 for (unsigned i = 1; i != NumArgs; ++i) { 1867 Expr *Arg = TheCall->getArg(i); 1868 1869 // We can't check the value of a dependent argument. 1870 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1871 continue; 1872 1873 llvm::APSInt Result; 1874 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1875 return true; 1876 1877 // FIXME: gcc issues a warning and rewrites these to 0. These 1878 // seems especially odd for the third argument since the default 1879 // is 3. 1880 if (i == 1) { 1881 if (Result.getLimitedValue() > 1) 1882 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1883 << "0" << "1" << Arg->getSourceRange(); 1884 } else { 1885 if (Result.getLimitedValue() > 3) 1886 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1887 << "0" << "3" << Arg->getSourceRange(); 1888 } 1889 } 1890 1891 return false; 1892} 1893 1894/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1895/// TheCall is a constant expression. 1896bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1897 llvm::APSInt &Result) { 1898 Expr *Arg = TheCall->getArg(ArgNum); 1899 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1900 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1901 1902 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1903 1904 if (!Arg->isIntegerConstantExpr(Result, Context)) 1905 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1906 << FDecl->getDeclName() << Arg->getSourceRange(); 1907 1908 return false; 1909} 1910 1911/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1912/// int type). This simply type checks that type is one of the defined 1913/// constants (0-3). 1914// For compatibility check 0-3, llvm only handles 0 and 2. 1915bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1916 llvm::APSInt Result; 1917 1918 // We can't check the value of a dependent argument. 1919 if (TheCall->getArg(1)->isTypeDependent() || 1920 TheCall->getArg(1)->isValueDependent()) 1921 return false; 1922 1923 // Check constant-ness first. 1924 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1925 return true; 1926 1927 Expr *Arg = TheCall->getArg(1); 1928 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1929 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1930 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1931 } 1932 1933 return false; 1934} 1935 1936/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1937/// This checks that val is a constant 1. 1938bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1939 Expr *Arg = TheCall->getArg(1); 1940 llvm::APSInt Result; 1941 1942 // TODO: This is less than ideal. Overload this to take a value. 1943 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1944 return true; 1945 1946 if (Result != 1) 1947 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1948 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1949 1950 return false; 1951} 1952 1953namespace { 1954enum StringLiteralCheckType { 1955 SLCT_NotALiteral, 1956 SLCT_UncheckedLiteral, 1957 SLCT_CheckedLiteral 1958}; 1959} 1960 1961// Determine if an expression is a string literal or constant string. 1962// If this function returns false on the arguments to a function expecting a 1963// format string, we will usually need to emit a warning. 1964// True string literals are then checked by CheckFormatString. 1965static StringLiteralCheckType 1966checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 1967 bool HasVAListArg, unsigned format_idx, 1968 unsigned firstDataArg, Sema::FormatStringType Type, 1969 Sema::VariadicCallType CallType, bool InFunctionCall, 1970 llvm::SmallBitVector &CheckedVarArgs) { 1971 tryAgain: 1972 if (E->isTypeDependent() || E->isValueDependent()) 1973 return SLCT_NotALiteral; 1974 1975 E = E->IgnoreParenCasts(); 1976 1977 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 1978 // Technically -Wformat-nonliteral does not warn about this case. 1979 // The behavior of printf and friends in this case is implementation 1980 // dependent. Ideally if the format string cannot be null then 1981 // it should have a 'nonnull' attribute in the function prototype. 1982 return SLCT_UncheckedLiteral; 1983 1984 switch (E->getStmtClass()) { 1985 case Stmt::BinaryConditionalOperatorClass: 1986 case Stmt::ConditionalOperatorClass: { 1987 // The expression is a literal if both sub-expressions were, and it was 1988 // completely checked only if both sub-expressions were checked. 1989 const AbstractConditionalOperator *C = 1990 cast<AbstractConditionalOperator>(E); 1991 StringLiteralCheckType Left = 1992 checkFormatStringExpr(S, C->getTrueExpr(), Args, 1993 HasVAListArg, format_idx, firstDataArg, 1994 Type, CallType, InFunctionCall, CheckedVarArgs); 1995 if (Left == SLCT_NotALiteral) 1996 return SLCT_NotALiteral; 1997 StringLiteralCheckType Right = 1998 checkFormatStringExpr(S, C->getFalseExpr(), Args, 1999 HasVAListArg, format_idx, firstDataArg, 2000 Type, CallType, InFunctionCall, CheckedVarArgs); 2001 return Left < Right ? Left : Right; 2002 } 2003 2004 case Stmt::ImplicitCastExprClass: { 2005 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 2006 goto tryAgain; 2007 } 2008 2009 case Stmt::OpaqueValueExprClass: 2010 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 2011 E = src; 2012 goto tryAgain; 2013 } 2014 return SLCT_NotALiteral; 2015 2016 case Stmt::PredefinedExprClass: 2017 // While __func__, etc., are technically not string literals, they 2018 // cannot contain format specifiers and thus are not a security 2019 // liability. 2020 return SLCT_UncheckedLiteral; 2021 2022 case Stmt::DeclRefExprClass: { 2023 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 2024 2025 // As an exception, do not flag errors for variables binding to 2026 // const string literals. 2027 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 2028 bool isConstant = false; 2029 QualType T = DR->getType(); 2030 2031 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 2032 isConstant = AT->getElementType().isConstant(S.Context); 2033 } else if (const PointerType *PT = T->getAs<PointerType>()) { 2034 isConstant = T.isConstant(S.Context) && 2035 PT->getPointeeType().isConstant(S.Context); 2036 } else if (T->isObjCObjectPointerType()) { 2037 // In ObjC, there is usually no "const ObjectPointer" type, 2038 // so don't check if the pointee type is constant. 2039 isConstant = T.isConstant(S.Context); 2040 } 2041 2042 if (isConstant) { 2043 if (const Expr *Init = VD->getAnyInitializer()) { 2044 // Look through initializers like const char c[] = { "foo" } 2045 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2046 if (InitList->isStringLiteralInit()) 2047 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 2048 } 2049 return checkFormatStringExpr(S, Init, Args, 2050 HasVAListArg, format_idx, 2051 firstDataArg, Type, CallType, 2052 /*InFunctionCall*/false, CheckedVarArgs); 2053 } 2054 } 2055 2056 // For vprintf* functions (i.e., HasVAListArg==true), we add a 2057 // special check to see if the format string is a function parameter 2058 // of the function calling the printf function. If the function 2059 // has an attribute indicating it is a printf-like function, then we 2060 // should suppress warnings concerning non-literals being used in a call 2061 // to a vprintf function. For example: 2062 // 2063 // void 2064 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 2065 // va_list ap; 2066 // va_start(ap, fmt); 2067 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 2068 // ... 2069 // } 2070 if (HasVAListArg) { 2071 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 2072 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 2073 int PVIndex = PV->getFunctionScopeIndex() + 1; 2074 for (specific_attr_iterator<FormatAttr> 2075 i = ND->specific_attr_begin<FormatAttr>(), 2076 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 2077 FormatAttr *PVFormat = *i; 2078 // adjust for implicit parameter 2079 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2080 if (MD->isInstance()) 2081 ++PVIndex; 2082 // We also check if the formats are compatible. 2083 // We can't pass a 'scanf' string to a 'printf' function. 2084 if (PVIndex == PVFormat->getFormatIdx() && 2085 Type == S.GetFormatStringType(PVFormat)) 2086 return SLCT_UncheckedLiteral; 2087 } 2088 } 2089 } 2090 } 2091 } 2092 2093 return SLCT_NotALiteral; 2094 } 2095 2096 case Stmt::CallExprClass: 2097 case Stmt::CXXMemberCallExprClass: { 2098 const CallExpr *CE = cast<CallExpr>(E); 2099 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 2100 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 2101 unsigned ArgIndex = FA->getFormatIdx(); 2102 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2103 if (MD->isInstance()) 2104 --ArgIndex; 2105 const Expr *Arg = CE->getArg(ArgIndex - 1); 2106 2107 return checkFormatStringExpr(S, Arg, Args, 2108 HasVAListArg, format_idx, firstDataArg, 2109 Type, CallType, InFunctionCall, 2110 CheckedVarArgs); 2111 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 2112 unsigned BuiltinID = FD->getBuiltinID(); 2113 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 2114 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 2115 const Expr *Arg = CE->getArg(0); 2116 return checkFormatStringExpr(S, Arg, Args, 2117 HasVAListArg, format_idx, 2118 firstDataArg, Type, CallType, 2119 InFunctionCall, CheckedVarArgs); 2120 } 2121 } 2122 } 2123 2124 return SLCT_NotALiteral; 2125 } 2126 case Stmt::ObjCStringLiteralClass: 2127 case Stmt::StringLiteralClass: { 2128 const StringLiteral *StrE = NULL; 2129 2130 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 2131 StrE = ObjCFExpr->getString(); 2132 else 2133 StrE = cast<StringLiteral>(E); 2134 2135 if (StrE) { 2136 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg, 2137 Type, InFunctionCall, CallType, CheckedVarArgs); 2138 return SLCT_CheckedLiteral; 2139 } 2140 2141 return SLCT_NotALiteral; 2142 } 2143 2144 default: 2145 return SLCT_NotALiteral; 2146 } 2147} 2148 2149void 2150Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 2151 const Expr * const *ExprArgs, 2152 SourceLocation CallSiteLoc) { 2153 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 2154 e = NonNull->args_end(); 2155 i != e; ++i) { 2156 const Expr *ArgExpr = ExprArgs[*i]; 2157 2158 // As a special case, transparent unions initialized with zero are 2159 // considered null for the purposes of the nonnull attribute. 2160 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) { 2161 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2162 if (const CompoundLiteralExpr *CLE = 2163 dyn_cast<CompoundLiteralExpr>(ArgExpr)) 2164 if (const InitListExpr *ILE = 2165 dyn_cast<InitListExpr>(CLE->getInitializer())) 2166 ArgExpr = ILE->getInit(0); 2167 } 2168 2169 bool Result; 2170 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result) 2171 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 2172 } 2173} 2174 2175Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 2176 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 2177 .Case("scanf", FST_Scanf) 2178 .Cases("printf", "printf0", FST_Printf) 2179 .Cases("NSString", "CFString", FST_NSString) 2180 .Case("strftime", FST_Strftime) 2181 .Case("strfmon", FST_Strfmon) 2182 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 2183 .Default(FST_Unknown); 2184} 2185 2186/// CheckFormatArguments - Check calls to printf and scanf (and similar 2187/// functions) for correct use of format strings. 2188/// Returns true if a format string has been fully checked. 2189bool Sema::CheckFormatArguments(const FormatAttr *Format, 2190 ArrayRef<const Expr *> Args, 2191 bool IsCXXMember, 2192 VariadicCallType CallType, 2193 SourceLocation Loc, SourceRange Range, 2194 llvm::SmallBitVector &CheckedVarArgs) { 2195 FormatStringInfo FSI; 2196 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 2197 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 2198 FSI.FirstDataArg, GetFormatStringType(Format), 2199 CallType, Loc, Range, CheckedVarArgs); 2200 return false; 2201} 2202 2203bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 2204 bool HasVAListArg, unsigned format_idx, 2205 unsigned firstDataArg, FormatStringType Type, 2206 VariadicCallType CallType, 2207 SourceLocation Loc, SourceRange Range, 2208 llvm::SmallBitVector &CheckedVarArgs) { 2209 // CHECK: printf/scanf-like function is called with no format string. 2210 if (format_idx >= Args.size()) { 2211 Diag(Loc, diag::warn_missing_format_string) << Range; 2212 return false; 2213 } 2214 2215 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 2216 2217 // CHECK: format string is not a string literal. 2218 // 2219 // Dynamically generated format strings are difficult to 2220 // automatically vet at compile time. Requiring that format strings 2221 // are string literals: (1) permits the checking of format strings by 2222 // the compiler and thereby (2) can practically remove the source of 2223 // many format string exploits. 2224 2225 // Format string can be either ObjC string (e.g. @"%d") or 2226 // C string (e.g. "%d") 2227 // ObjC string uses the same format specifiers as C string, so we can use 2228 // the same format string checking logic for both ObjC and C strings. 2229 StringLiteralCheckType CT = 2230 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 2231 format_idx, firstDataArg, Type, CallType, 2232 /*IsFunctionCall*/true, CheckedVarArgs); 2233 if (CT != SLCT_NotALiteral) 2234 // Literal format string found, check done! 2235 return CT == SLCT_CheckedLiteral; 2236 2237 // Strftime is particular as it always uses a single 'time' argument, 2238 // so it is safe to pass a non-literal string. 2239 if (Type == FST_Strftime) 2240 return false; 2241 2242 // Do not emit diag when the string param is a macro expansion and the 2243 // format is either NSString or CFString. This is a hack to prevent 2244 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 2245 // which are usually used in place of NS and CF string literals. 2246 if (Type == FST_NSString && 2247 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 2248 return false; 2249 2250 // If there are no arguments specified, warn with -Wformat-security, otherwise 2251 // warn only with -Wformat-nonliteral. 2252 if (Args.size() == firstDataArg) 2253 Diag(Args[format_idx]->getLocStart(), 2254 diag::warn_format_nonliteral_noargs) 2255 << OrigFormatExpr->getSourceRange(); 2256 else 2257 Diag(Args[format_idx]->getLocStart(), 2258 diag::warn_format_nonliteral) 2259 << OrigFormatExpr->getSourceRange(); 2260 return false; 2261} 2262 2263namespace { 2264class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 2265protected: 2266 Sema &S; 2267 const StringLiteral *FExpr; 2268 const Expr *OrigFormatExpr; 2269 const unsigned FirstDataArg; 2270 const unsigned NumDataArgs; 2271 const char *Beg; // Start of format string. 2272 const bool HasVAListArg; 2273 ArrayRef<const Expr *> Args; 2274 unsigned FormatIdx; 2275 llvm::SmallBitVector CoveredArgs; 2276 bool usesPositionalArgs; 2277 bool atFirstArg; 2278 bool inFunctionCall; 2279 Sema::VariadicCallType CallType; 2280 llvm::SmallBitVector &CheckedVarArgs; 2281public: 2282 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 2283 const Expr *origFormatExpr, unsigned firstDataArg, 2284 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2285 ArrayRef<const Expr *> Args, 2286 unsigned formatIdx, bool inFunctionCall, 2287 Sema::VariadicCallType callType, 2288 llvm::SmallBitVector &CheckedVarArgs) 2289 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 2290 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 2291 Beg(beg), HasVAListArg(hasVAListArg), 2292 Args(Args), FormatIdx(formatIdx), 2293 usesPositionalArgs(false), atFirstArg(true), 2294 inFunctionCall(inFunctionCall), CallType(callType), 2295 CheckedVarArgs(CheckedVarArgs) { 2296 CoveredArgs.resize(numDataArgs); 2297 CoveredArgs.reset(); 2298 } 2299 2300 void DoneProcessing(); 2301 2302 void HandleIncompleteSpecifier(const char *startSpecifier, 2303 unsigned specifierLen); 2304 2305 void HandleInvalidLengthModifier( 2306 const analyze_format_string::FormatSpecifier &FS, 2307 const analyze_format_string::ConversionSpecifier &CS, 2308 const char *startSpecifier, unsigned specifierLen, unsigned DiagID); 2309 2310 void HandleNonStandardLengthModifier( 2311 const analyze_format_string::FormatSpecifier &FS, 2312 const char *startSpecifier, unsigned specifierLen); 2313 2314 void HandleNonStandardConversionSpecifier( 2315 const analyze_format_string::ConversionSpecifier &CS, 2316 const char *startSpecifier, unsigned specifierLen); 2317 2318 virtual void HandlePosition(const char *startPos, unsigned posLen); 2319 2320 virtual void HandleInvalidPosition(const char *startSpecifier, 2321 unsigned specifierLen, 2322 analyze_format_string::PositionContext p); 2323 2324 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 2325 2326 void HandleNullChar(const char *nullCharacter); 2327 2328 template <typename Range> 2329 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 2330 const Expr *ArgumentExpr, 2331 PartialDiagnostic PDiag, 2332 SourceLocation StringLoc, 2333 bool IsStringLocation, Range StringRange, 2334 ArrayRef<FixItHint> Fixit = None); 2335 2336protected: 2337 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 2338 const char *startSpec, 2339 unsigned specifierLen, 2340 const char *csStart, unsigned csLen); 2341 2342 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 2343 const char *startSpec, 2344 unsigned specifierLen); 2345 2346 SourceRange getFormatStringRange(); 2347 CharSourceRange getSpecifierRange(const char *startSpecifier, 2348 unsigned specifierLen); 2349 SourceLocation getLocationOfByte(const char *x); 2350 2351 const Expr *getDataArg(unsigned i) const; 2352 2353 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 2354 const analyze_format_string::ConversionSpecifier &CS, 2355 const char *startSpecifier, unsigned specifierLen, 2356 unsigned argIndex); 2357 2358 template <typename Range> 2359 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 2360 bool IsStringLocation, Range StringRange, 2361 ArrayRef<FixItHint> Fixit = None); 2362 2363 void CheckPositionalAndNonpositionalArgs( 2364 const analyze_format_string::FormatSpecifier *FS); 2365}; 2366} 2367 2368SourceRange CheckFormatHandler::getFormatStringRange() { 2369 return OrigFormatExpr->getSourceRange(); 2370} 2371 2372CharSourceRange CheckFormatHandler:: 2373getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2374 SourceLocation Start = getLocationOfByte(startSpecifier); 2375 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2376 2377 // Advance the end SourceLocation by one due to half-open ranges. 2378 End = End.getLocWithOffset(1); 2379 2380 return CharSourceRange::getCharRange(Start, End); 2381} 2382 2383SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2384 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2385} 2386 2387void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2388 unsigned specifierLen){ 2389 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2390 getLocationOfByte(startSpecifier), 2391 /*IsStringLocation*/true, 2392 getSpecifierRange(startSpecifier, specifierLen)); 2393} 2394 2395void CheckFormatHandler::HandleInvalidLengthModifier( 2396 const analyze_format_string::FormatSpecifier &FS, 2397 const analyze_format_string::ConversionSpecifier &CS, 2398 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 2399 using namespace analyze_format_string; 2400 2401 const LengthModifier &LM = FS.getLengthModifier(); 2402 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2403 2404 // See if we know how to fix this length modifier. 2405 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2406 if (FixedLM) { 2407 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2408 getLocationOfByte(LM.getStart()), 2409 /*IsStringLocation*/true, 2410 getSpecifierRange(startSpecifier, specifierLen)); 2411 2412 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2413 << FixedLM->toString() 2414 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2415 2416 } else { 2417 FixItHint Hint; 2418 if (DiagID == diag::warn_format_nonsensical_length) 2419 Hint = FixItHint::CreateRemoval(LMRange); 2420 2421 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2422 getLocationOfByte(LM.getStart()), 2423 /*IsStringLocation*/true, 2424 getSpecifierRange(startSpecifier, specifierLen), 2425 Hint); 2426 } 2427} 2428 2429void CheckFormatHandler::HandleNonStandardLengthModifier( 2430 const analyze_format_string::FormatSpecifier &FS, 2431 const char *startSpecifier, unsigned specifierLen) { 2432 using namespace analyze_format_string; 2433 2434 const LengthModifier &LM = FS.getLengthModifier(); 2435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2436 2437 // See if we know how to fix this length modifier. 2438 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2439 if (FixedLM) { 2440 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2441 << LM.toString() << 0, 2442 getLocationOfByte(LM.getStart()), 2443 /*IsStringLocation*/true, 2444 getSpecifierRange(startSpecifier, specifierLen)); 2445 2446 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2447 << FixedLM->toString() 2448 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2449 2450 } else { 2451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2452 << LM.toString() << 0, 2453 getLocationOfByte(LM.getStart()), 2454 /*IsStringLocation*/true, 2455 getSpecifierRange(startSpecifier, specifierLen)); 2456 } 2457} 2458 2459void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2460 const analyze_format_string::ConversionSpecifier &CS, 2461 const char *startSpecifier, unsigned specifierLen) { 2462 using namespace analyze_format_string; 2463 2464 // See if we know how to fix this conversion specifier. 2465 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 2466 if (FixedCS) { 2467 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2468 << CS.toString() << /*conversion specifier*/1, 2469 getLocationOfByte(CS.getStart()), 2470 /*IsStringLocation*/true, 2471 getSpecifierRange(startSpecifier, specifierLen)); 2472 2473 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 2474 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 2475 << FixedCS->toString() 2476 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 2477 } else { 2478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2479 << CS.toString() << /*conversion specifier*/1, 2480 getLocationOfByte(CS.getStart()), 2481 /*IsStringLocation*/true, 2482 getSpecifierRange(startSpecifier, specifierLen)); 2483 } 2484} 2485 2486void CheckFormatHandler::HandlePosition(const char *startPos, 2487 unsigned posLen) { 2488 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2489 getLocationOfByte(startPos), 2490 /*IsStringLocation*/true, 2491 getSpecifierRange(startPos, posLen)); 2492} 2493 2494void 2495CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2496 analyze_format_string::PositionContext p) { 2497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2498 << (unsigned) p, 2499 getLocationOfByte(startPos), /*IsStringLocation*/true, 2500 getSpecifierRange(startPos, posLen)); 2501} 2502 2503void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2504 unsigned posLen) { 2505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 2506 getLocationOfByte(startPos), 2507 /*IsStringLocation*/true, 2508 getSpecifierRange(startPos, posLen)); 2509} 2510 2511void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 2512 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 2513 // The presence of a null character is likely an error. 2514 EmitFormatDiagnostic( 2515 S.PDiag(diag::warn_printf_format_string_contains_null_char), 2516 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 2517 getFormatStringRange()); 2518 } 2519} 2520 2521// Note that this may return NULL if there was an error parsing or building 2522// one of the argument expressions. 2523const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 2524 return Args[FirstDataArg + i]; 2525} 2526 2527void CheckFormatHandler::DoneProcessing() { 2528 // Does the number of data arguments exceed the number of 2529 // format conversions in the format string? 2530 if (!HasVAListArg) { 2531 // Find any arguments that weren't covered. 2532 CoveredArgs.flip(); 2533 signed notCoveredArg = CoveredArgs.find_first(); 2534 if (notCoveredArg >= 0) { 2535 assert((unsigned)notCoveredArg < NumDataArgs); 2536 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 2537 SourceLocation Loc = E->getLocStart(); 2538 if (!S.getSourceManager().isInSystemMacro(Loc)) { 2539 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 2540 Loc, /*IsStringLocation*/false, 2541 getFormatStringRange()); 2542 } 2543 } 2544 } 2545 } 2546} 2547 2548bool 2549CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2550 SourceLocation Loc, 2551 const char *startSpec, 2552 unsigned specifierLen, 2553 const char *csStart, 2554 unsigned csLen) { 2555 2556 bool keepGoing = true; 2557 if (argIndex < NumDataArgs) { 2558 // Consider the argument coverered, even though the specifier doesn't 2559 // make sense. 2560 CoveredArgs.set(argIndex); 2561 } 2562 else { 2563 // If argIndex exceeds the number of data arguments we 2564 // don't issue a warning because that is just a cascade of warnings (and 2565 // they may have intended '%%' anyway). We don't want to continue processing 2566 // the format string after this point, however, as we will like just get 2567 // gibberish when trying to match arguments. 2568 keepGoing = false; 2569 } 2570 2571 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2572 << StringRef(csStart, csLen), 2573 Loc, /*IsStringLocation*/true, 2574 getSpecifierRange(startSpec, specifierLen)); 2575 2576 return keepGoing; 2577} 2578 2579void 2580CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2581 const char *startSpec, 2582 unsigned specifierLen) { 2583 EmitFormatDiagnostic( 2584 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2585 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2586} 2587 2588bool 2589CheckFormatHandler::CheckNumArgs( 2590 const analyze_format_string::FormatSpecifier &FS, 2591 const analyze_format_string::ConversionSpecifier &CS, 2592 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2593 2594 if (argIndex >= NumDataArgs) { 2595 PartialDiagnostic PDiag = FS.usesPositionalArg() 2596 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2597 << (argIndex+1) << NumDataArgs) 2598 : S.PDiag(diag::warn_printf_insufficient_data_args); 2599 EmitFormatDiagnostic( 2600 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2601 getSpecifierRange(startSpecifier, specifierLen)); 2602 return false; 2603 } 2604 return true; 2605} 2606 2607template<typename Range> 2608void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2609 SourceLocation Loc, 2610 bool IsStringLocation, 2611 Range StringRange, 2612 ArrayRef<FixItHint> FixIt) { 2613 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2614 Loc, IsStringLocation, StringRange, FixIt); 2615} 2616 2617/// \brief If the format string is not within the funcion call, emit a note 2618/// so that the function call and string are in diagnostic messages. 2619/// 2620/// \param InFunctionCall if true, the format string is within the function 2621/// call and only one diagnostic message will be produced. Otherwise, an 2622/// extra note will be emitted pointing to location of the format string. 2623/// 2624/// \param ArgumentExpr the expression that is passed as the format string 2625/// argument in the function call. Used for getting locations when two 2626/// diagnostics are emitted. 2627/// 2628/// \param PDiag the callee should already have provided any strings for the 2629/// diagnostic message. This function only adds locations and fixits 2630/// to diagnostics. 2631/// 2632/// \param Loc primary location for diagnostic. If two diagnostics are 2633/// required, one will be at Loc and a new SourceLocation will be created for 2634/// the other one. 2635/// 2636/// \param IsStringLocation if true, Loc points to the format string should be 2637/// used for the note. Otherwise, Loc points to the argument list and will 2638/// be used with PDiag. 2639/// 2640/// \param StringRange some or all of the string to highlight. This is 2641/// templated so it can accept either a CharSourceRange or a SourceRange. 2642/// 2643/// \param FixIt optional fix it hint for the format string. 2644template<typename Range> 2645void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2646 const Expr *ArgumentExpr, 2647 PartialDiagnostic PDiag, 2648 SourceLocation Loc, 2649 bool IsStringLocation, 2650 Range StringRange, 2651 ArrayRef<FixItHint> FixIt) { 2652 if (InFunctionCall) { 2653 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 2654 D << StringRange; 2655 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2656 I != E; ++I) { 2657 D << *I; 2658 } 2659 } else { 2660 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2661 << ArgumentExpr->getSourceRange(); 2662 2663 const Sema::SemaDiagnosticBuilder &Note = 2664 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2665 diag::note_format_string_defined); 2666 2667 Note << StringRange; 2668 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2669 I != E; ++I) { 2670 Note << *I; 2671 } 2672 } 2673} 2674 2675//===--- CHECK: Printf format string checking ------------------------------===// 2676 2677namespace { 2678class CheckPrintfHandler : public CheckFormatHandler { 2679 bool ObjCContext; 2680public: 2681 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2682 const Expr *origFormatExpr, unsigned firstDataArg, 2683 unsigned numDataArgs, bool isObjC, 2684 const char *beg, bool hasVAListArg, 2685 ArrayRef<const Expr *> Args, 2686 unsigned formatIdx, bool inFunctionCall, 2687 Sema::VariadicCallType CallType, 2688 llvm::SmallBitVector &CheckedVarArgs) 2689 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2690 numDataArgs, beg, hasVAListArg, Args, 2691 formatIdx, inFunctionCall, CallType, CheckedVarArgs), 2692 ObjCContext(isObjC) 2693 {} 2694 2695 2696 bool HandleInvalidPrintfConversionSpecifier( 2697 const analyze_printf::PrintfSpecifier &FS, 2698 const char *startSpecifier, 2699 unsigned specifierLen); 2700 2701 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2702 const char *startSpecifier, 2703 unsigned specifierLen); 2704 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2705 const char *StartSpecifier, 2706 unsigned SpecifierLen, 2707 const Expr *E); 2708 2709 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2710 const char *startSpecifier, unsigned specifierLen); 2711 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2712 const analyze_printf::OptionalAmount &Amt, 2713 unsigned type, 2714 const char *startSpecifier, unsigned specifierLen); 2715 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2716 const analyze_printf::OptionalFlag &flag, 2717 const char *startSpecifier, unsigned specifierLen); 2718 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2719 const analyze_printf::OptionalFlag &ignoredFlag, 2720 const analyze_printf::OptionalFlag &flag, 2721 const char *startSpecifier, unsigned specifierLen); 2722 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 2723 const Expr *E, const CharSourceRange &CSR); 2724 2725}; 2726} 2727 2728bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2729 const analyze_printf::PrintfSpecifier &FS, 2730 const char *startSpecifier, 2731 unsigned specifierLen) { 2732 const analyze_printf::PrintfConversionSpecifier &CS = 2733 FS.getConversionSpecifier(); 2734 2735 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2736 getLocationOfByte(CS.getStart()), 2737 startSpecifier, specifierLen, 2738 CS.getStart(), CS.getLength()); 2739} 2740 2741bool CheckPrintfHandler::HandleAmount( 2742 const analyze_format_string::OptionalAmount &Amt, 2743 unsigned k, const char *startSpecifier, 2744 unsigned specifierLen) { 2745 2746 if (Amt.hasDataArgument()) { 2747 if (!HasVAListArg) { 2748 unsigned argIndex = Amt.getArgIndex(); 2749 if (argIndex >= NumDataArgs) { 2750 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2751 << k, 2752 getLocationOfByte(Amt.getStart()), 2753 /*IsStringLocation*/true, 2754 getSpecifierRange(startSpecifier, specifierLen)); 2755 // Don't do any more checking. We will just emit 2756 // spurious errors. 2757 return false; 2758 } 2759 2760 // Type check the data argument. It should be an 'int'. 2761 // Although not in conformance with C99, we also allow the argument to be 2762 // an 'unsigned int' as that is a reasonably safe case. GCC also 2763 // doesn't emit a warning for that case. 2764 CoveredArgs.set(argIndex); 2765 const Expr *Arg = getDataArg(argIndex); 2766 if (!Arg) 2767 return false; 2768 2769 QualType T = Arg->getType(); 2770 2771 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 2772 assert(AT.isValid()); 2773 2774 if (!AT.matchesType(S.Context, T)) { 2775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2776 << k << AT.getRepresentativeTypeName(S.Context) 2777 << T << Arg->getSourceRange(), 2778 getLocationOfByte(Amt.getStart()), 2779 /*IsStringLocation*/true, 2780 getSpecifierRange(startSpecifier, specifierLen)); 2781 // Don't do any more checking. We will just emit 2782 // spurious errors. 2783 return false; 2784 } 2785 } 2786 } 2787 return true; 2788} 2789 2790void CheckPrintfHandler::HandleInvalidAmount( 2791 const analyze_printf::PrintfSpecifier &FS, 2792 const analyze_printf::OptionalAmount &Amt, 2793 unsigned type, 2794 const char *startSpecifier, 2795 unsigned specifierLen) { 2796 const analyze_printf::PrintfConversionSpecifier &CS = 2797 FS.getConversionSpecifier(); 2798 2799 FixItHint fixit = 2800 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2801 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2802 Amt.getConstantLength())) 2803 : FixItHint(); 2804 2805 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2806 << type << CS.toString(), 2807 getLocationOfByte(Amt.getStart()), 2808 /*IsStringLocation*/true, 2809 getSpecifierRange(startSpecifier, specifierLen), 2810 fixit); 2811} 2812 2813void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2814 const analyze_printf::OptionalFlag &flag, 2815 const char *startSpecifier, 2816 unsigned specifierLen) { 2817 // Warn about pointless flag with a fixit removal. 2818 const analyze_printf::PrintfConversionSpecifier &CS = 2819 FS.getConversionSpecifier(); 2820 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2821 << flag.toString() << CS.toString(), 2822 getLocationOfByte(flag.getPosition()), 2823 /*IsStringLocation*/true, 2824 getSpecifierRange(startSpecifier, specifierLen), 2825 FixItHint::CreateRemoval( 2826 getSpecifierRange(flag.getPosition(), 1))); 2827} 2828 2829void CheckPrintfHandler::HandleIgnoredFlag( 2830 const analyze_printf::PrintfSpecifier &FS, 2831 const analyze_printf::OptionalFlag &ignoredFlag, 2832 const analyze_printf::OptionalFlag &flag, 2833 const char *startSpecifier, 2834 unsigned specifierLen) { 2835 // Warn about ignored flag with a fixit removal. 2836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2837 << ignoredFlag.toString() << flag.toString(), 2838 getLocationOfByte(ignoredFlag.getPosition()), 2839 /*IsStringLocation*/true, 2840 getSpecifierRange(startSpecifier, specifierLen), 2841 FixItHint::CreateRemoval( 2842 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2843} 2844 2845// Determines if the specified is a C++ class or struct containing 2846// a member with the specified name and kind (e.g. a CXXMethodDecl named 2847// "c_str()"). 2848template<typename MemberKind> 2849static llvm::SmallPtrSet<MemberKind*, 1> 2850CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 2851 const RecordType *RT = Ty->getAs<RecordType>(); 2852 llvm::SmallPtrSet<MemberKind*, 1> Results; 2853 2854 if (!RT) 2855 return Results; 2856 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2857 if (!RD) 2858 return Results; 2859 2860 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(), 2861 Sema::LookupMemberName); 2862 2863 // We just need to include all members of the right kind turned up by the 2864 // filter, at this point. 2865 if (S.LookupQualifiedName(R, RT->getDecl())) 2866 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2867 NamedDecl *decl = (*I)->getUnderlyingDecl(); 2868 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 2869 Results.insert(FK); 2870 } 2871 return Results; 2872} 2873 2874// Check if a (w)string was passed when a (w)char* was needed, and offer a 2875// better diagnostic if so. AT is assumed to be valid. 2876// Returns true when a c_str() conversion method is found. 2877bool CheckPrintfHandler::checkForCStrMembers( 2878 const analyze_printf::ArgType &AT, const Expr *E, 2879 const CharSourceRange &CSR) { 2880 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 2881 2882 MethodSet Results = 2883 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 2884 2885 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 2886 MI != ME; ++MI) { 2887 const CXXMethodDecl *Method = *MI; 2888 if (Method->getNumParams() == 0 && 2889 AT.matchesType(S.Context, Method->getResultType())) { 2890 // FIXME: Suggest parens if the expression needs them. 2891 SourceLocation EndLoc = 2892 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()); 2893 S.Diag(E->getLocStart(), diag::note_printf_c_str) 2894 << "c_str()" 2895 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 2896 return true; 2897 } 2898 } 2899 2900 return false; 2901} 2902 2903bool 2904CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2905 &FS, 2906 const char *startSpecifier, 2907 unsigned specifierLen) { 2908 2909 using namespace analyze_format_string; 2910 using namespace analyze_printf; 2911 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2912 2913 if (FS.consumesDataArgument()) { 2914 if (atFirstArg) { 2915 atFirstArg = false; 2916 usesPositionalArgs = FS.usesPositionalArg(); 2917 } 2918 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2919 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2920 startSpecifier, specifierLen); 2921 return false; 2922 } 2923 } 2924 2925 // First check if the field width, precision, and conversion specifier 2926 // have matching data arguments. 2927 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2928 startSpecifier, specifierLen)) { 2929 return false; 2930 } 2931 2932 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2933 startSpecifier, specifierLen)) { 2934 return false; 2935 } 2936 2937 if (!CS.consumesDataArgument()) { 2938 // FIXME: Technically specifying a precision or field width here 2939 // makes no sense. Worth issuing a warning at some point. 2940 return true; 2941 } 2942 2943 // Consume the argument. 2944 unsigned argIndex = FS.getArgIndex(); 2945 if (argIndex < NumDataArgs) { 2946 // The check to see if the argIndex is valid will come later. 2947 // We set the bit here because we may exit early from this 2948 // function if we encounter some other error. 2949 CoveredArgs.set(argIndex); 2950 } 2951 2952 // Check for using an Objective-C specific conversion specifier 2953 // in a non-ObjC literal. 2954 if (!ObjCContext && CS.isObjCArg()) { 2955 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2956 specifierLen); 2957 } 2958 2959 // Check for invalid use of field width 2960 if (!FS.hasValidFieldWidth()) { 2961 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2962 startSpecifier, specifierLen); 2963 } 2964 2965 // Check for invalid use of precision 2966 if (!FS.hasValidPrecision()) { 2967 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2968 startSpecifier, specifierLen); 2969 } 2970 2971 // Check each flag does not conflict with any other component. 2972 if (!FS.hasValidThousandsGroupingPrefix()) 2973 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2974 if (!FS.hasValidLeadingZeros()) 2975 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2976 if (!FS.hasValidPlusPrefix()) 2977 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2978 if (!FS.hasValidSpacePrefix()) 2979 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2980 if (!FS.hasValidAlternativeForm()) 2981 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2982 if (!FS.hasValidLeftJustified()) 2983 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2984 2985 // Check that flags are not ignored by another flag 2986 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2987 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2988 startSpecifier, specifierLen); 2989 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2990 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2991 startSpecifier, specifierLen); 2992 2993 // Check the length modifier is valid with the given conversion specifier. 2994 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 2995 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 2996 diag::warn_format_nonsensical_length); 2997 else if (!FS.hasStandardLengthModifier()) 2998 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 2999 else if (!FS.hasStandardLengthConversionCombination()) 3000 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3001 diag::warn_format_non_standard_conversion_spec); 3002 3003 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3004 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3005 3006 // The remaining checks depend on the data arguments. 3007 if (HasVAListArg) 3008 return true; 3009 3010 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3011 return false; 3012 3013 const Expr *Arg = getDataArg(argIndex); 3014 if (!Arg) 3015 return true; 3016 3017 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 3018} 3019 3020static bool requiresParensToAddCast(const Expr *E) { 3021 // FIXME: We should have a general way to reason about operator 3022 // precedence and whether parens are actually needed here. 3023 // Take care of a few common cases where they aren't. 3024 const Expr *Inside = E->IgnoreImpCasts(); 3025 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 3026 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 3027 3028 switch (Inside->getStmtClass()) { 3029 case Stmt::ArraySubscriptExprClass: 3030 case Stmt::CallExprClass: 3031 case Stmt::CharacterLiteralClass: 3032 case Stmt::CXXBoolLiteralExprClass: 3033 case Stmt::DeclRefExprClass: 3034 case Stmt::FloatingLiteralClass: 3035 case Stmt::IntegerLiteralClass: 3036 case Stmt::MemberExprClass: 3037 case Stmt::ObjCArrayLiteralClass: 3038 case Stmt::ObjCBoolLiteralExprClass: 3039 case Stmt::ObjCBoxedExprClass: 3040 case Stmt::ObjCDictionaryLiteralClass: 3041 case Stmt::ObjCEncodeExprClass: 3042 case Stmt::ObjCIvarRefExprClass: 3043 case Stmt::ObjCMessageExprClass: 3044 case Stmt::ObjCPropertyRefExprClass: 3045 case Stmt::ObjCStringLiteralClass: 3046 case Stmt::ObjCSubscriptRefExprClass: 3047 case Stmt::ParenExprClass: 3048 case Stmt::StringLiteralClass: 3049 case Stmt::UnaryOperatorClass: 3050 return false; 3051 default: 3052 return true; 3053 } 3054} 3055 3056bool 3057CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3058 const char *StartSpecifier, 3059 unsigned SpecifierLen, 3060 const Expr *E) { 3061 using namespace analyze_format_string; 3062 using namespace analyze_printf; 3063 // Now type check the data expression that matches the 3064 // format specifier. 3065 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 3066 ObjCContext); 3067 if (!AT.isValid()) 3068 return true; 3069 3070 QualType ExprTy = E->getType(); 3071 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 3072 ExprTy = TET->getUnderlyingExpr()->getType(); 3073 } 3074 3075 if (AT.matchesType(S.Context, ExprTy)) 3076 return true; 3077 3078 // Look through argument promotions for our error message's reported type. 3079 // This includes the integral and floating promotions, but excludes array 3080 // and function pointer decay; seeing that an argument intended to be a 3081 // string has type 'char [6]' is probably more confusing than 'char *'. 3082 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3083 if (ICE->getCastKind() == CK_IntegralCast || 3084 ICE->getCastKind() == CK_FloatingCast) { 3085 E = ICE->getSubExpr(); 3086 ExprTy = E->getType(); 3087 3088 // Check if we didn't match because of an implicit cast from a 'char' 3089 // or 'short' to an 'int'. This is done because printf is a varargs 3090 // function. 3091 if (ICE->getType() == S.Context.IntTy || 3092 ICE->getType() == S.Context.UnsignedIntTy) { 3093 // All further checking is done on the subexpression. 3094 if (AT.matchesType(S.Context, ExprTy)) 3095 return true; 3096 } 3097 } 3098 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 3099 // Special case for 'a', which has type 'int' in C. 3100 // Note, however, that we do /not/ want to treat multibyte constants like 3101 // 'MooV' as characters! This form is deprecated but still exists. 3102 if (ExprTy == S.Context.IntTy) 3103 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 3104 ExprTy = S.Context.CharTy; 3105 } 3106 3107 // %C in an Objective-C context prints a unichar, not a wchar_t. 3108 // If the argument is an integer of some kind, believe the %C and suggest 3109 // a cast instead of changing the conversion specifier. 3110 QualType IntendedTy = ExprTy; 3111 if (ObjCContext && 3112 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 3113 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 3114 !ExprTy->isCharType()) { 3115 // 'unichar' is defined as a typedef of unsigned short, but we should 3116 // prefer using the typedef if it is visible. 3117 IntendedTy = S.Context.UnsignedShortTy; 3118 3119 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 3120 Sema::LookupOrdinaryName); 3121 if (S.LookupName(Result, S.getCurScope())) { 3122 NamedDecl *ND = Result.getFoundDecl(); 3123 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 3124 if (TD->getUnderlyingType() == IntendedTy) 3125 IntendedTy = S.Context.getTypedefType(TD); 3126 } 3127 } 3128 } 3129 3130 // Special-case some of Darwin's platform-independence types by suggesting 3131 // casts to primitive types that are known to be large enough. 3132 bool ShouldNotPrintDirectly = false; 3133 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 3134 // Use a 'while' to peel off layers of typedefs. 3135 QualType TyTy = IntendedTy; 3136 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 3137 StringRef Name = UserTy->getDecl()->getName(); 3138 QualType CastTy = llvm::StringSwitch<QualType>(Name) 3139 .Case("NSInteger", S.Context.LongTy) 3140 .Case("NSUInteger", S.Context.UnsignedLongTy) 3141 .Case("SInt32", S.Context.IntTy) 3142 .Case("UInt32", S.Context.UnsignedIntTy) 3143 .Default(QualType()); 3144 3145 if (!CastTy.isNull()) { 3146 ShouldNotPrintDirectly = true; 3147 IntendedTy = CastTy; 3148 break; 3149 } 3150 TyTy = UserTy->desugar(); 3151 } 3152 } 3153 3154 // We may be able to offer a FixItHint if it is a supported type. 3155 PrintfSpecifier fixedFS = FS; 3156 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 3157 S.Context, ObjCContext); 3158 3159 if (success) { 3160 // Get the fix string from the fixed format specifier 3161 SmallString<16> buf; 3162 llvm::raw_svector_ostream os(buf); 3163 fixedFS.toString(os); 3164 3165 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 3166 3167 if (IntendedTy == ExprTy) { 3168 // In this case, the specifier is wrong and should be changed to match 3169 // the argument. 3170 EmitFormatDiagnostic( 3171 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3172 << AT.getRepresentativeTypeName(S.Context) << IntendedTy 3173 << E->getSourceRange(), 3174 E->getLocStart(), 3175 /*IsStringLocation*/false, 3176 SpecRange, 3177 FixItHint::CreateReplacement(SpecRange, os.str())); 3178 3179 } else { 3180 // The canonical type for formatting this value is different from the 3181 // actual type of the expression. (This occurs, for example, with Darwin's 3182 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 3183 // should be printed as 'long' for 64-bit compatibility.) 3184 // Rather than emitting a normal format/argument mismatch, we want to 3185 // add a cast to the recommended type (and correct the format string 3186 // if necessary). 3187 SmallString<16> CastBuf; 3188 llvm::raw_svector_ostream CastFix(CastBuf); 3189 CastFix << "("; 3190 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 3191 CastFix << ")"; 3192 3193 SmallVector<FixItHint,4> Hints; 3194 if (!AT.matchesType(S.Context, IntendedTy)) 3195 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 3196 3197 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 3198 // If there's already a cast present, just replace it. 3199 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 3200 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 3201 3202 } else if (!requiresParensToAddCast(E)) { 3203 // If the expression has high enough precedence, 3204 // just write the C-style cast. 3205 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3206 CastFix.str())); 3207 } else { 3208 // Otherwise, add parens around the expression as well as the cast. 3209 CastFix << "("; 3210 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3211 CastFix.str())); 3212 3213 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd()); 3214 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 3215 } 3216 3217 if (ShouldNotPrintDirectly) { 3218 // The expression has a type that should not be printed directly. 3219 // We extract the name from the typedef because we don't want to show 3220 // the underlying type in the diagnostic. 3221 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName(); 3222 3223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 3224 << Name << IntendedTy 3225 << E->getSourceRange(), 3226 E->getLocStart(), /*IsStringLocation=*/false, 3227 SpecRange, Hints); 3228 } else { 3229 // In this case, the expression could be printed using a different 3230 // specifier, but we've decided that the specifier is probably correct 3231 // and we should cast instead. Just use the normal warning message. 3232 EmitFormatDiagnostic( 3233 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3234 << AT.getRepresentativeTypeName(S.Context) << ExprTy 3235 << E->getSourceRange(), 3236 E->getLocStart(), /*IsStringLocation*/false, 3237 SpecRange, Hints); 3238 } 3239 } 3240 } else { 3241 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 3242 SpecifierLen); 3243 // Since the warning for passing non-POD types to variadic functions 3244 // was deferred until now, we emit a warning for non-POD 3245 // arguments here. 3246 switch (S.isValidVarArgType(ExprTy)) { 3247 case Sema::VAK_Valid: 3248 case Sema::VAK_ValidInCXX11: 3249 EmitFormatDiagnostic( 3250 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3251 << AT.getRepresentativeTypeName(S.Context) << ExprTy 3252 << CSR 3253 << E->getSourceRange(), 3254 E->getLocStart(), /*IsStringLocation*/false, CSR); 3255 break; 3256 3257 case Sema::VAK_Undefined: 3258 EmitFormatDiagnostic( 3259 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 3260 << S.getLangOpts().CPlusPlus11 3261 << ExprTy 3262 << CallType 3263 << AT.getRepresentativeTypeName(S.Context) 3264 << CSR 3265 << E->getSourceRange(), 3266 E->getLocStart(), /*IsStringLocation*/false, CSR); 3267 checkForCStrMembers(AT, E, CSR); 3268 break; 3269 3270 case Sema::VAK_Invalid: 3271 if (ExprTy->isObjCObjectType()) 3272 EmitFormatDiagnostic( 3273 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 3274 << S.getLangOpts().CPlusPlus11 3275 << ExprTy 3276 << CallType 3277 << AT.getRepresentativeTypeName(S.Context) 3278 << CSR 3279 << E->getSourceRange(), 3280 E->getLocStart(), /*IsStringLocation*/false, CSR); 3281 else 3282 // FIXME: If this is an initializer list, suggest removing the braces 3283 // or inserting a cast to the target type. 3284 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 3285 << isa<InitListExpr>(E) << ExprTy << CallType 3286 << AT.getRepresentativeTypeName(S.Context) 3287 << E->getSourceRange(); 3288 break; 3289 } 3290 3291 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 3292 "format string specifier index out of range"); 3293 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 3294 } 3295 3296 return true; 3297} 3298 3299//===--- CHECK: Scanf format string checking ------------------------------===// 3300 3301namespace { 3302class CheckScanfHandler : public CheckFormatHandler { 3303public: 3304 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 3305 const Expr *origFormatExpr, unsigned firstDataArg, 3306 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3307 ArrayRef<const Expr *> Args, 3308 unsigned formatIdx, bool inFunctionCall, 3309 Sema::VariadicCallType CallType, 3310 llvm::SmallBitVector &CheckedVarArgs) 3311 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3312 numDataArgs, beg, hasVAListArg, 3313 Args, formatIdx, inFunctionCall, CallType, 3314 CheckedVarArgs) 3315 {} 3316 3317 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 3318 const char *startSpecifier, 3319 unsigned specifierLen); 3320 3321 bool HandleInvalidScanfConversionSpecifier( 3322 const analyze_scanf::ScanfSpecifier &FS, 3323 const char *startSpecifier, 3324 unsigned specifierLen); 3325 3326 void HandleIncompleteScanList(const char *start, const char *end); 3327}; 3328} 3329 3330void CheckScanfHandler::HandleIncompleteScanList(const char *start, 3331 const char *end) { 3332 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 3333 getLocationOfByte(end), /*IsStringLocation*/true, 3334 getSpecifierRange(start, end - start)); 3335} 3336 3337bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 3338 const analyze_scanf::ScanfSpecifier &FS, 3339 const char *startSpecifier, 3340 unsigned specifierLen) { 3341 3342 const analyze_scanf::ScanfConversionSpecifier &CS = 3343 FS.getConversionSpecifier(); 3344 3345 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3346 getLocationOfByte(CS.getStart()), 3347 startSpecifier, specifierLen, 3348 CS.getStart(), CS.getLength()); 3349} 3350 3351bool CheckScanfHandler::HandleScanfSpecifier( 3352 const analyze_scanf::ScanfSpecifier &FS, 3353 const char *startSpecifier, 3354 unsigned specifierLen) { 3355 3356 using namespace analyze_scanf; 3357 using namespace analyze_format_string; 3358 3359 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 3360 3361 // Handle case where '%' and '*' don't consume an argument. These shouldn't 3362 // be used to decide if we are using positional arguments consistently. 3363 if (FS.consumesDataArgument()) { 3364 if (atFirstArg) { 3365 atFirstArg = false; 3366 usesPositionalArgs = FS.usesPositionalArg(); 3367 } 3368 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3369 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3370 startSpecifier, specifierLen); 3371 return false; 3372 } 3373 } 3374 3375 // Check if the field with is non-zero. 3376 const OptionalAmount &Amt = FS.getFieldWidth(); 3377 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 3378 if (Amt.getConstantAmount() == 0) { 3379 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 3380 Amt.getConstantLength()); 3381 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 3382 getLocationOfByte(Amt.getStart()), 3383 /*IsStringLocation*/true, R, 3384 FixItHint::CreateRemoval(R)); 3385 } 3386 } 3387 3388 if (!FS.consumesDataArgument()) { 3389 // FIXME: Technically specifying a precision or field width here 3390 // makes no sense. Worth issuing a warning at some point. 3391 return true; 3392 } 3393 3394 // Consume the argument. 3395 unsigned argIndex = FS.getArgIndex(); 3396 if (argIndex < NumDataArgs) { 3397 // The check to see if the argIndex is valid will come later. 3398 // We set the bit here because we may exit early from this 3399 // function if we encounter some other error. 3400 CoveredArgs.set(argIndex); 3401 } 3402 3403 // Check the length modifier is valid with the given conversion specifier. 3404 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3405 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3406 diag::warn_format_nonsensical_length); 3407 else if (!FS.hasStandardLengthModifier()) 3408 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3409 else if (!FS.hasStandardLengthConversionCombination()) 3410 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3411 diag::warn_format_non_standard_conversion_spec); 3412 3413 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3414 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3415 3416 // The remaining checks depend on the data arguments. 3417 if (HasVAListArg) 3418 return true; 3419 3420 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3421 return false; 3422 3423 // Check that the argument type matches the format specifier. 3424 const Expr *Ex = getDataArg(argIndex); 3425 if (!Ex) 3426 return true; 3427 3428 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 3429 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 3430 ScanfSpecifier fixedFS = FS; 3431 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 3432 S.Context); 3433 3434 if (success) { 3435 // Get the fix string from the fixed format specifier. 3436 SmallString<128> buf; 3437 llvm::raw_svector_ostream os(buf); 3438 fixedFS.toString(os); 3439 3440 EmitFormatDiagnostic( 3441 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3442 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3443 << Ex->getSourceRange(), 3444 Ex->getLocStart(), 3445 /*IsStringLocation*/false, 3446 getSpecifierRange(startSpecifier, specifierLen), 3447 FixItHint::CreateReplacement( 3448 getSpecifierRange(startSpecifier, specifierLen), 3449 os.str())); 3450 } else { 3451 EmitFormatDiagnostic( 3452 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3453 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3454 << Ex->getSourceRange(), 3455 Ex->getLocStart(), 3456 /*IsStringLocation*/false, 3457 getSpecifierRange(startSpecifier, specifierLen)); 3458 } 3459 } 3460 3461 return true; 3462} 3463 3464void Sema::CheckFormatString(const StringLiteral *FExpr, 3465 const Expr *OrigFormatExpr, 3466 ArrayRef<const Expr *> Args, 3467 bool HasVAListArg, unsigned format_idx, 3468 unsigned firstDataArg, FormatStringType Type, 3469 bool inFunctionCall, VariadicCallType CallType, 3470 llvm::SmallBitVector &CheckedVarArgs) { 3471 3472 // CHECK: is the format string a wide literal? 3473 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 3474 CheckFormatHandler::EmitFormatDiagnostic( 3475 *this, inFunctionCall, Args[format_idx], 3476 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 3477 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3478 return; 3479 } 3480 3481 // Str - The format string. NOTE: this is NOT null-terminated! 3482 StringRef StrRef = FExpr->getString(); 3483 const char *Str = StrRef.data(); 3484 unsigned StrLen = StrRef.size(); 3485 const unsigned numDataArgs = Args.size() - firstDataArg; 3486 3487 // CHECK: empty format string? 3488 if (StrLen == 0 && numDataArgs > 0) { 3489 CheckFormatHandler::EmitFormatDiagnostic( 3490 *this, inFunctionCall, Args[format_idx], 3491 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 3492 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3493 return; 3494 } 3495 3496 if (Type == FST_Printf || Type == FST_NSString) { 3497 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 3498 numDataArgs, (Type == FST_NSString), 3499 Str, HasVAListArg, Args, format_idx, 3500 inFunctionCall, CallType, CheckedVarArgs); 3501 3502 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 3503 getLangOpts(), 3504 Context.getTargetInfo())) 3505 H.DoneProcessing(); 3506 } else if (Type == FST_Scanf) { 3507 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 3508 Str, HasVAListArg, Args, format_idx, 3509 inFunctionCall, CallType, CheckedVarArgs); 3510 3511 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 3512 getLangOpts(), 3513 Context.getTargetInfo())) 3514 H.DoneProcessing(); 3515 } // TODO: handle other formats 3516} 3517 3518//===--- CHECK: Standard memory functions ---------------------------------===// 3519 3520/// \brief Determine whether the given type is a dynamic class type (e.g., 3521/// whether it has a vtable). 3522static bool isDynamicClassType(QualType T) { 3523 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3524 if (CXXRecordDecl *Definition = Record->getDefinition()) 3525 if (Definition->isDynamicClass()) 3526 return true; 3527 3528 return false; 3529} 3530 3531/// \brief If E is a sizeof expression, returns its argument expression, 3532/// otherwise returns NULL. 3533static const Expr *getSizeOfExprArg(const Expr* E) { 3534 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3535 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3536 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 3537 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 3538 3539 return 0; 3540} 3541 3542/// \brief If E is a sizeof expression, returns its argument type. 3543static QualType getSizeOfArgType(const Expr* E) { 3544 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3545 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3546 if (SizeOf->getKind() == clang::UETT_SizeOf) 3547 return SizeOf->getTypeOfArgument(); 3548 3549 return QualType(); 3550} 3551 3552/// \brief Check for dangerous or invalid arguments to memset(). 3553/// 3554/// This issues warnings on known problematic, dangerous or unspecified 3555/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 3556/// function calls. 3557/// 3558/// \param Call The call expression to diagnose. 3559void Sema::CheckMemaccessArguments(const CallExpr *Call, 3560 unsigned BId, 3561 IdentifierInfo *FnName) { 3562 assert(BId != 0); 3563 3564 // It is possible to have a non-standard definition of memset. Validate 3565 // we have enough arguments, and if not, abort further checking. 3566 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 3567 if (Call->getNumArgs() < ExpectedNumArgs) 3568 return; 3569 3570 unsigned LastArg = (BId == Builtin::BImemset || 3571 BId == Builtin::BIstrndup ? 1 : 2); 3572 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 3573 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 3574 3575 // We have special checking when the length is a sizeof expression. 3576 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 3577 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 3578 llvm::FoldingSetNodeID SizeOfArgID; 3579 3580 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 3581 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 3582 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 3583 3584 QualType DestTy = Dest->getType(); 3585 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 3586 QualType PointeeTy = DestPtrTy->getPointeeType(); 3587 3588 // Never warn about void type pointers. This can be used to suppress 3589 // false positives. 3590 if (PointeeTy->isVoidType()) 3591 continue; 3592 3593 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 3594 // actually comparing the expressions for equality. Because computing the 3595 // expression IDs can be expensive, we only do this if the diagnostic is 3596 // enabled. 3597 if (SizeOfArg && 3598 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 3599 SizeOfArg->getExprLoc())) { 3600 // We only compute IDs for expressions if the warning is enabled, and 3601 // cache the sizeof arg's ID. 3602 if (SizeOfArgID == llvm::FoldingSetNodeID()) 3603 SizeOfArg->Profile(SizeOfArgID, Context, true); 3604 llvm::FoldingSetNodeID DestID; 3605 Dest->Profile(DestID, Context, true); 3606 if (DestID == SizeOfArgID) { 3607 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 3608 // over sizeof(src) as well. 3609 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 3610 StringRef ReadableName = FnName->getName(); 3611 3612 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 3613 if (UnaryOp->getOpcode() == UO_AddrOf) 3614 ActionIdx = 1; // If its an address-of operator, just remove it. 3615 if (!PointeeTy->isIncompleteType() && 3616 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 3617 ActionIdx = 2; // If the pointee's size is sizeof(char), 3618 // suggest an explicit length. 3619 3620 // If the function is defined as a builtin macro, do not show macro 3621 // expansion. 3622 SourceLocation SL = SizeOfArg->getExprLoc(); 3623 SourceRange DSR = Dest->getSourceRange(); 3624 SourceRange SSR = SizeOfArg->getSourceRange(); 3625 SourceManager &SM = PP.getSourceManager(); 3626 3627 if (SM.isMacroArgExpansion(SL)) { 3628 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 3629 SL = SM.getSpellingLoc(SL); 3630 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 3631 SM.getSpellingLoc(DSR.getEnd())); 3632 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 3633 SM.getSpellingLoc(SSR.getEnd())); 3634 } 3635 3636 DiagRuntimeBehavior(SL, SizeOfArg, 3637 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 3638 << ReadableName 3639 << PointeeTy 3640 << DestTy 3641 << DSR 3642 << SSR); 3643 DiagRuntimeBehavior(SL, SizeOfArg, 3644 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 3645 << ActionIdx 3646 << SSR); 3647 3648 break; 3649 } 3650 } 3651 3652 // Also check for cases where the sizeof argument is the exact same 3653 // type as the memory argument, and where it points to a user-defined 3654 // record type. 3655 if (SizeOfArgTy != QualType()) { 3656 if (PointeeTy->isRecordType() && 3657 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 3658 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 3659 PDiag(diag::warn_sizeof_pointer_type_memaccess) 3660 << FnName << SizeOfArgTy << ArgIdx 3661 << PointeeTy << Dest->getSourceRange() 3662 << LenExpr->getSourceRange()); 3663 break; 3664 } 3665 } 3666 3667 // Always complain about dynamic classes. 3668 if (isDynamicClassType(PointeeTy)) { 3669 3670 unsigned OperationType = 0; 3671 // "overwritten" if we're warning about the destination for any call 3672 // but memcmp; otherwise a verb appropriate to the call. 3673 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 3674 if (BId == Builtin::BImemcpy) 3675 OperationType = 1; 3676 else if(BId == Builtin::BImemmove) 3677 OperationType = 2; 3678 else if (BId == Builtin::BImemcmp) 3679 OperationType = 3; 3680 } 3681 3682 DiagRuntimeBehavior( 3683 Dest->getExprLoc(), Dest, 3684 PDiag(diag::warn_dyn_class_memaccess) 3685 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 3686 << FnName << PointeeTy 3687 << OperationType 3688 << Call->getCallee()->getSourceRange()); 3689 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 3690 BId != Builtin::BImemset) 3691 DiagRuntimeBehavior( 3692 Dest->getExprLoc(), Dest, 3693 PDiag(diag::warn_arc_object_memaccess) 3694 << ArgIdx << FnName << PointeeTy 3695 << Call->getCallee()->getSourceRange()); 3696 else 3697 continue; 3698 3699 DiagRuntimeBehavior( 3700 Dest->getExprLoc(), Dest, 3701 PDiag(diag::note_bad_memaccess_silence) 3702 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 3703 break; 3704 } 3705 } 3706} 3707 3708// A little helper routine: ignore addition and subtraction of integer literals. 3709// This intentionally does not ignore all integer constant expressions because 3710// we don't want to remove sizeof(). 3711static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 3712 Ex = Ex->IgnoreParenCasts(); 3713 3714 for (;;) { 3715 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 3716 if (!BO || !BO->isAdditiveOp()) 3717 break; 3718 3719 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 3720 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 3721 3722 if (isa<IntegerLiteral>(RHS)) 3723 Ex = LHS; 3724 else if (isa<IntegerLiteral>(LHS)) 3725 Ex = RHS; 3726 else 3727 break; 3728 } 3729 3730 return Ex; 3731} 3732 3733static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 3734 ASTContext &Context) { 3735 // Only handle constant-sized or VLAs, but not flexible members. 3736 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 3737 // Only issue the FIXIT for arrays of size > 1. 3738 if (CAT->getSize().getSExtValue() <= 1) 3739 return false; 3740 } else if (!Ty->isVariableArrayType()) { 3741 return false; 3742 } 3743 return true; 3744} 3745 3746// Warn if the user has made the 'size' argument to strlcpy or strlcat 3747// be the size of the source, instead of the destination. 3748void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 3749 IdentifierInfo *FnName) { 3750 3751 // Don't crash if the user has the wrong number of arguments 3752 if (Call->getNumArgs() != 3) 3753 return; 3754 3755 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 3756 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 3757 const Expr *CompareWithSrc = NULL; 3758 3759 // Look for 'strlcpy(dst, x, sizeof(x))' 3760 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 3761 CompareWithSrc = Ex; 3762 else { 3763 // Look for 'strlcpy(dst, x, strlen(x))' 3764 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 3765 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 3766 && SizeCall->getNumArgs() == 1) 3767 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 3768 } 3769 } 3770 3771 if (!CompareWithSrc) 3772 return; 3773 3774 // Determine if the argument to sizeof/strlen is equal to the source 3775 // argument. In principle there's all kinds of things you could do 3776 // here, for instance creating an == expression and evaluating it with 3777 // EvaluateAsBooleanCondition, but this uses a more direct technique: 3778 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 3779 if (!SrcArgDRE) 3780 return; 3781 3782 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 3783 if (!CompareWithSrcDRE || 3784 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 3785 return; 3786 3787 const Expr *OriginalSizeArg = Call->getArg(2); 3788 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 3789 << OriginalSizeArg->getSourceRange() << FnName; 3790 3791 // Output a FIXIT hint if the destination is an array (rather than a 3792 // pointer to an array). This could be enhanced to handle some 3793 // pointers if we know the actual size, like if DstArg is 'array+2' 3794 // we could say 'sizeof(array)-2'. 3795 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 3796 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 3797 return; 3798 3799 SmallString<128> sizeString; 3800 llvm::raw_svector_ostream OS(sizeString); 3801 OS << "sizeof("; 3802 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3803 OS << ")"; 3804 3805 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 3806 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 3807 OS.str()); 3808} 3809 3810/// Check if two expressions refer to the same declaration. 3811static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 3812 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 3813 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 3814 return D1->getDecl() == D2->getDecl(); 3815 return false; 3816} 3817 3818static const Expr *getStrlenExprArg(const Expr *E) { 3819 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 3820 const FunctionDecl *FD = CE->getDirectCallee(); 3821 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 3822 return 0; 3823 return CE->getArg(0)->IgnoreParenCasts(); 3824 } 3825 return 0; 3826} 3827 3828// Warn on anti-patterns as the 'size' argument to strncat. 3829// The correct size argument should look like following: 3830// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 3831void Sema::CheckStrncatArguments(const CallExpr *CE, 3832 IdentifierInfo *FnName) { 3833 // Don't crash if the user has the wrong number of arguments. 3834 if (CE->getNumArgs() < 3) 3835 return; 3836 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 3837 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 3838 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 3839 3840 // Identify common expressions, which are wrongly used as the size argument 3841 // to strncat and may lead to buffer overflows. 3842 unsigned PatternType = 0; 3843 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 3844 // - sizeof(dst) 3845 if (referToTheSameDecl(SizeOfArg, DstArg)) 3846 PatternType = 1; 3847 // - sizeof(src) 3848 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 3849 PatternType = 2; 3850 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 3851 if (BE->getOpcode() == BO_Sub) { 3852 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3853 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3854 // - sizeof(dst) - strlen(dst) 3855 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3856 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3857 PatternType = 1; 3858 // - sizeof(src) - (anything) 3859 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3860 PatternType = 2; 3861 } 3862 } 3863 3864 if (PatternType == 0) 3865 return; 3866 3867 // Generate the diagnostic. 3868 SourceLocation SL = LenArg->getLocStart(); 3869 SourceRange SR = LenArg->getSourceRange(); 3870 SourceManager &SM = PP.getSourceManager(); 3871 3872 // If the function is defined as a builtin macro, do not show macro expansion. 3873 if (SM.isMacroArgExpansion(SL)) { 3874 SL = SM.getSpellingLoc(SL); 3875 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3876 SM.getSpellingLoc(SR.getEnd())); 3877 } 3878 3879 // Check if the destination is an array (rather than a pointer to an array). 3880 QualType DstTy = DstArg->getType(); 3881 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 3882 Context); 3883 if (!isKnownSizeArray) { 3884 if (PatternType == 1) 3885 Diag(SL, diag::warn_strncat_wrong_size) << SR; 3886 else 3887 Diag(SL, diag::warn_strncat_src_size) << SR; 3888 return; 3889 } 3890 3891 if (PatternType == 1) 3892 Diag(SL, diag::warn_strncat_large_size) << SR; 3893 else 3894 Diag(SL, diag::warn_strncat_src_size) << SR; 3895 3896 SmallString<128> sizeString; 3897 llvm::raw_svector_ostream OS(sizeString); 3898 OS << "sizeof("; 3899 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3900 OS << ") - "; 3901 OS << "strlen("; 3902 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3903 OS << ") - 1"; 3904 3905 Diag(SL, diag::note_strncat_wrong_size) 3906 << FixItHint::CreateReplacement(SR, OS.str()); 3907} 3908 3909//===--- CHECK: Return Address of Stack Variable --------------------------===// 3910 3911static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3912 Decl *ParentDecl); 3913static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3914 Decl *ParentDecl); 3915 3916/// CheckReturnStackAddr - Check if a return statement returns the address 3917/// of a stack variable. 3918void 3919Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3920 SourceLocation ReturnLoc) { 3921 3922 Expr *stackE = 0; 3923 SmallVector<DeclRefExpr *, 8> refVars; 3924 3925 // Perform checking for returned stack addresses, local blocks, 3926 // label addresses or references to temporaries. 3927 if (lhsType->isPointerType() || 3928 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3929 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3930 } else if (lhsType->isReferenceType()) { 3931 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3932 } 3933 3934 if (stackE == 0) 3935 return; // Nothing suspicious was found. 3936 3937 SourceLocation diagLoc; 3938 SourceRange diagRange; 3939 if (refVars.empty()) { 3940 diagLoc = stackE->getLocStart(); 3941 diagRange = stackE->getSourceRange(); 3942 } else { 3943 // We followed through a reference variable. 'stackE' contains the 3944 // problematic expression but we will warn at the return statement pointing 3945 // at the reference variable. We will later display the "trail" of 3946 // reference variables using notes. 3947 diagLoc = refVars[0]->getLocStart(); 3948 diagRange = refVars[0]->getSourceRange(); 3949 } 3950 3951 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3952 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3953 : diag::warn_ret_stack_addr) 3954 << DR->getDecl()->getDeclName() << diagRange; 3955 } else if (isa<BlockExpr>(stackE)) { // local block. 3956 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3957 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3958 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3959 } else { // local temporary. 3960 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3961 : diag::warn_ret_local_temp_addr) 3962 << diagRange; 3963 } 3964 3965 // Display the "trail" of reference variables that we followed until we 3966 // found the problematic expression using notes. 3967 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3968 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3969 // If this var binds to another reference var, show the range of the next 3970 // var, otherwise the var binds to the problematic expression, in which case 3971 // show the range of the expression. 3972 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3973 : stackE->getSourceRange(); 3974 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3975 << VD->getDeclName() << range; 3976 } 3977} 3978 3979/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3980/// check if the expression in a return statement evaluates to an address 3981/// to a location on the stack, a local block, an address of a label, or a 3982/// reference to local temporary. The recursion is used to traverse the 3983/// AST of the return expression, with recursion backtracking when we 3984/// encounter a subexpression that (1) clearly does not lead to one of the 3985/// above problematic expressions (2) is something we cannot determine leads to 3986/// a problematic expression based on such local checking. 3987/// 3988/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3989/// the expression that they point to. Such variables are added to the 3990/// 'refVars' vector so that we know what the reference variable "trail" was. 3991/// 3992/// EvalAddr processes expressions that are pointers that are used as 3993/// references (and not L-values). EvalVal handles all other values. 3994/// At the base case of the recursion is a check for the above problematic 3995/// expressions. 3996/// 3997/// This implementation handles: 3998/// 3999/// * pointer-to-pointer casts 4000/// * implicit conversions from array references to pointers 4001/// * taking the address of fields 4002/// * arbitrary interplay between "&" and "*" operators 4003/// * pointer arithmetic from an address of a stack variable 4004/// * taking the address of an array element where the array is on the stack 4005static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4006 Decl *ParentDecl) { 4007 if (E->isTypeDependent()) 4008 return NULL; 4009 4010 // We should only be called for evaluating pointer expressions. 4011 assert((E->getType()->isAnyPointerType() || 4012 E->getType()->isBlockPointerType() || 4013 E->getType()->isObjCQualifiedIdType()) && 4014 "EvalAddr only works on pointers"); 4015 4016 E = E->IgnoreParens(); 4017 4018 // Our "symbolic interpreter" is just a dispatch off the currently 4019 // viewed AST node. We then recursively traverse the AST by calling 4020 // EvalAddr and EvalVal appropriately. 4021 switch (E->getStmtClass()) { 4022 case Stmt::DeclRefExprClass: { 4023 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4024 4025 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 4026 // If this is a reference variable, follow through to the expression that 4027 // it points to. 4028 if (V->hasLocalStorage() && 4029 V->getType()->isReferenceType() && V->hasInit()) { 4030 // Add the reference variable to the "trail". 4031 refVars.push_back(DR); 4032 return EvalAddr(V->getInit(), refVars, ParentDecl); 4033 } 4034 4035 return NULL; 4036 } 4037 4038 case Stmt::UnaryOperatorClass: { 4039 // The only unary operator that make sense to handle here 4040 // is AddrOf. All others don't make sense as pointers. 4041 UnaryOperator *U = cast<UnaryOperator>(E); 4042 4043 if (U->getOpcode() == UO_AddrOf) 4044 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 4045 else 4046 return NULL; 4047 } 4048 4049 case Stmt::BinaryOperatorClass: { 4050 // Handle pointer arithmetic. All other binary operators are not valid 4051 // in this context. 4052 BinaryOperator *B = cast<BinaryOperator>(E); 4053 BinaryOperatorKind op = B->getOpcode(); 4054 4055 if (op != BO_Add && op != BO_Sub) 4056 return NULL; 4057 4058 Expr *Base = B->getLHS(); 4059 4060 // Determine which argument is the real pointer base. It could be 4061 // the RHS argument instead of the LHS. 4062 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 4063 4064 assert (Base->getType()->isPointerType()); 4065 return EvalAddr(Base, refVars, ParentDecl); 4066 } 4067 4068 // For conditional operators we need to see if either the LHS or RHS are 4069 // valid DeclRefExpr*s. If one of them is valid, we return it. 4070 case Stmt::ConditionalOperatorClass: { 4071 ConditionalOperator *C = cast<ConditionalOperator>(E); 4072 4073 // Handle the GNU extension for missing LHS. 4074 if (Expr *lhsExpr = C->getLHS()) { 4075 // In C++, we can have a throw-expression, which has 'void' type. 4076 if (!lhsExpr->getType()->isVoidType()) 4077 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 4078 return LHS; 4079 } 4080 4081 // In C++, we can have a throw-expression, which has 'void' type. 4082 if (C->getRHS()->getType()->isVoidType()) 4083 return NULL; 4084 4085 return EvalAddr(C->getRHS(), refVars, ParentDecl); 4086 } 4087 4088 case Stmt::BlockExprClass: 4089 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 4090 return E; // local block. 4091 return NULL; 4092 4093 case Stmt::AddrLabelExprClass: 4094 return E; // address of label. 4095 4096 case Stmt::ExprWithCleanupsClass: 4097 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 4098 ParentDecl); 4099 4100 // For casts, we need to handle conversions from arrays to 4101 // pointer values, and pointer-to-pointer conversions. 4102 case Stmt::ImplicitCastExprClass: 4103 case Stmt::CStyleCastExprClass: 4104 case Stmt::CXXFunctionalCastExprClass: 4105 case Stmt::ObjCBridgedCastExprClass: 4106 case Stmt::CXXStaticCastExprClass: 4107 case Stmt::CXXDynamicCastExprClass: 4108 case Stmt::CXXConstCastExprClass: 4109 case Stmt::CXXReinterpretCastExprClass: { 4110 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 4111 switch (cast<CastExpr>(E)->getCastKind()) { 4112 case CK_BitCast: 4113 case CK_LValueToRValue: 4114 case CK_NoOp: 4115 case CK_BaseToDerived: 4116 case CK_DerivedToBase: 4117 case CK_UncheckedDerivedToBase: 4118 case CK_Dynamic: 4119 case CK_CPointerToObjCPointerCast: 4120 case CK_BlockPointerToObjCPointerCast: 4121 case CK_AnyPointerToBlockPointerCast: 4122 return EvalAddr(SubExpr, refVars, ParentDecl); 4123 4124 case CK_ArrayToPointerDecay: 4125 return EvalVal(SubExpr, refVars, ParentDecl); 4126 4127 default: 4128 return 0; 4129 } 4130 } 4131 4132 case Stmt::MaterializeTemporaryExprClass: 4133 if (Expr *Result = EvalAddr( 4134 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4135 refVars, ParentDecl)) 4136 return Result; 4137 4138 return E; 4139 4140 // Everything else: we simply don't reason about them. 4141 default: 4142 return NULL; 4143 } 4144} 4145 4146 4147/// EvalVal - This function is complements EvalAddr in the mutual recursion. 4148/// See the comments for EvalAddr for more details. 4149static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4150 Decl *ParentDecl) { 4151do { 4152 // We should only be called for evaluating non-pointer expressions, or 4153 // expressions with a pointer type that are not used as references but instead 4154 // are l-values (e.g., DeclRefExpr with a pointer type). 4155 4156 // Our "symbolic interpreter" is just a dispatch off the currently 4157 // viewed AST node. We then recursively traverse the AST by calling 4158 // EvalAddr and EvalVal appropriately. 4159 4160 E = E->IgnoreParens(); 4161 switch (E->getStmtClass()) { 4162 case Stmt::ImplicitCastExprClass: { 4163 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 4164 if (IE->getValueKind() == VK_LValue) { 4165 E = IE->getSubExpr(); 4166 continue; 4167 } 4168 return NULL; 4169 } 4170 4171 case Stmt::ExprWithCleanupsClass: 4172 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 4173 4174 case Stmt::DeclRefExprClass: { 4175 // When we hit a DeclRefExpr we are looking at code that refers to a 4176 // variable's name. If it's not a reference variable we check if it has 4177 // local storage within the function, and if so, return the expression. 4178 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4179 4180 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 4181 // Check if it refers to itself, e.g. "int& i = i;". 4182 if (V == ParentDecl) 4183 return DR; 4184 4185 if (V->hasLocalStorage()) { 4186 if (!V->getType()->isReferenceType()) 4187 return DR; 4188 4189 // Reference variable, follow through to the expression that 4190 // it points to. 4191 if (V->hasInit()) { 4192 // Add the reference variable to the "trail". 4193 refVars.push_back(DR); 4194 return EvalVal(V->getInit(), refVars, V); 4195 } 4196 } 4197 } 4198 4199 return NULL; 4200 } 4201 4202 case Stmt::UnaryOperatorClass: { 4203 // The only unary operator that make sense to handle here 4204 // is Deref. All others don't resolve to a "name." This includes 4205 // handling all sorts of rvalues passed to a unary operator. 4206 UnaryOperator *U = cast<UnaryOperator>(E); 4207 4208 if (U->getOpcode() == UO_Deref) 4209 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 4210 4211 return NULL; 4212 } 4213 4214 case Stmt::ArraySubscriptExprClass: { 4215 // Array subscripts are potential references to data on the stack. We 4216 // retrieve the DeclRefExpr* for the array variable if it indeed 4217 // has local storage. 4218 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 4219 } 4220 4221 case Stmt::ConditionalOperatorClass: { 4222 // For conditional operators we need to see if either the LHS or RHS are 4223 // non-NULL Expr's. If one is non-NULL, we return it. 4224 ConditionalOperator *C = cast<ConditionalOperator>(E); 4225 4226 // Handle the GNU extension for missing LHS. 4227 if (Expr *lhsExpr = C->getLHS()) 4228 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 4229 return LHS; 4230 4231 return EvalVal(C->getRHS(), refVars, ParentDecl); 4232 } 4233 4234 // Accesses to members are potential references to data on the stack. 4235 case Stmt::MemberExprClass: { 4236 MemberExpr *M = cast<MemberExpr>(E); 4237 4238 // Check for indirect access. We only want direct field accesses. 4239 if (M->isArrow()) 4240 return NULL; 4241 4242 // Check whether the member type is itself a reference, in which case 4243 // we're not going to refer to the member, but to what the member refers to. 4244 if (M->getMemberDecl()->getType()->isReferenceType()) 4245 return NULL; 4246 4247 return EvalVal(M->getBase(), refVars, ParentDecl); 4248 } 4249 4250 case Stmt::MaterializeTemporaryExprClass: 4251 if (Expr *Result = EvalVal( 4252 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4253 refVars, ParentDecl)) 4254 return Result; 4255 4256 return E; 4257 4258 default: 4259 // Check that we don't return or take the address of a reference to a 4260 // temporary. This is only useful in C++. 4261 if (!E->isTypeDependent() && E->isRValue()) 4262 return E; 4263 4264 // Everything else: we simply don't reason about them. 4265 return NULL; 4266 } 4267} while (true); 4268} 4269 4270//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 4271 4272/// Check for comparisons of floating point operands using != and ==. 4273/// Issue a warning if these are no self-comparisons, as they are not likely 4274/// to do what the programmer intended. 4275void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 4276 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 4277 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 4278 4279 // Special case: check for x == x (which is OK). 4280 // Do not emit warnings for such cases. 4281 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 4282 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 4283 if (DRL->getDecl() == DRR->getDecl()) 4284 return; 4285 4286 4287 // Special case: check for comparisons against literals that can be exactly 4288 // represented by APFloat. In such cases, do not emit a warning. This 4289 // is a heuristic: often comparison against such literals are used to 4290 // detect if a value in a variable has not changed. This clearly can 4291 // lead to false negatives. 4292 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 4293 if (FLL->isExact()) 4294 return; 4295 } else 4296 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 4297 if (FLR->isExact()) 4298 return; 4299 4300 // Check for comparisons with builtin types. 4301 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 4302 if (CL->isBuiltinCall()) 4303 return; 4304 4305 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 4306 if (CR->isBuiltinCall()) 4307 return; 4308 4309 // Emit the diagnostic. 4310 Diag(Loc, diag::warn_floatingpoint_eq) 4311 << LHS->getSourceRange() << RHS->getSourceRange(); 4312} 4313 4314//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 4315//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 4316 4317namespace { 4318 4319/// Structure recording the 'active' range of an integer-valued 4320/// expression. 4321struct IntRange { 4322 /// The number of bits active in the int. 4323 unsigned Width; 4324 4325 /// True if the int is known not to have negative values. 4326 bool NonNegative; 4327 4328 IntRange(unsigned Width, bool NonNegative) 4329 : Width(Width), NonNegative(NonNegative) 4330 {} 4331 4332 /// Returns the range of the bool type. 4333 static IntRange forBoolType() { 4334 return IntRange(1, true); 4335 } 4336 4337 /// Returns the range of an opaque value of the given integral type. 4338 static IntRange forValueOfType(ASTContext &C, QualType T) { 4339 return forValueOfCanonicalType(C, 4340 T->getCanonicalTypeInternal().getTypePtr()); 4341 } 4342 4343 /// Returns the range of an opaque value of a canonical integral type. 4344 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 4345 assert(T->isCanonicalUnqualified()); 4346 4347 if (const VectorType *VT = dyn_cast<VectorType>(T)) 4348 T = VT->getElementType().getTypePtr(); 4349 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 4350 T = CT->getElementType().getTypePtr(); 4351 4352 // For enum types, use the known bit width of the enumerators. 4353 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 4354 EnumDecl *Enum = ET->getDecl(); 4355 if (!Enum->isCompleteDefinition()) 4356 return IntRange(C.getIntWidth(QualType(T, 0)), false); 4357 4358 unsigned NumPositive = Enum->getNumPositiveBits(); 4359 unsigned NumNegative = Enum->getNumNegativeBits(); 4360 4361 if (NumNegative == 0) 4362 return IntRange(NumPositive, true/*NonNegative*/); 4363 else 4364 return IntRange(std::max(NumPositive + 1, NumNegative), 4365 false/*NonNegative*/); 4366 } 4367 4368 const BuiltinType *BT = cast<BuiltinType>(T); 4369 assert(BT->isInteger()); 4370 4371 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 4372 } 4373 4374 /// Returns the "target" range of a canonical integral type, i.e. 4375 /// the range of values expressible in the type. 4376 /// 4377 /// This matches forValueOfCanonicalType except that enums have the 4378 /// full range of their type, not the range of their enumerators. 4379 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 4380 assert(T->isCanonicalUnqualified()); 4381 4382 if (const VectorType *VT = dyn_cast<VectorType>(T)) 4383 T = VT->getElementType().getTypePtr(); 4384 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 4385 T = CT->getElementType().getTypePtr(); 4386 if (const EnumType *ET = dyn_cast<EnumType>(T)) 4387 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 4388 4389 const BuiltinType *BT = cast<BuiltinType>(T); 4390 assert(BT->isInteger()); 4391 4392 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 4393 } 4394 4395 /// Returns the supremum of two ranges: i.e. their conservative merge. 4396 static IntRange join(IntRange L, IntRange R) { 4397 return IntRange(std::max(L.Width, R.Width), 4398 L.NonNegative && R.NonNegative); 4399 } 4400 4401 /// Returns the infinum of two ranges: i.e. their aggressive merge. 4402 static IntRange meet(IntRange L, IntRange R) { 4403 return IntRange(std::min(L.Width, R.Width), 4404 L.NonNegative || R.NonNegative); 4405 } 4406}; 4407 4408static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 4409 unsigned MaxWidth) { 4410 if (value.isSigned() && value.isNegative()) 4411 return IntRange(value.getMinSignedBits(), false); 4412 4413 if (value.getBitWidth() > MaxWidth) 4414 value = value.trunc(MaxWidth); 4415 4416 // isNonNegative() just checks the sign bit without considering 4417 // signedness. 4418 return IntRange(value.getActiveBits(), true); 4419} 4420 4421static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 4422 unsigned MaxWidth) { 4423 if (result.isInt()) 4424 return GetValueRange(C, result.getInt(), MaxWidth); 4425 4426 if (result.isVector()) { 4427 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 4428 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 4429 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 4430 R = IntRange::join(R, El); 4431 } 4432 return R; 4433 } 4434 4435 if (result.isComplexInt()) { 4436 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 4437 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 4438 return IntRange::join(R, I); 4439 } 4440 4441 // This can happen with lossless casts to intptr_t of "based" lvalues. 4442 // Assume it might use arbitrary bits. 4443 // FIXME: The only reason we need to pass the type in here is to get 4444 // the sign right on this one case. It would be nice if APValue 4445 // preserved this. 4446 assert(result.isLValue() || result.isAddrLabelDiff()); 4447 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 4448} 4449 4450static QualType GetExprType(Expr *E) { 4451 QualType Ty = E->getType(); 4452 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 4453 Ty = AtomicRHS->getValueType(); 4454 return Ty; 4455} 4456 4457/// Pseudo-evaluate the given integer expression, estimating the 4458/// range of values it might take. 4459/// 4460/// \param MaxWidth - the width to which the value will be truncated 4461static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 4462 E = E->IgnoreParens(); 4463 4464 // Try a full evaluation first. 4465 Expr::EvalResult result; 4466 if (E->EvaluateAsRValue(result, C)) 4467 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 4468 4469 // I think we only want to look through implicit casts here; if the 4470 // user has an explicit widening cast, we should treat the value as 4471 // being of the new, wider type. 4472 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 4473 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 4474 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 4475 4476 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 4477 4478 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 4479 4480 // Assume that non-integer casts can span the full range of the type. 4481 if (!isIntegerCast) 4482 return OutputTypeRange; 4483 4484 IntRange SubRange 4485 = GetExprRange(C, CE->getSubExpr(), 4486 std::min(MaxWidth, OutputTypeRange.Width)); 4487 4488 // Bail out if the subexpr's range is as wide as the cast type. 4489 if (SubRange.Width >= OutputTypeRange.Width) 4490 return OutputTypeRange; 4491 4492 // Otherwise, we take the smaller width, and we're non-negative if 4493 // either the output type or the subexpr is. 4494 return IntRange(SubRange.Width, 4495 SubRange.NonNegative || OutputTypeRange.NonNegative); 4496 } 4497 4498 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 4499 // If we can fold the condition, just take that operand. 4500 bool CondResult; 4501 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 4502 return GetExprRange(C, CondResult ? CO->getTrueExpr() 4503 : CO->getFalseExpr(), 4504 MaxWidth); 4505 4506 // Otherwise, conservatively merge. 4507 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 4508 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 4509 return IntRange::join(L, R); 4510 } 4511 4512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4513 switch (BO->getOpcode()) { 4514 4515 // Boolean-valued operations are single-bit and positive. 4516 case BO_LAnd: 4517 case BO_LOr: 4518 case BO_LT: 4519 case BO_GT: 4520 case BO_LE: 4521 case BO_GE: 4522 case BO_EQ: 4523 case BO_NE: 4524 return IntRange::forBoolType(); 4525 4526 // The type of the assignments is the type of the LHS, so the RHS 4527 // is not necessarily the same type. 4528 case BO_MulAssign: 4529 case BO_DivAssign: 4530 case BO_RemAssign: 4531 case BO_AddAssign: 4532 case BO_SubAssign: 4533 case BO_XorAssign: 4534 case BO_OrAssign: 4535 // TODO: bitfields? 4536 return IntRange::forValueOfType(C, GetExprType(E)); 4537 4538 // Simple assignments just pass through the RHS, which will have 4539 // been coerced to the LHS type. 4540 case BO_Assign: 4541 // TODO: bitfields? 4542 return GetExprRange(C, BO->getRHS(), MaxWidth); 4543 4544 // Operations with opaque sources are black-listed. 4545 case BO_PtrMemD: 4546 case BO_PtrMemI: 4547 return IntRange::forValueOfType(C, GetExprType(E)); 4548 4549 // Bitwise-and uses the *infinum* of the two source ranges. 4550 case BO_And: 4551 case BO_AndAssign: 4552 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 4553 GetExprRange(C, BO->getRHS(), MaxWidth)); 4554 4555 // Left shift gets black-listed based on a judgement call. 4556 case BO_Shl: 4557 // ...except that we want to treat '1 << (blah)' as logically 4558 // positive. It's an important idiom. 4559 if (IntegerLiteral *I 4560 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 4561 if (I->getValue() == 1) { 4562 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 4563 return IntRange(R.Width, /*NonNegative*/ true); 4564 } 4565 } 4566 // fallthrough 4567 4568 case BO_ShlAssign: 4569 return IntRange::forValueOfType(C, GetExprType(E)); 4570 4571 // Right shift by a constant can narrow its left argument. 4572 case BO_Shr: 4573 case BO_ShrAssign: { 4574 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4575 4576 // If the shift amount is a positive constant, drop the width by 4577 // that much. 4578 llvm::APSInt shift; 4579 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 4580 shift.isNonNegative()) { 4581 unsigned zext = shift.getZExtValue(); 4582 if (zext >= L.Width) 4583 L.Width = (L.NonNegative ? 0 : 1); 4584 else 4585 L.Width -= zext; 4586 } 4587 4588 return L; 4589 } 4590 4591 // Comma acts as its right operand. 4592 case BO_Comma: 4593 return GetExprRange(C, BO->getRHS(), MaxWidth); 4594 4595 // Black-list pointer subtractions. 4596 case BO_Sub: 4597 if (BO->getLHS()->getType()->isPointerType()) 4598 return IntRange::forValueOfType(C, GetExprType(E)); 4599 break; 4600 4601 // The width of a division result is mostly determined by the size 4602 // of the LHS. 4603 case BO_Div: { 4604 // Don't 'pre-truncate' the operands. 4605 unsigned opWidth = C.getIntWidth(GetExprType(E)); 4606 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4607 4608 // If the divisor is constant, use that. 4609 llvm::APSInt divisor; 4610 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 4611 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 4612 if (log2 >= L.Width) 4613 L.Width = (L.NonNegative ? 0 : 1); 4614 else 4615 L.Width = std::min(L.Width - log2, MaxWidth); 4616 return L; 4617 } 4618 4619 // Otherwise, just use the LHS's width. 4620 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4621 return IntRange(L.Width, L.NonNegative && R.NonNegative); 4622 } 4623 4624 // The result of a remainder can't be larger than the result of 4625 // either side. 4626 case BO_Rem: { 4627 // Don't 'pre-truncate' the operands. 4628 unsigned opWidth = C.getIntWidth(GetExprType(E)); 4629 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4630 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4631 4632 IntRange meet = IntRange::meet(L, R); 4633 meet.Width = std::min(meet.Width, MaxWidth); 4634 return meet; 4635 } 4636 4637 // The default behavior is okay for these. 4638 case BO_Mul: 4639 case BO_Add: 4640 case BO_Xor: 4641 case BO_Or: 4642 break; 4643 } 4644 4645 // The default case is to treat the operation as if it were closed 4646 // on the narrowest type that encompasses both operands. 4647 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4648 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 4649 return IntRange::join(L, R); 4650 } 4651 4652 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 4653 switch (UO->getOpcode()) { 4654 // Boolean-valued operations are white-listed. 4655 case UO_LNot: 4656 return IntRange::forBoolType(); 4657 4658 // Operations with opaque sources are black-listed. 4659 case UO_Deref: 4660 case UO_AddrOf: // should be impossible 4661 return IntRange::forValueOfType(C, GetExprType(E)); 4662 4663 default: 4664 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 4665 } 4666 } 4667 4668 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 4669 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 4670 4671 if (FieldDecl *BitField = E->getSourceBitField()) 4672 return IntRange(BitField->getBitWidthValue(C), 4673 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 4674 4675 return IntRange::forValueOfType(C, GetExprType(E)); 4676} 4677 4678static IntRange GetExprRange(ASTContext &C, Expr *E) { 4679 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 4680} 4681 4682/// Checks whether the given value, which currently has the given 4683/// source semantics, has the same value when coerced through the 4684/// target semantics. 4685static bool IsSameFloatAfterCast(const llvm::APFloat &value, 4686 const llvm::fltSemantics &Src, 4687 const llvm::fltSemantics &Tgt) { 4688 llvm::APFloat truncated = value; 4689 4690 bool ignored; 4691 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 4692 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 4693 4694 return truncated.bitwiseIsEqual(value); 4695} 4696 4697/// Checks whether the given value, which currently has the given 4698/// source semantics, has the same value when coerced through the 4699/// target semantics. 4700/// 4701/// The value might be a vector of floats (or a complex number). 4702static bool IsSameFloatAfterCast(const APValue &value, 4703 const llvm::fltSemantics &Src, 4704 const llvm::fltSemantics &Tgt) { 4705 if (value.isFloat()) 4706 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 4707 4708 if (value.isVector()) { 4709 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 4710 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 4711 return false; 4712 return true; 4713 } 4714 4715 assert(value.isComplexFloat()); 4716 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 4717 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 4718} 4719 4720static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 4721 4722static bool IsZero(Sema &S, Expr *E) { 4723 // Suppress cases where we are comparing against an enum constant. 4724 if (const DeclRefExpr *DR = 4725 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 4726 if (isa<EnumConstantDecl>(DR->getDecl())) 4727 return false; 4728 4729 // Suppress cases where the '0' value is expanded from a macro. 4730 if (E->getLocStart().isMacroID()) 4731 return false; 4732 4733 llvm::APSInt Value; 4734 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 4735} 4736 4737static bool HasEnumType(Expr *E) { 4738 // Strip off implicit integral promotions. 4739 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4740 if (ICE->getCastKind() != CK_IntegralCast && 4741 ICE->getCastKind() != CK_NoOp) 4742 break; 4743 E = ICE->getSubExpr(); 4744 } 4745 4746 return E->getType()->isEnumeralType(); 4747} 4748 4749static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 4750 BinaryOperatorKind op = E->getOpcode(); 4751 if (E->isValueDependent()) 4752 return; 4753 4754 if (op == BO_LT && IsZero(S, E->getRHS())) { 4755 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4756 << "< 0" << "false" << HasEnumType(E->getLHS()) 4757 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4758 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 4759 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4760 << ">= 0" << "true" << HasEnumType(E->getLHS()) 4761 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4762 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 4763 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4764 << "0 >" << "false" << HasEnumType(E->getRHS()) 4765 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4766 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 4767 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4768 << "0 <=" << "true" << HasEnumType(E->getRHS()) 4769 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4770 } 4771} 4772 4773static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 4774 Expr *Constant, Expr *Other, 4775 llvm::APSInt Value, 4776 bool RhsConstant) { 4777 // 0 values are handled later by CheckTrivialUnsignedComparison(). 4778 if (Value == 0) 4779 return; 4780 4781 BinaryOperatorKind op = E->getOpcode(); 4782 QualType OtherT = Other->getType(); 4783 QualType ConstantT = Constant->getType(); 4784 QualType CommonT = E->getLHS()->getType(); 4785 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 4786 return; 4787 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) 4788 && "comparison with non-integer type"); 4789 4790 bool ConstantSigned = ConstantT->isSignedIntegerType(); 4791 bool CommonSigned = CommonT->isSignedIntegerType(); 4792 4793 bool EqualityOnly = false; 4794 4795 // TODO: Investigate using GetExprRange() to get tighter bounds on 4796 // on the bit ranges. 4797 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 4798 unsigned OtherWidth = OtherRange.Width; 4799 4800 if (CommonSigned) { 4801 // The common type is signed, therefore no signed to unsigned conversion. 4802 if (!OtherRange.NonNegative) { 4803 // Check that the constant is representable in type OtherT. 4804 if (ConstantSigned) { 4805 if (OtherWidth >= Value.getMinSignedBits()) 4806 return; 4807 } else { // !ConstantSigned 4808 if (OtherWidth >= Value.getActiveBits() + 1) 4809 return; 4810 } 4811 } else { // !OtherSigned 4812 // Check that the constant is representable in type OtherT. 4813 // Negative values are out of range. 4814 if (ConstantSigned) { 4815 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 4816 return; 4817 } else { // !ConstantSigned 4818 if (OtherWidth >= Value.getActiveBits()) 4819 return; 4820 } 4821 } 4822 } else { // !CommonSigned 4823 if (OtherRange.NonNegative) { 4824 if (OtherWidth >= Value.getActiveBits()) 4825 return; 4826 } else if (!OtherRange.NonNegative && !ConstantSigned) { 4827 // Check to see if the constant is representable in OtherT. 4828 if (OtherWidth > Value.getActiveBits()) 4829 return; 4830 // Check to see if the constant is equivalent to a negative value 4831 // cast to CommonT. 4832 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) && 4833 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 4834 return; 4835 // The constant value rests between values that OtherT can represent after 4836 // conversion. Relational comparison still works, but equality 4837 // comparisons will be tautological. 4838 EqualityOnly = true; 4839 } else { // OtherSigned && ConstantSigned 4840 assert(0 && "Two signed types converted to unsigned types."); 4841 } 4842 } 4843 4844 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 4845 4846 bool IsTrue = true; 4847 if (op == BO_EQ || op == BO_NE) { 4848 IsTrue = op == BO_NE; 4849 } else if (EqualityOnly) { 4850 return; 4851 } else if (RhsConstant) { 4852 if (op == BO_GT || op == BO_GE) 4853 IsTrue = !PositiveConstant; 4854 else // op == BO_LT || op == BO_LE 4855 IsTrue = PositiveConstant; 4856 } else { 4857 if (op == BO_LT || op == BO_LE) 4858 IsTrue = !PositiveConstant; 4859 else // op == BO_GT || op == BO_GE 4860 IsTrue = PositiveConstant; 4861 } 4862 4863 // If this is a comparison to an enum constant, include that 4864 // constant in the diagnostic. 4865 const EnumConstantDecl *ED = 0; 4866 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 4867 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 4868 4869 SmallString<64> PrettySourceValue; 4870 llvm::raw_svector_ostream OS(PrettySourceValue); 4871 if (ED) 4872 OS << '\'' << *ED << "' (" << Value << ")"; 4873 else 4874 OS << Value; 4875 4876 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare) 4877 << OS.str() << OtherT << IsTrue 4878 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4879} 4880 4881/// Analyze the operands of the given comparison. Implements the 4882/// fallback case from AnalyzeComparison. 4883static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 4884 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4885 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4886} 4887 4888/// \brief Implements -Wsign-compare. 4889/// 4890/// \param E the binary operator to check for warnings 4891static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 4892 // The type the comparison is being performed in. 4893 QualType T = E->getLHS()->getType(); 4894 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 4895 && "comparison with mismatched types"); 4896 if (E->isValueDependent()) 4897 return AnalyzeImpConvsInComparison(S, E); 4898 4899 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 4900 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 4901 4902 bool IsComparisonConstant = false; 4903 4904 // Check whether an integer constant comparison results in a value 4905 // of 'true' or 'false'. 4906 if (T->isIntegralType(S.Context)) { 4907 llvm::APSInt RHSValue; 4908 bool IsRHSIntegralLiteral = 4909 RHS->isIntegerConstantExpr(RHSValue, S.Context); 4910 llvm::APSInt LHSValue; 4911 bool IsLHSIntegralLiteral = 4912 LHS->isIntegerConstantExpr(LHSValue, S.Context); 4913 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 4914 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 4915 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 4916 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 4917 else 4918 IsComparisonConstant = 4919 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 4920 } else if (!T->hasUnsignedIntegerRepresentation()) 4921 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 4922 4923 // We don't do anything special if this isn't an unsigned integral 4924 // comparison: we're only interested in integral comparisons, and 4925 // signed comparisons only happen in cases we don't care to warn about. 4926 // 4927 // We also don't care about value-dependent expressions or expressions 4928 // whose result is a constant. 4929 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 4930 return AnalyzeImpConvsInComparison(S, E); 4931 4932 // Check to see if one of the (unmodified) operands is of different 4933 // signedness. 4934 Expr *signedOperand, *unsignedOperand; 4935 if (LHS->getType()->hasSignedIntegerRepresentation()) { 4936 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 4937 "unsigned comparison between two signed integer expressions?"); 4938 signedOperand = LHS; 4939 unsignedOperand = RHS; 4940 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 4941 signedOperand = RHS; 4942 unsignedOperand = LHS; 4943 } else { 4944 CheckTrivialUnsignedComparison(S, E); 4945 return AnalyzeImpConvsInComparison(S, E); 4946 } 4947 4948 // Otherwise, calculate the effective range of the signed operand. 4949 IntRange signedRange = GetExprRange(S.Context, signedOperand); 4950 4951 // Go ahead and analyze implicit conversions in the operands. Note 4952 // that we skip the implicit conversions on both sides. 4953 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 4954 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 4955 4956 // If the signed range is non-negative, -Wsign-compare won't fire, 4957 // but we should still check for comparisons which are always true 4958 // or false. 4959 if (signedRange.NonNegative) 4960 return CheckTrivialUnsignedComparison(S, E); 4961 4962 // For (in)equality comparisons, if the unsigned operand is a 4963 // constant which cannot collide with a overflowed signed operand, 4964 // then reinterpreting the signed operand as unsigned will not 4965 // change the result of the comparison. 4966 if (E->isEqualityOp()) { 4967 unsigned comparisonWidth = S.Context.getIntWidth(T); 4968 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 4969 4970 // We should never be unable to prove that the unsigned operand is 4971 // non-negative. 4972 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 4973 4974 if (unsignedRange.Width < comparisonWidth) 4975 return; 4976 } 4977 4978 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 4979 S.PDiag(diag::warn_mixed_sign_comparison) 4980 << LHS->getType() << RHS->getType() 4981 << LHS->getSourceRange() << RHS->getSourceRange()); 4982} 4983 4984/// Analyzes an attempt to assign the given value to a bitfield. 4985/// 4986/// Returns true if there was something fishy about the attempt. 4987static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 4988 SourceLocation InitLoc) { 4989 assert(Bitfield->isBitField()); 4990 if (Bitfield->isInvalidDecl()) 4991 return false; 4992 4993 // White-list bool bitfields. 4994 if (Bitfield->getType()->isBooleanType()) 4995 return false; 4996 4997 // Ignore value- or type-dependent expressions. 4998 if (Bitfield->getBitWidth()->isValueDependent() || 4999 Bitfield->getBitWidth()->isTypeDependent() || 5000 Init->isValueDependent() || 5001 Init->isTypeDependent()) 5002 return false; 5003 5004 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 5005 5006 llvm::APSInt Value; 5007 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 5008 return false; 5009 5010 unsigned OriginalWidth = Value.getBitWidth(); 5011 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 5012 5013 if (OriginalWidth <= FieldWidth) 5014 return false; 5015 5016 // Compute the value which the bitfield will contain. 5017 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 5018 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 5019 5020 // Check whether the stored value is equal to the original value. 5021 TruncatedValue = TruncatedValue.extend(OriginalWidth); 5022 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 5023 return false; 5024 5025 // Special-case bitfields of width 1: booleans are naturally 0/1, and 5026 // therefore don't strictly fit into a signed bitfield of width 1. 5027 if (FieldWidth == 1 && Value == 1) 5028 return false; 5029 5030 std::string PrettyValue = Value.toString(10); 5031 std::string PrettyTrunc = TruncatedValue.toString(10); 5032 5033 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 5034 << PrettyValue << PrettyTrunc << OriginalInit->getType() 5035 << Init->getSourceRange(); 5036 5037 return true; 5038} 5039 5040/// Analyze the given simple or compound assignment for warning-worthy 5041/// operations. 5042static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 5043 // Just recurse on the LHS. 5044 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5045 5046 // We want to recurse on the RHS as normal unless we're assigning to 5047 // a bitfield. 5048 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 5049 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 5050 E->getOperatorLoc())) { 5051 // Recurse, ignoring any implicit conversions on the RHS. 5052 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 5053 E->getOperatorLoc()); 5054 } 5055 } 5056 5057 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5058} 5059 5060/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5061static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 5062 SourceLocation CContext, unsigned diag, 5063 bool pruneControlFlow = false) { 5064 if (pruneControlFlow) { 5065 S.DiagRuntimeBehavior(E->getExprLoc(), E, 5066 S.PDiag(diag) 5067 << SourceType << T << E->getSourceRange() 5068 << SourceRange(CContext)); 5069 return; 5070 } 5071 S.Diag(E->getExprLoc(), diag) 5072 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 5073} 5074 5075/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5076static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 5077 SourceLocation CContext, unsigned diag, 5078 bool pruneControlFlow = false) { 5079 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 5080} 5081 5082/// Diagnose an implicit cast from a literal expression. Does not warn when the 5083/// cast wouldn't lose information. 5084void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 5085 SourceLocation CContext) { 5086 // Try to convert the literal exactly to an integer. If we can, don't warn. 5087 bool isExact = false; 5088 const llvm::APFloat &Value = FL->getValue(); 5089 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 5090 T->hasUnsignedIntegerRepresentation()); 5091 if (Value.convertToInteger(IntegerValue, 5092 llvm::APFloat::rmTowardZero, &isExact) 5093 == llvm::APFloat::opOK && isExact) 5094 return; 5095 5096 // FIXME: Force the precision of the source value down so we don't print 5097 // digits which are usually useless (we don't really care here if we 5098 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 5099 // would automatically print the shortest representation, but it's a bit 5100 // tricky to implement. 5101 SmallString<16> PrettySourceValue; 5102 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 5103 precision = (precision * 59 + 195) / 196; 5104 Value.toString(PrettySourceValue, precision); 5105 5106 SmallString<16> PrettyTargetValue; 5107 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 5108 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 5109 else 5110 IntegerValue.toString(PrettyTargetValue); 5111 5112 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 5113 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 5114 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 5115} 5116 5117std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 5118 if (!Range.Width) return "0"; 5119 5120 llvm::APSInt ValueInRange = Value; 5121 ValueInRange.setIsSigned(!Range.NonNegative); 5122 ValueInRange = ValueInRange.trunc(Range.Width); 5123 return ValueInRange.toString(10); 5124} 5125 5126static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 5127 if (!isa<ImplicitCastExpr>(Ex)) 5128 return false; 5129 5130 Expr *InnerE = Ex->IgnoreParenImpCasts(); 5131 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 5132 const Type *Source = 5133 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 5134 if (Target->isDependentType()) 5135 return false; 5136 5137 const BuiltinType *FloatCandidateBT = 5138 dyn_cast<BuiltinType>(ToBool ? Source : Target); 5139 const Type *BoolCandidateType = ToBool ? Target : Source; 5140 5141 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 5142 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 5143} 5144 5145void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 5146 SourceLocation CC) { 5147 unsigned NumArgs = TheCall->getNumArgs(); 5148 for (unsigned i = 0; i < NumArgs; ++i) { 5149 Expr *CurrA = TheCall->getArg(i); 5150 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 5151 continue; 5152 5153 bool IsSwapped = ((i > 0) && 5154 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 5155 IsSwapped |= ((i < (NumArgs - 1)) && 5156 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 5157 if (IsSwapped) { 5158 // Warn on this floating-point to bool conversion. 5159 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 5160 CurrA->getType(), CC, 5161 diag::warn_impcast_floating_point_to_bool); 5162 } 5163 } 5164} 5165 5166void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 5167 SourceLocation CC, bool *ICContext = 0) { 5168 if (E->isTypeDependent() || E->isValueDependent()) return; 5169 5170 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 5171 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 5172 if (Source == Target) return; 5173 if (Target->isDependentType()) return; 5174 5175 // If the conversion context location is invalid don't complain. We also 5176 // don't want to emit a warning if the issue occurs from the expansion of 5177 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 5178 // delay this check as long as possible. Once we detect we are in that 5179 // scenario, we just return. 5180 if (CC.isInvalid()) 5181 return; 5182 5183 // Diagnose implicit casts to bool. 5184 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 5185 if (isa<StringLiteral>(E)) 5186 // Warn on string literal to bool. Checks for string literals in logical 5187 // expressions, for instances, assert(0 && "error here"), is prevented 5188 // by a check in AnalyzeImplicitConversions(). 5189 return DiagnoseImpCast(S, E, T, CC, 5190 diag::warn_impcast_string_literal_to_bool); 5191 if (Source->isFunctionType()) { 5192 // Warn on function to bool. Checks free functions and static member 5193 // functions. Weakly imported functions are excluded from the check, 5194 // since it's common to test their value to check whether the linker 5195 // found a definition for them. 5196 ValueDecl *D = 0; 5197 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 5198 D = R->getDecl(); 5199 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 5200 D = M->getMemberDecl(); 5201 } 5202 5203 if (D && !D->isWeak()) { 5204 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 5205 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 5206 << F << E->getSourceRange() << SourceRange(CC); 5207 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 5208 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 5209 QualType ReturnType; 5210 UnresolvedSet<4> NonTemplateOverloads; 5211 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 5212 if (!ReturnType.isNull() 5213 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 5214 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 5215 << FixItHint::CreateInsertion( 5216 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 5217 return; 5218 } 5219 } 5220 } 5221 } 5222 5223 // Strip vector types. 5224 if (isa<VectorType>(Source)) { 5225 if (!isa<VectorType>(Target)) { 5226 if (S.SourceMgr.isInSystemMacro(CC)) 5227 return; 5228 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 5229 } 5230 5231 // If the vector cast is cast between two vectors of the same size, it is 5232 // a bitcast, not a conversion. 5233 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 5234 return; 5235 5236 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 5237 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 5238 } 5239 5240 // Strip complex types. 5241 if (isa<ComplexType>(Source)) { 5242 if (!isa<ComplexType>(Target)) { 5243 if (S.SourceMgr.isInSystemMacro(CC)) 5244 return; 5245 5246 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 5247 } 5248 5249 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 5250 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 5251 } 5252 5253 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 5254 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 5255 5256 // If the source is floating point... 5257 if (SourceBT && SourceBT->isFloatingPoint()) { 5258 // ...and the target is floating point... 5259 if (TargetBT && TargetBT->isFloatingPoint()) { 5260 // ...then warn if we're dropping FP rank. 5261 5262 // Builtin FP kinds are ordered by increasing FP rank. 5263 if (SourceBT->getKind() > TargetBT->getKind()) { 5264 // Don't warn about float constants that are precisely 5265 // representable in the target type. 5266 Expr::EvalResult result; 5267 if (E->EvaluateAsRValue(result, S.Context)) { 5268 // Value might be a float, a float vector, or a float complex. 5269 if (IsSameFloatAfterCast(result.Val, 5270 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 5271 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 5272 return; 5273 } 5274 5275 if (S.SourceMgr.isInSystemMacro(CC)) 5276 return; 5277 5278 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 5279 } 5280 return; 5281 } 5282 5283 // If the target is integral, always warn. 5284 if (TargetBT && TargetBT->isInteger()) { 5285 if (S.SourceMgr.isInSystemMacro(CC)) 5286 return; 5287 5288 Expr *InnerE = E->IgnoreParenImpCasts(); 5289 // We also want to warn on, e.g., "int i = -1.234" 5290 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 5291 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 5292 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 5293 5294 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 5295 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 5296 } else { 5297 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 5298 } 5299 } 5300 5301 // If the target is bool, warn if expr is a function or method call. 5302 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 5303 isa<CallExpr>(E)) { 5304 // Check last argument of function call to see if it is an 5305 // implicit cast from a type matching the type the result 5306 // is being cast to. 5307 CallExpr *CEx = cast<CallExpr>(E); 5308 unsigned NumArgs = CEx->getNumArgs(); 5309 if (NumArgs > 0) { 5310 Expr *LastA = CEx->getArg(NumArgs - 1); 5311 Expr *InnerE = LastA->IgnoreParenImpCasts(); 5312 const Type *InnerType = 5313 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 5314 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 5315 // Warn on this floating-point to bool conversion 5316 DiagnoseImpCast(S, E, T, CC, 5317 diag::warn_impcast_floating_point_to_bool); 5318 } 5319 } 5320 } 5321 return; 5322 } 5323 5324 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 5325 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 5326 && !Target->isBlockPointerType() && !Target->isMemberPointerType() 5327 && Target->isScalarType() && !Target->isNullPtrType()) { 5328 SourceLocation Loc = E->getSourceRange().getBegin(); 5329 if (Loc.isMacroID()) 5330 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 5331 if (!Loc.isMacroID() || CC.isMacroID()) 5332 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 5333 << T << clang::SourceRange(CC) 5334 << FixItHint::CreateReplacement(Loc, 5335 S.getFixItZeroLiteralForType(T, Loc)); 5336 } 5337 5338 if (!Source->isIntegerType() || !Target->isIntegerType()) 5339 return; 5340 5341 // TODO: remove this early return once the false positives for constant->bool 5342 // in templates, macros, etc, are reduced or removed. 5343 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 5344 return; 5345 5346 IntRange SourceRange = GetExprRange(S.Context, E); 5347 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 5348 5349 if (SourceRange.Width > TargetRange.Width) { 5350 // If the source is a constant, use a default-on diagnostic. 5351 // TODO: this should happen for bitfield stores, too. 5352 llvm::APSInt Value(32); 5353 if (E->isIntegerConstantExpr(Value, S.Context)) { 5354 if (S.SourceMgr.isInSystemMacro(CC)) 5355 return; 5356 5357 std::string PrettySourceValue = Value.toString(10); 5358 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 5359 5360 S.DiagRuntimeBehavior(E->getExprLoc(), E, 5361 S.PDiag(diag::warn_impcast_integer_precision_constant) 5362 << PrettySourceValue << PrettyTargetValue 5363 << E->getType() << T << E->getSourceRange() 5364 << clang::SourceRange(CC)); 5365 return; 5366 } 5367 5368 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 5369 if (S.SourceMgr.isInSystemMacro(CC)) 5370 return; 5371 5372 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 5373 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 5374 /* pruneControlFlow */ true); 5375 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 5376 } 5377 5378 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 5379 (!TargetRange.NonNegative && SourceRange.NonNegative && 5380 SourceRange.Width == TargetRange.Width)) { 5381 5382 if (S.SourceMgr.isInSystemMacro(CC)) 5383 return; 5384 5385 unsigned DiagID = diag::warn_impcast_integer_sign; 5386 5387 // Traditionally, gcc has warned about this under -Wsign-compare. 5388 // We also want to warn about it in -Wconversion. 5389 // So if -Wconversion is off, use a completely identical diagnostic 5390 // in the sign-compare group. 5391 // The conditional-checking code will 5392 if (ICContext) { 5393 DiagID = diag::warn_impcast_integer_sign_conditional; 5394 *ICContext = true; 5395 } 5396 5397 return DiagnoseImpCast(S, E, T, CC, DiagID); 5398 } 5399 5400 // Diagnose conversions between different enumeration types. 5401 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 5402 // type, to give us better diagnostics. 5403 QualType SourceType = E->getType(); 5404 if (!S.getLangOpts().CPlusPlus) { 5405 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5406 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 5407 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 5408 SourceType = S.Context.getTypeDeclType(Enum); 5409 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 5410 } 5411 } 5412 5413 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 5414 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 5415 if (SourceEnum->getDecl()->hasNameForLinkage() && 5416 TargetEnum->getDecl()->hasNameForLinkage() && 5417 SourceEnum != TargetEnum) { 5418 if (S.SourceMgr.isInSystemMacro(CC)) 5419 return; 5420 5421 return DiagnoseImpCast(S, E, SourceType, T, CC, 5422 diag::warn_impcast_different_enum_types); 5423 } 5424 5425 return; 5426} 5427 5428void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 5429 SourceLocation CC, QualType T); 5430 5431void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 5432 SourceLocation CC, bool &ICContext) { 5433 E = E->IgnoreParenImpCasts(); 5434 5435 if (isa<ConditionalOperator>(E)) 5436 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 5437 5438 AnalyzeImplicitConversions(S, E, CC); 5439 if (E->getType() != T) 5440 return CheckImplicitConversion(S, E, T, CC, &ICContext); 5441 return; 5442} 5443 5444void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 5445 SourceLocation CC, QualType T) { 5446 AnalyzeImplicitConversions(S, E->getCond(), CC); 5447 5448 bool Suspicious = false; 5449 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 5450 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 5451 5452 // If -Wconversion would have warned about either of the candidates 5453 // for a signedness conversion to the context type... 5454 if (!Suspicious) return; 5455 5456 // ...but it's currently ignored... 5457 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 5458 CC)) 5459 return; 5460 5461 // ...then check whether it would have warned about either of the 5462 // candidates for a signedness conversion to the condition type. 5463 if (E->getType() == T) return; 5464 5465 Suspicious = false; 5466 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 5467 E->getType(), CC, &Suspicious); 5468 if (!Suspicious) 5469 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 5470 E->getType(), CC, &Suspicious); 5471} 5472 5473/// AnalyzeImplicitConversions - Find and report any interesting 5474/// implicit conversions in the given expression. There are a couple 5475/// of competing diagnostics here, -Wconversion and -Wsign-compare. 5476void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 5477 QualType T = OrigE->getType(); 5478 Expr *E = OrigE->IgnoreParenImpCasts(); 5479 5480 if (E->isTypeDependent() || E->isValueDependent()) 5481 return; 5482 5483 // For conditional operators, we analyze the arguments as if they 5484 // were being fed directly into the output. 5485 if (isa<ConditionalOperator>(E)) { 5486 ConditionalOperator *CO = cast<ConditionalOperator>(E); 5487 CheckConditionalOperator(S, CO, CC, T); 5488 return; 5489 } 5490 5491 // Check implicit argument conversions for function calls. 5492 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 5493 CheckImplicitArgumentConversions(S, Call, CC); 5494 5495 // Go ahead and check any implicit conversions we might have skipped. 5496 // The non-canonical typecheck is just an optimization; 5497 // CheckImplicitConversion will filter out dead implicit conversions. 5498 if (E->getType() != T) 5499 CheckImplicitConversion(S, E, T, CC); 5500 5501 // Now continue drilling into this expression. 5502 5503 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) { 5504 if (POE->getResultExpr()) 5505 E = POE->getResultExpr(); 5506 } 5507 5508 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 5509 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 5510 5511 // Skip past explicit casts. 5512 if (isa<ExplicitCastExpr>(E)) { 5513 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 5514 return AnalyzeImplicitConversions(S, E, CC); 5515 } 5516 5517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5518 // Do a somewhat different check with comparison operators. 5519 if (BO->isComparisonOp()) 5520 return AnalyzeComparison(S, BO); 5521 5522 // And with simple assignments. 5523 if (BO->getOpcode() == BO_Assign) 5524 return AnalyzeAssignment(S, BO); 5525 } 5526 5527 // These break the otherwise-useful invariant below. Fortunately, 5528 // we don't really need to recurse into them, because any internal 5529 // expressions should have been analyzed already when they were 5530 // built into statements. 5531 if (isa<StmtExpr>(E)) return; 5532 5533 // Don't descend into unevaluated contexts. 5534 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 5535 5536 // Now just recurse over the expression's children. 5537 CC = E->getExprLoc(); 5538 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 5539 bool IsLogicalOperator = BO && BO->isLogicalOp(); 5540 for (Stmt::child_range I = E->children(); I; ++I) { 5541 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 5542 if (!ChildExpr) 5543 continue; 5544 5545 if (IsLogicalOperator && 5546 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 5547 // Ignore checking string literals that are in logical operators. 5548 continue; 5549 AnalyzeImplicitConversions(S, ChildExpr, CC); 5550 } 5551} 5552 5553} // end anonymous namespace 5554 5555/// Diagnoses "dangerous" implicit conversions within the given 5556/// expression (which is a full expression). Implements -Wconversion 5557/// and -Wsign-compare. 5558/// 5559/// \param CC the "context" location of the implicit conversion, i.e. 5560/// the most location of the syntactic entity requiring the implicit 5561/// conversion 5562void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 5563 // Don't diagnose in unevaluated contexts. 5564 if (isUnevaluatedContext()) 5565 return; 5566 5567 // Don't diagnose for value- or type-dependent expressions. 5568 if (E->isTypeDependent() || E->isValueDependent()) 5569 return; 5570 5571 // Check for array bounds violations in cases where the check isn't triggered 5572 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 5573 // ArraySubscriptExpr is on the RHS of a variable initialization. 5574 CheckArrayAccess(E); 5575 5576 // This is not the right CC for (e.g.) a variable initialization. 5577 AnalyzeImplicitConversions(*this, E, CC); 5578} 5579 5580/// Diagnose when expression is an integer constant expression and its evaluation 5581/// results in integer overflow 5582void Sema::CheckForIntOverflow (Expr *E) { 5583 if (isa<BinaryOperator>(E->IgnoreParens())) { 5584 SmallVector<PartialDiagnosticAt, 4> Diags; 5585 E->EvaluateForOverflow(Context, &Diags); 5586 } 5587} 5588 5589namespace { 5590/// \brief Visitor for expressions which looks for unsequenced operations on the 5591/// same object. 5592class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 5593 typedef EvaluatedExprVisitor<SequenceChecker> Base; 5594 5595 /// \brief A tree of sequenced regions within an expression. Two regions are 5596 /// unsequenced if one is an ancestor or a descendent of the other. When we 5597 /// finish processing an expression with sequencing, such as a comma 5598 /// expression, we fold its tree nodes into its parent, since they are 5599 /// unsequenced with respect to nodes we will visit later. 5600 class SequenceTree { 5601 struct Value { 5602 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 5603 unsigned Parent : 31; 5604 bool Merged : 1; 5605 }; 5606 SmallVector<Value, 8> Values; 5607 5608 public: 5609 /// \brief A region within an expression which may be sequenced with respect 5610 /// to some other region. 5611 class Seq { 5612 explicit Seq(unsigned N) : Index(N) {} 5613 unsigned Index; 5614 friend class SequenceTree; 5615 public: 5616 Seq() : Index(0) {} 5617 }; 5618 5619 SequenceTree() { Values.push_back(Value(0)); } 5620 Seq root() const { return Seq(0); } 5621 5622 /// \brief Create a new sequence of operations, which is an unsequenced 5623 /// subset of \p Parent. This sequence of operations is sequenced with 5624 /// respect to other children of \p Parent. 5625 Seq allocate(Seq Parent) { 5626 Values.push_back(Value(Parent.Index)); 5627 return Seq(Values.size() - 1); 5628 } 5629 5630 /// \brief Merge a sequence of operations into its parent. 5631 void merge(Seq S) { 5632 Values[S.Index].Merged = true; 5633 } 5634 5635 /// \brief Determine whether two operations are unsequenced. This operation 5636 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 5637 /// should have been merged into its parent as appropriate. 5638 bool isUnsequenced(Seq Cur, Seq Old) { 5639 unsigned C = representative(Cur.Index); 5640 unsigned Target = representative(Old.Index); 5641 while (C >= Target) { 5642 if (C == Target) 5643 return true; 5644 C = Values[C].Parent; 5645 } 5646 return false; 5647 } 5648 5649 private: 5650 /// \brief Pick a representative for a sequence. 5651 unsigned representative(unsigned K) { 5652 if (Values[K].Merged) 5653 // Perform path compression as we go. 5654 return Values[K].Parent = representative(Values[K].Parent); 5655 return K; 5656 } 5657 }; 5658 5659 /// An object for which we can track unsequenced uses. 5660 typedef NamedDecl *Object; 5661 5662 /// Different flavors of object usage which we track. We only track the 5663 /// least-sequenced usage of each kind. 5664 enum UsageKind { 5665 /// A read of an object. Multiple unsequenced reads are OK. 5666 UK_Use, 5667 /// A modification of an object which is sequenced before the value 5668 /// computation of the expression, such as ++n in C++. 5669 UK_ModAsValue, 5670 /// A modification of an object which is not sequenced before the value 5671 /// computation of the expression, such as n++. 5672 UK_ModAsSideEffect, 5673 5674 UK_Count = UK_ModAsSideEffect + 1 5675 }; 5676 5677 struct Usage { 5678 Usage() : Use(0), Seq() {} 5679 Expr *Use; 5680 SequenceTree::Seq Seq; 5681 }; 5682 5683 struct UsageInfo { 5684 UsageInfo() : Diagnosed(false) {} 5685 Usage Uses[UK_Count]; 5686 /// Have we issued a diagnostic for this variable already? 5687 bool Diagnosed; 5688 }; 5689 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 5690 5691 Sema &SemaRef; 5692 /// Sequenced regions within the expression. 5693 SequenceTree Tree; 5694 /// Declaration modifications and references which we have seen. 5695 UsageInfoMap UsageMap; 5696 /// The region we are currently within. 5697 SequenceTree::Seq Region; 5698 /// Filled in with declarations which were modified as a side-effect 5699 /// (that is, post-increment operations). 5700 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 5701 /// Expressions to check later. We defer checking these to reduce 5702 /// stack usage. 5703 SmallVectorImpl<Expr *> &WorkList; 5704 5705 /// RAII object wrapping the visitation of a sequenced subexpression of an 5706 /// expression. At the end of this process, the side-effects of the evaluation 5707 /// become sequenced with respect to the value computation of the result, so 5708 /// we downgrade any UK_ModAsSideEffect within the evaluation to 5709 /// UK_ModAsValue. 5710 struct SequencedSubexpression { 5711 SequencedSubexpression(SequenceChecker &Self) 5712 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 5713 Self.ModAsSideEffect = &ModAsSideEffect; 5714 } 5715 ~SequencedSubexpression() { 5716 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) { 5717 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first]; 5718 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second; 5719 Self.addUsage(U, ModAsSideEffect[I].first, 5720 ModAsSideEffect[I].second.Use, UK_ModAsValue); 5721 } 5722 Self.ModAsSideEffect = OldModAsSideEffect; 5723 } 5724 5725 SequenceChecker &Self; 5726 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 5727 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 5728 }; 5729 5730 /// RAII object wrapping the visitation of a subexpression which we might 5731 /// choose to evaluate as a constant. If any subexpression is evaluated and 5732 /// found to be non-constant, this allows us to suppress the evaluation of 5733 /// the outer expression. 5734 class EvaluationTracker { 5735 public: 5736 EvaluationTracker(SequenceChecker &Self) 5737 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 5738 Self.EvalTracker = this; 5739 } 5740 ~EvaluationTracker() { 5741 Self.EvalTracker = Prev; 5742 if (Prev) 5743 Prev->EvalOK &= EvalOK; 5744 } 5745 5746 bool evaluate(const Expr *E, bool &Result) { 5747 if (!EvalOK || E->isValueDependent()) 5748 return false; 5749 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 5750 return EvalOK; 5751 } 5752 5753 private: 5754 SequenceChecker &Self; 5755 EvaluationTracker *Prev; 5756 bool EvalOK; 5757 } *EvalTracker; 5758 5759 /// \brief Find the object which is produced by the specified expression, 5760 /// if any. 5761 Object getObject(Expr *E, bool Mod) const { 5762 E = E->IgnoreParenCasts(); 5763 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 5764 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 5765 return getObject(UO->getSubExpr(), Mod); 5766 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5767 if (BO->getOpcode() == BO_Comma) 5768 return getObject(BO->getRHS(), Mod); 5769 if (Mod && BO->isAssignmentOp()) 5770 return getObject(BO->getLHS(), Mod); 5771 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5772 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 5773 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 5774 return ME->getMemberDecl(); 5775 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5776 // FIXME: If this is a reference, map through to its value. 5777 return DRE->getDecl(); 5778 return 0; 5779 } 5780 5781 /// \brief Note that an object was modified or used by an expression. 5782 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 5783 Usage &U = UI.Uses[UK]; 5784 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 5785 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 5786 ModAsSideEffect->push_back(std::make_pair(O, U)); 5787 U.Use = Ref; 5788 U.Seq = Region; 5789 } 5790 } 5791 /// \brief Check whether a modification or use conflicts with a prior usage. 5792 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 5793 bool IsModMod) { 5794 if (UI.Diagnosed) 5795 return; 5796 5797 const Usage &U = UI.Uses[OtherKind]; 5798 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 5799 return; 5800 5801 Expr *Mod = U.Use; 5802 Expr *ModOrUse = Ref; 5803 if (OtherKind == UK_Use) 5804 std::swap(Mod, ModOrUse); 5805 5806 SemaRef.Diag(Mod->getExprLoc(), 5807 IsModMod ? diag::warn_unsequenced_mod_mod 5808 : diag::warn_unsequenced_mod_use) 5809 << O << SourceRange(ModOrUse->getExprLoc()); 5810 UI.Diagnosed = true; 5811 } 5812 5813 void notePreUse(Object O, Expr *Use) { 5814 UsageInfo &U = UsageMap[O]; 5815 // Uses conflict with other modifications. 5816 checkUsage(O, U, Use, UK_ModAsValue, false); 5817 } 5818 void notePostUse(Object O, Expr *Use) { 5819 UsageInfo &U = UsageMap[O]; 5820 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 5821 addUsage(U, O, Use, UK_Use); 5822 } 5823 5824 void notePreMod(Object O, Expr *Mod) { 5825 UsageInfo &U = UsageMap[O]; 5826 // Modifications conflict with other modifications and with uses. 5827 checkUsage(O, U, Mod, UK_ModAsValue, true); 5828 checkUsage(O, U, Mod, UK_Use, false); 5829 } 5830 void notePostMod(Object O, Expr *Use, UsageKind UK) { 5831 UsageInfo &U = UsageMap[O]; 5832 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 5833 addUsage(U, O, Use, UK); 5834 } 5835 5836public: 5837 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 5838 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0), 5839 WorkList(WorkList), EvalTracker(0) { 5840 Visit(E); 5841 } 5842 5843 void VisitStmt(Stmt *S) { 5844 // Skip all statements which aren't expressions for now. 5845 } 5846 5847 void VisitExpr(Expr *E) { 5848 // By default, just recurse to evaluated subexpressions. 5849 Base::VisitStmt(E); 5850 } 5851 5852 void VisitCastExpr(CastExpr *E) { 5853 Object O = Object(); 5854 if (E->getCastKind() == CK_LValueToRValue) 5855 O = getObject(E->getSubExpr(), false); 5856 5857 if (O) 5858 notePreUse(O, E); 5859 VisitExpr(E); 5860 if (O) 5861 notePostUse(O, E); 5862 } 5863 5864 void VisitBinComma(BinaryOperator *BO) { 5865 // C++11 [expr.comma]p1: 5866 // Every value computation and side effect associated with the left 5867 // expression is sequenced before every value computation and side 5868 // effect associated with the right expression. 5869 SequenceTree::Seq LHS = Tree.allocate(Region); 5870 SequenceTree::Seq RHS = Tree.allocate(Region); 5871 SequenceTree::Seq OldRegion = Region; 5872 5873 { 5874 SequencedSubexpression SeqLHS(*this); 5875 Region = LHS; 5876 Visit(BO->getLHS()); 5877 } 5878 5879 Region = RHS; 5880 Visit(BO->getRHS()); 5881 5882 Region = OldRegion; 5883 5884 // Forget that LHS and RHS are sequenced. They are both unsequenced 5885 // with respect to other stuff. 5886 Tree.merge(LHS); 5887 Tree.merge(RHS); 5888 } 5889 5890 void VisitBinAssign(BinaryOperator *BO) { 5891 // The modification is sequenced after the value computation of the LHS 5892 // and RHS, so check it before inspecting the operands and update the 5893 // map afterwards. 5894 Object O = getObject(BO->getLHS(), true); 5895 if (!O) 5896 return VisitExpr(BO); 5897 5898 notePreMod(O, BO); 5899 5900 // C++11 [expr.ass]p7: 5901 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 5902 // only once. 5903 // 5904 // Therefore, for a compound assignment operator, O is considered used 5905 // everywhere except within the evaluation of E1 itself. 5906 if (isa<CompoundAssignOperator>(BO)) 5907 notePreUse(O, BO); 5908 5909 Visit(BO->getLHS()); 5910 5911 if (isa<CompoundAssignOperator>(BO)) 5912 notePostUse(O, BO); 5913 5914 Visit(BO->getRHS()); 5915 5916 // C++11 [expr.ass]p1: 5917 // the assignment is sequenced [...] before the value computation of the 5918 // assignment expression. 5919 // C11 6.5.16/3 has no such rule. 5920 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 5921 : UK_ModAsSideEffect); 5922 } 5923 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 5924 VisitBinAssign(CAO); 5925 } 5926 5927 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 5928 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 5929 void VisitUnaryPreIncDec(UnaryOperator *UO) { 5930 Object O = getObject(UO->getSubExpr(), true); 5931 if (!O) 5932 return VisitExpr(UO); 5933 5934 notePreMod(O, UO); 5935 Visit(UO->getSubExpr()); 5936 // C++11 [expr.pre.incr]p1: 5937 // the expression ++x is equivalent to x+=1 5938 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 5939 : UK_ModAsSideEffect); 5940 } 5941 5942 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 5943 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 5944 void VisitUnaryPostIncDec(UnaryOperator *UO) { 5945 Object O = getObject(UO->getSubExpr(), true); 5946 if (!O) 5947 return VisitExpr(UO); 5948 5949 notePreMod(O, UO); 5950 Visit(UO->getSubExpr()); 5951 notePostMod(O, UO, UK_ModAsSideEffect); 5952 } 5953 5954 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 5955 void VisitBinLOr(BinaryOperator *BO) { 5956 // The side-effects of the LHS of an '&&' are sequenced before the 5957 // value computation of the RHS, and hence before the value computation 5958 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 5959 // as if they were unconditionally sequenced. 5960 EvaluationTracker Eval(*this); 5961 { 5962 SequencedSubexpression Sequenced(*this); 5963 Visit(BO->getLHS()); 5964 } 5965 5966 bool Result; 5967 if (Eval.evaluate(BO->getLHS(), Result)) { 5968 if (!Result) 5969 Visit(BO->getRHS()); 5970 } else { 5971 // Check for unsequenced operations in the RHS, treating it as an 5972 // entirely separate evaluation. 5973 // 5974 // FIXME: If there are operations in the RHS which are unsequenced 5975 // with respect to operations outside the RHS, and those operations 5976 // are unconditionally evaluated, diagnose them. 5977 WorkList.push_back(BO->getRHS()); 5978 } 5979 } 5980 void VisitBinLAnd(BinaryOperator *BO) { 5981 EvaluationTracker Eval(*this); 5982 { 5983 SequencedSubexpression Sequenced(*this); 5984 Visit(BO->getLHS()); 5985 } 5986 5987 bool Result; 5988 if (Eval.evaluate(BO->getLHS(), Result)) { 5989 if (Result) 5990 Visit(BO->getRHS()); 5991 } else { 5992 WorkList.push_back(BO->getRHS()); 5993 } 5994 } 5995 5996 // Only visit the condition, unless we can be sure which subexpression will 5997 // be chosen. 5998 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 5999 EvaluationTracker Eval(*this); 6000 { 6001 SequencedSubexpression Sequenced(*this); 6002 Visit(CO->getCond()); 6003 } 6004 6005 bool Result; 6006 if (Eval.evaluate(CO->getCond(), Result)) 6007 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 6008 else { 6009 WorkList.push_back(CO->getTrueExpr()); 6010 WorkList.push_back(CO->getFalseExpr()); 6011 } 6012 } 6013 6014 void VisitCallExpr(CallExpr *CE) { 6015 // C++11 [intro.execution]p15: 6016 // When calling a function [...], every value computation and side effect 6017 // associated with any argument expression, or with the postfix expression 6018 // designating the called function, is sequenced before execution of every 6019 // expression or statement in the body of the function [and thus before 6020 // the value computation of its result]. 6021 SequencedSubexpression Sequenced(*this); 6022 Base::VisitCallExpr(CE); 6023 6024 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 6025 } 6026 6027 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 6028 // This is a call, so all subexpressions are sequenced before the result. 6029 SequencedSubexpression Sequenced(*this); 6030 6031 if (!CCE->isListInitialization()) 6032 return VisitExpr(CCE); 6033 6034 // In C++11, list initializations are sequenced. 6035 SmallVector<SequenceTree::Seq, 32> Elts; 6036 SequenceTree::Seq Parent = Region; 6037 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 6038 E = CCE->arg_end(); 6039 I != E; ++I) { 6040 Region = Tree.allocate(Parent); 6041 Elts.push_back(Region); 6042 Visit(*I); 6043 } 6044 6045 // Forget that the initializers are sequenced. 6046 Region = Parent; 6047 for (unsigned I = 0; I < Elts.size(); ++I) 6048 Tree.merge(Elts[I]); 6049 } 6050 6051 void VisitInitListExpr(InitListExpr *ILE) { 6052 if (!SemaRef.getLangOpts().CPlusPlus11) 6053 return VisitExpr(ILE); 6054 6055 // In C++11, list initializations are sequenced. 6056 SmallVector<SequenceTree::Seq, 32> Elts; 6057 SequenceTree::Seq Parent = Region; 6058 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 6059 Expr *E = ILE->getInit(I); 6060 if (!E) continue; 6061 Region = Tree.allocate(Parent); 6062 Elts.push_back(Region); 6063 Visit(E); 6064 } 6065 6066 // Forget that the initializers are sequenced. 6067 Region = Parent; 6068 for (unsigned I = 0; I < Elts.size(); ++I) 6069 Tree.merge(Elts[I]); 6070 } 6071}; 6072} 6073 6074void Sema::CheckUnsequencedOperations(Expr *E) { 6075 SmallVector<Expr *, 8> WorkList; 6076 WorkList.push_back(E); 6077 while (!WorkList.empty()) { 6078 Expr *Item = WorkList.pop_back_val(); 6079 SequenceChecker(*this, Item, WorkList); 6080 } 6081} 6082 6083void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 6084 bool IsConstexpr) { 6085 CheckImplicitConversions(E, CheckLoc); 6086 CheckUnsequencedOperations(E); 6087 if (!IsConstexpr && !E->isValueDependent()) 6088 CheckForIntOverflow(E); 6089} 6090 6091void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 6092 FieldDecl *BitField, 6093 Expr *Init) { 6094 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 6095} 6096 6097/// CheckParmsForFunctionDef - Check that the parameters of the given 6098/// function are appropriate for the definition of a function. This 6099/// takes care of any checks that cannot be performed on the 6100/// declaration itself, e.g., that the types of each of the function 6101/// parameters are complete. 6102bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 6103 ParmVarDecl *const *PEnd, 6104 bool CheckParameterNames) { 6105 bool HasInvalidParm = false; 6106 for (; P != PEnd; ++P) { 6107 ParmVarDecl *Param = *P; 6108 6109 // C99 6.7.5.3p4: the parameters in a parameter type list in a 6110 // function declarator that is part of a function definition of 6111 // that function shall not have incomplete type. 6112 // 6113 // This is also C++ [dcl.fct]p6. 6114 if (!Param->isInvalidDecl() && 6115 RequireCompleteType(Param->getLocation(), Param->getType(), 6116 diag::err_typecheck_decl_incomplete_type)) { 6117 Param->setInvalidDecl(); 6118 HasInvalidParm = true; 6119 } 6120 6121 // C99 6.9.1p5: If the declarator includes a parameter type list, the 6122 // declaration of each parameter shall include an identifier. 6123 if (CheckParameterNames && 6124 Param->getIdentifier() == 0 && 6125 !Param->isImplicit() && 6126 !getLangOpts().CPlusPlus) 6127 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 6128 6129 // C99 6.7.5.3p12: 6130 // If the function declarator is not part of a definition of that 6131 // function, parameters may have incomplete type and may use the [*] 6132 // notation in their sequences of declarator specifiers to specify 6133 // variable length array types. 6134 QualType PType = Param->getOriginalType(); 6135 while (const ArrayType *AT = Context.getAsArrayType(PType)) { 6136 if (AT->getSizeModifier() == ArrayType::Star) { 6137 // FIXME: This diagnostic should point the '[*]' if source-location 6138 // information is added for it. 6139 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 6140 break; 6141 } 6142 PType= AT->getElementType(); 6143 } 6144 6145 // MSVC destroys objects passed by value in the callee. Therefore a 6146 // function definition which takes such a parameter must be able to call the 6147 // object's destructor. 6148 if (getLangOpts().CPlusPlus && 6149 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) { 6150 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) 6151 FinalizeVarWithDestructor(Param, RT); 6152 } 6153 } 6154 6155 return HasInvalidParm; 6156} 6157 6158/// CheckCastAlign - Implements -Wcast-align, which warns when a 6159/// pointer cast increases the alignment requirements. 6160void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 6161 // This is actually a lot of work to potentially be doing on every 6162 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 6163 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 6164 TRange.getBegin()) 6165 == DiagnosticsEngine::Ignored) 6166 return; 6167 6168 // Ignore dependent types. 6169 if (T->isDependentType() || Op->getType()->isDependentType()) 6170 return; 6171 6172 // Require that the destination be a pointer type. 6173 const PointerType *DestPtr = T->getAs<PointerType>(); 6174 if (!DestPtr) return; 6175 6176 // If the destination has alignment 1, we're done. 6177 QualType DestPointee = DestPtr->getPointeeType(); 6178 if (DestPointee->isIncompleteType()) return; 6179 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 6180 if (DestAlign.isOne()) return; 6181 6182 // Require that the source be a pointer type. 6183 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 6184 if (!SrcPtr) return; 6185 QualType SrcPointee = SrcPtr->getPointeeType(); 6186 6187 // Whitelist casts from cv void*. We already implicitly 6188 // whitelisted casts to cv void*, since they have alignment 1. 6189 // Also whitelist casts involving incomplete types, which implicitly 6190 // includes 'void'. 6191 if (SrcPointee->isIncompleteType()) return; 6192 6193 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 6194 if (SrcAlign >= DestAlign) return; 6195 6196 Diag(TRange.getBegin(), diag::warn_cast_align) 6197 << Op->getType() << T 6198 << static_cast<unsigned>(SrcAlign.getQuantity()) 6199 << static_cast<unsigned>(DestAlign.getQuantity()) 6200 << TRange << Op->getSourceRange(); 6201} 6202 6203static const Type* getElementType(const Expr *BaseExpr) { 6204 const Type* EltType = BaseExpr->getType().getTypePtr(); 6205 if (EltType->isAnyPointerType()) 6206 return EltType->getPointeeType().getTypePtr(); 6207 else if (EltType->isArrayType()) 6208 return EltType->getBaseElementTypeUnsafe(); 6209 return EltType; 6210} 6211 6212/// \brief Check whether this array fits the idiom of a size-one tail padded 6213/// array member of a struct. 6214/// 6215/// We avoid emitting out-of-bounds access warnings for such arrays as they are 6216/// commonly used to emulate flexible arrays in C89 code. 6217static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 6218 const NamedDecl *ND) { 6219 if (Size != 1 || !ND) return false; 6220 6221 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 6222 if (!FD) return false; 6223 6224 // Don't consider sizes resulting from macro expansions or template argument 6225 // substitution to form C89 tail-padded arrays. 6226 6227 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 6228 while (TInfo) { 6229 TypeLoc TL = TInfo->getTypeLoc(); 6230 // Look through typedefs. 6231 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 6232 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 6233 TInfo = TDL->getTypeSourceInfo(); 6234 continue; 6235 } 6236 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 6237 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 6238 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 6239 return false; 6240 } 6241 break; 6242 } 6243 6244 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 6245 if (!RD) return false; 6246 if (RD->isUnion()) return false; 6247 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 6248 if (!CRD->isStandardLayout()) return false; 6249 } 6250 6251 // See if this is the last field decl in the record. 6252 const Decl *D = FD; 6253 while ((D = D->getNextDeclInContext())) 6254 if (isa<FieldDecl>(D)) 6255 return false; 6256 return true; 6257} 6258 6259void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6260 const ArraySubscriptExpr *ASE, 6261 bool AllowOnePastEnd, bool IndexNegated) { 6262 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 6263 if (IndexExpr->isValueDependent()) 6264 return; 6265 6266 const Type *EffectiveType = getElementType(BaseExpr); 6267 BaseExpr = BaseExpr->IgnoreParenCasts(); 6268 const ConstantArrayType *ArrayTy = 6269 Context.getAsConstantArrayType(BaseExpr->getType()); 6270 if (!ArrayTy) 6271 return; 6272 6273 llvm::APSInt index; 6274 if (!IndexExpr->EvaluateAsInt(index, Context)) 6275 return; 6276 if (IndexNegated) 6277 index = -index; 6278 6279 const NamedDecl *ND = NULL; 6280 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 6281 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 6282 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 6283 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 6284 6285 if (index.isUnsigned() || !index.isNegative()) { 6286 llvm::APInt size = ArrayTy->getSize(); 6287 if (!size.isStrictlyPositive()) 6288 return; 6289 6290 const Type* BaseType = getElementType(BaseExpr); 6291 if (BaseType != EffectiveType) { 6292 // Make sure we're comparing apples to apples when comparing index to size 6293 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 6294 uint64_t array_typesize = Context.getTypeSize(BaseType); 6295 // Handle ptrarith_typesize being zero, such as when casting to void* 6296 if (!ptrarith_typesize) ptrarith_typesize = 1; 6297 if (ptrarith_typesize != array_typesize) { 6298 // There's a cast to a different size type involved 6299 uint64_t ratio = array_typesize / ptrarith_typesize; 6300 // TODO: Be smarter about handling cases where array_typesize is not a 6301 // multiple of ptrarith_typesize 6302 if (ptrarith_typesize * ratio == array_typesize) 6303 size *= llvm::APInt(size.getBitWidth(), ratio); 6304 } 6305 } 6306 6307 if (size.getBitWidth() > index.getBitWidth()) 6308 index = index.zext(size.getBitWidth()); 6309 else if (size.getBitWidth() < index.getBitWidth()) 6310 size = size.zext(index.getBitWidth()); 6311 6312 // For array subscripting the index must be less than size, but for pointer 6313 // arithmetic also allow the index (offset) to be equal to size since 6314 // computing the next address after the end of the array is legal and 6315 // commonly done e.g. in C++ iterators and range-based for loops. 6316 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 6317 return; 6318 6319 // Also don't warn for arrays of size 1 which are members of some 6320 // structure. These are often used to approximate flexible arrays in C89 6321 // code. 6322 if (IsTailPaddedMemberArray(*this, size, ND)) 6323 return; 6324 6325 // Suppress the warning if the subscript expression (as identified by the 6326 // ']' location) and the index expression are both from macro expansions 6327 // within a system header. 6328 if (ASE) { 6329 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 6330 ASE->getRBracketLoc()); 6331 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 6332 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 6333 IndexExpr->getLocStart()); 6334 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 6335 return; 6336 } 6337 } 6338 6339 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 6340 if (ASE) 6341 DiagID = diag::warn_array_index_exceeds_bounds; 6342 6343 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 6344 PDiag(DiagID) << index.toString(10, true) 6345 << size.toString(10, true) 6346 << (unsigned)size.getLimitedValue(~0U) 6347 << IndexExpr->getSourceRange()); 6348 } else { 6349 unsigned DiagID = diag::warn_array_index_precedes_bounds; 6350 if (!ASE) { 6351 DiagID = diag::warn_ptr_arith_precedes_bounds; 6352 if (index.isNegative()) index = -index; 6353 } 6354 6355 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 6356 PDiag(DiagID) << index.toString(10, true) 6357 << IndexExpr->getSourceRange()); 6358 } 6359 6360 if (!ND) { 6361 // Try harder to find a NamedDecl to point at in the note. 6362 while (const ArraySubscriptExpr *ASE = 6363 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 6364 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 6365 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 6366 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 6367 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 6368 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 6369 } 6370 6371 if (ND) 6372 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 6373 PDiag(diag::note_array_index_out_of_bounds) 6374 << ND->getDeclName()); 6375} 6376 6377void Sema::CheckArrayAccess(const Expr *expr) { 6378 int AllowOnePastEnd = 0; 6379 while (expr) { 6380 expr = expr->IgnoreParenImpCasts(); 6381 switch (expr->getStmtClass()) { 6382 case Stmt::ArraySubscriptExprClass: { 6383 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 6384 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 6385 AllowOnePastEnd > 0); 6386 return; 6387 } 6388 case Stmt::UnaryOperatorClass: { 6389 // Only unwrap the * and & unary operators 6390 const UnaryOperator *UO = cast<UnaryOperator>(expr); 6391 expr = UO->getSubExpr(); 6392 switch (UO->getOpcode()) { 6393 case UO_AddrOf: 6394 AllowOnePastEnd++; 6395 break; 6396 case UO_Deref: 6397 AllowOnePastEnd--; 6398 break; 6399 default: 6400 return; 6401 } 6402 break; 6403 } 6404 case Stmt::ConditionalOperatorClass: { 6405 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 6406 if (const Expr *lhs = cond->getLHS()) 6407 CheckArrayAccess(lhs); 6408 if (const Expr *rhs = cond->getRHS()) 6409 CheckArrayAccess(rhs); 6410 return; 6411 } 6412 default: 6413 return; 6414 } 6415 } 6416} 6417 6418//===--- CHECK: Objective-C retain cycles ----------------------------------// 6419 6420namespace { 6421 struct RetainCycleOwner { 6422 RetainCycleOwner() : Variable(0), Indirect(false) {} 6423 VarDecl *Variable; 6424 SourceRange Range; 6425 SourceLocation Loc; 6426 bool Indirect; 6427 6428 void setLocsFrom(Expr *e) { 6429 Loc = e->getExprLoc(); 6430 Range = e->getSourceRange(); 6431 } 6432 }; 6433} 6434 6435/// Consider whether capturing the given variable can possibly lead to 6436/// a retain cycle. 6437static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 6438 // In ARC, it's captured strongly iff the variable has __strong 6439 // lifetime. In MRR, it's captured strongly if the variable is 6440 // __block and has an appropriate type. 6441 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 6442 return false; 6443 6444 owner.Variable = var; 6445 if (ref) 6446 owner.setLocsFrom(ref); 6447 return true; 6448} 6449 6450static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 6451 while (true) { 6452 e = e->IgnoreParens(); 6453 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 6454 switch (cast->getCastKind()) { 6455 case CK_BitCast: 6456 case CK_LValueBitCast: 6457 case CK_LValueToRValue: 6458 case CK_ARCReclaimReturnedObject: 6459 e = cast->getSubExpr(); 6460 continue; 6461 6462 default: 6463 return false; 6464 } 6465 } 6466 6467 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 6468 ObjCIvarDecl *ivar = ref->getDecl(); 6469 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 6470 return false; 6471 6472 // Try to find a retain cycle in the base. 6473 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 6474 return false; 6475 6476 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 6477 owner.Indirect = true; 6478 return true; 6479 } 6480 6481 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 6482 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 6483 if (!var) return false; 6484 return considerVariable(var, ref, owner); 6485 } 6486 6487 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 6488 if (member->isArrow()) return false; 6489 6490 // Don't count this as an indirect ownership. 6491 e = member->getBase(); 6492 continue; 6493 } 6494 6495 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 6496 // Only pay attention to pseudo-objects on property references. 6497 ObjCPropertyRefExpr *pre 6498 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 6499 ->IgnoreParens()); 6500 if (!pre) return false; 6501 if (pre->isImplicitProperty()) return false; 6502 ObjCPropertyDecl *property = pre->getExplicitProperty(); 6503 if (!property->isRetaining() && 6504 !(property->getPropertyIvarDecl() && 6505 property->getPropertyIvarDecl()->getType() 6506 .getObjCLifetime() == Qualifiers::OCL_Strong)) 6507 return false; 6508 6509 owner.Indirect = true; 6510 if (pre->isSuperReceiver()) { 6511 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 6512 if (!owner.Variable) 6513 return false; 6514 owner.Loc = pre->getLocation(); 6515 owner.Range = pre->getSourceRange(); 6516 return true; 6517 } 6518 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 6519 ->getSourceExpr()); 6520 continue; 6521 } 6522 6523 // Array ivars? 6524 6525 return false; 6526 } 6527} 6528 6529namespace { 6530 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 6531 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 6532 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 6533 Variable(variable), Capturer(0) {} 6534 6535 VarDecl *Variable; 6536 Expr *Capturer; 6537 6538 void VisitDeclRefExpr(DeclRefExpr *ref) { 6539 if (ref->getDecl() == Variable && !Capturer) 6540 Capturer = ref; 6541 } 6542 6543 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 6544 if (Capturer) return; 6545 Visit(ref->getBase()); 6546 if (Capturer && ref->isFreeIvar()) 6547 Capturer = ref; 6548 } 6549 6550 void VisitBlockExpr(BlockExpr *block) { 6551 // Look inside nested blocks 6552 if (block->getBlockDecl()->capturesVariable(Variable)) 6553 Visit(block->getBlockDecl()->getBody()); 6554 } 6555 6556 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 6557 if (Capturer) return; 6558 if (OVE->getSourceExpr()) 6559 Visit(OVE->getSourceExpr()); 6560 } 6561 }; 6562} 6563 6564/// Check whether the given argument is a block which captures a 6565/// variable. 6566static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 6567 assert(owner.Variable && owner.Loc.isValid()); 6568 6569 e = e->IgnoreParenCasts(); 6570 6571 // Look through [^{...} copy] and Block_copy(^{...}). 6572 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 6573 Selector Cmd = ME->getSelector(); 6574 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 6575 e = ME->getInstanceReceiver(); 6576 if (!e) 6577 return 0; 6578 e = e->IgnoreParenCasts(); 6579 } 6580 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 6581 if (CE->getNumArgs() == 1) { 6582 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 6583 if (Fn) { 6584 const IdentifierInfo *FnI = Fn->getIdentifier(); 6585 if (FnI && FnI->isStr("_Block_copy")) { 6586 e = CE->getArg(0)->IgnoreParenCasts(); 6587 } 6588 } 6589 } 6590 } 6591 6592 BlockExpr *block = dyn_cast<BlockExpr>(e); 6593 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 6594 return 0; 6595 6596 FindCaptureVisitor visitor(S.Context, owner.Variable); 6597 visitor.Visit(block->getBlockDecl()->getBody()); 6598 return visitor.Capturer; 6599} 6600 6601static void diagnoseRetainCycle(Sema &S, Expr *capturer, 6602 RetainCycleOwner &owner) { 6603 assert(capturer); 6604 assert(owner.Variable && owner.Loc.isValid()); 6605 6606 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 6607 << owner.Variable << capturer->getSourceRange(); 6608 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 6609 << owner.Indirect << owner.Range; 6610} 6611 6612/// Check for a keyword selector that starts with the word 'add' or 6613/// 'set'. 6614static bool isSetterLikeSelector(Selector sel) { 6615 if (sel.isUnarySelector()) return false; 6616 6617 StringRef str = sel.getNameForSlot(0); 6618 while (!str.empty() && str.front() == '_') str = str.substr(1); 6619 if (str.startswith("set")) 6620 str = str.substr(3); 6621 else if (str.startswith("add")) { 6622 // Specially whitelist 'addOperationWithBlock:'. 6623 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 6624 return false; 6625 str = str.substr(3); 6626 } 6627 else 6628 return false; 6629 6630 if (str.empty()) return true; 6631 return !isLowercase(str.front()); 6632} 6633 6634/// Check a message send to see if it's likely to cause a retain cycle. 6635void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 6636 // Only check instance methods whose selector looks like a setter. 6637 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 6638 return; 6639 6640 // Try to find a variable that the receiver is strongly owned by. 6641 RetainCycleOwner owner; 6642 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 6643 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 6644 return; 6645 } else { 6646 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 6647 owner.Variable = getCurMethodDecl()->getSelfDecl(); 6648 owner.Loc = msg->getSuperLoc(); 6649 owner.Range = msg->getSuperLoc(); 6650 } 6651 6652 // Check whether the receiver is captured by any of the arguments. 6653 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 6654 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 6655 return diagnoseRetainCycle(*this, capturer, owner); 6656} 6657 6658/// Check a property assign to see if it's likely to cause a retain cycle. 6659void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 6660 RetainCycleOwner owner; 6661 if (!findRetainCycleOwner(*this, receiver, owner)) 6662 return; 6663 6664 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 6665 diagnoseRetainCycle(*this, capturer, owner); 6666} 6667 6668void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 6669 RetainCycleOwner Owner; 6670 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner)) 6671 return; 6672 6673 // Because we don't have an expression for the variable, we have to set the 6674 // location explicitly here. 6675 Owner.Loc = Var->getLocation(); 6676 Owner.Range = Var->getSourceRange(); 6677 6678 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 6679 diagnoseRetainCycle(*this, Capturer, Owner); 6680} 6681 6682static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 6683 Expr *RHS, bool isProperty) { 6684 // Check if RHS is an Objective-C object literal, which also can get 6685 // immediately zapped in a weak reference. Note that we explicitly 6686 // allow ObjCStringLiterals, since those are designed to never really die. 6687 RHS = RHS->IgnoreParenImpCasts(); 6688 6689 // This enum needs to match with the 'select' in 6690 // warn_objc_arc_literal_assign (off-by-1). 6691 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 6692 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 6693 return false; 6694 6695 S.Diag(Loc, diag::warn_arc_literal_assign) 6696 << (unsigned) Kind 6697 << (isProperty ? 0 : 1) 6698 << RHS->getSourceRange(); 6699 6700 return true; 6701} 6702 6703static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 6704 Qualifiers::ObjCLifetime LT, 6705 Expr *RHS, bool isProperty) { 6706 // Strip off any implicit cast added to get to the one ARC-specific. 6707 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 6708 if (cast->getCastKind() == CK_ARCConsumeObject) { 6709 S.Diag(Loc, diag::warn_arc_retained_assign) 6710 << (LT == Qualifiers::OCL_ExplicitNone) 6711 << (isProperty ? 0 : 1) 6712 << RHS->getSourceRange(); 6713 return true; 6714 } 6715 RHS = cast->getSubExpr(); 6716 } 6717 6718 if (LT == Qualifiers::OCL_Weak && 6719 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 6720 return true; 6721 6722 return false; 6723} 6724 6725bool Sema::checkUnsafeAssigns(SourceLocation Loc, 6726 QualType LHS, Expr *RHS) { 6727 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 6728 6729 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 6730 return false; 6731 6732 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 6733 return true; 6734 6735 return false; 6736} 6737 6738void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 6739 Expr *LHS, Expr *RHS) { 6740 QualType LHSType; 6741 // PropertyRef on LHS type need be directly obtained from 6742 // its declaration as it has a PsuedoType. 6743 ObjCPropertyRefExpr *PRE 6744 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 6745 if (PRE && !PRE->isImplicitProperty()) { 6746 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 6747 if (PD) 6748 LHSType = PD->getType(); 6749 } 6750 6751 if (LHSType.isNull()) 6752 LHSType = LHS->getType(); 6753 6754 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 6755 6756 if (LT == Qualifiers::OCL_Weak) { 6757 DiagnosticsEngine::Level Level = 6758 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 6759 if (Level != DiagnosticsEngine::Ignored) 6760 getCurFunction()->markSafeWeakUse(LHS); 6761 } 6762 6763 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 6764 return; 6765 6766 // FIXME. Check for other life times. 6767 if (LT != Qualifiers::OCL_None) 6768 return; 6769 6770 if (PRE) { 6771 if (PRE->isImplicitProperty()) 6772 return; 6773 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 6774 if (!PD) 6775 return; 6776 6777 unsigned Attributes = PD->getPropertyAttributes(); 6778 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 6779 // when 'assign' attribute was not explicitly specified 6780 // by user, ignore it and rely on property type itself 6781 // for lifetime info. 6782 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 6783 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 6784 LHSType->isObjCRetainableType()) 6785 return; 6786 6787 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 6788 if (cast->getCastKind() == CK_ARCConsumeObject) { 6789 Diag(Loc, diag::warn_arc_retained_property_assign) 6790 << RHS->getSourceRange(); 6791 return; 6792 } 6793 RHS = cast->getSubExpr(); 6794 } 6795 } 6796 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 6797 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 6798 return; 6799 } 6800 } 6801} 6802 6803//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 6804 6805namespace { 6806bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 6807 SourceLocation StmtLoc, 6808 const NullStmt *Body) { 6809 // Do not warn if the body is a macro that expands to nothing, e.g: 6810 // 6811 // #define CALL(x) 6812 // if (condition) 6813 // CALL(0); 6814 // 6815 if (Body->hasLeadingEmptyMacro()) 6816 return false; 6817 6818 // Get line numbers of statement and body. 6819 bool StmtLineInvalid; 6820 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 6821 &StmtLineInvalid); 6822 if (StmtLineInvalid) 6823 return false; 6824 6825 bool BodyLineInvalid; 6826 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 6827 &BodyLineInvalid); 6828 if (BodyLineInvalid) 6829 return false; 6830 6831 // Warn if null statement and body are on the same line. 6832 if (StmtLine != BodyLine) 6833 return false; 6834 6835 return true; 6836} 6837} // Unnamed namespace 6838 6839void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 6840 const Stmt *Body, 6841 unsigned DiagID) { 6842 // Since this is a syntactic check, don't emit diagnostic for template 6843 // instantiations, this just adds noise. 6844 if (CurrentInstantiationScope) 6845 return; 6846 6847 // The body should be a null statement. 6848 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 6849 if (!NBody) 6850 return; 6851 6852 // Do the usual checks. 6853 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 6854 return; 6855 6856 Diag(NBody->getSemiLoc(), DiagID); 6857 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 6858} 6859 6860void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 6861 const Stmt *PossibleBody) { 6862 assert(!CurrentInstantiationScope); // Ensured by caller 6863 6864 SourceLocation StmtLoc; 6865 const Stmt *Body; 6866 unsigned DiagID; 6867 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 6868 StmtLoc = FS->getRParenLoc(); 6869 Body = FS->getBody(); 6870 DiagID = diag::warn_empty_for_body; 6871 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 6872 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 6873 Body = WS->getBody(); 6874 DiagID = diag::warn_empty_while_body; 6875 } else 6876 return; // Neither `for' nor `while'. 6877 6878 // The body should be a null statement. 6879 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 6880 if (!NBody) 6881 return; 6882 6883 // Skip expensive checks if diagnostic is disabled. 6884 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 6885 DiagnosticsEngine::Ignored) 6886 return; 6887 6888 // Do the usual checks. 6889 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 6890 return; 6891 6892 // `for(...);' and `while(...);' are popular idioms, so in order to keep 6893 // noise level low, emit diagnostics only if for/while is followed by a 6894 // CompoundStmt, e.g.: 6895 // for (int i = 0; i < n; i++); 6896 // { 6897 // a(i); 6898 // } 6899 // or if for/while is followed by a statement with more indentation 6900 // than for/while itself: 6901 // for (int i = 0; i < n; i++); 6902 // a(i); 6903 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 6904 if (!ProbableTypo) { 6905 bool BodyColInvalid; 6906 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 6907 PossibleBody->getLocStart(), 6908 &BodyColInvalid); 6909 if (BodyColInvalid) 6910 return; 6911 6912 bool StmtColInvalid; 6913 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 6914 S->getLocStart(), 6915 &StmtColInvalid); 6916 if (StmtColInvalid) 6917 return; 6918 6919 if (BodyCol > StmtCol) 6920 ProbableTypo = true; 6921 } 6922 6923 if (ProbableTypo) { 6924 Diag(NBody->getSemiLoc(), DiagID); 6925 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 6926 } 6927} 6928 6929//===--- Layout compatibility ----------------------------------------------// 6930 6931namespace { 6932 6933bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 6934 6935/// \brief Check if two enumeration types are layout-compatible. 6936bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 6937 // C++11 [dcl.enum] p8: 6938 // Two enumeration types are layout-compatible if they have the same 6939 // underlying type. 6940 return ED1->isComplete() && ED2->isComplete() && 6941 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 6942} 6943 6944/// \brief Check if two fields are layout-compatible. 6945bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 6946 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 6947 return false; 6948 6949 if (Field1->isBitField() != Field2->isBitField()) 6950 return false; 6951 6952 if (Field1->isBitField()) { 6953 // Make sure that the bit-fields are the same length. 6954 unsigned Bits1 = Field1->getBitWidthValue(C); 6955 unsigned Bits2 = Field2->getBitWidthValue(C); 6956 6957 if (Bits1 != Bits2) 6958 return false; 6959 } 6960 6961 return true; 6962} 6963 6964/// \brief Check if two standard-layout structs are layout-compatible. 6965/// (C++11 [class.mem] p17) 6966bool isLayoutCompatibleStruct(ASTContext &C, 6967 RecordDecl *RD1, 6968 RecordDecl *RD2) { 6969 // If both records are C++ classes, check that base classes match. 6970 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 6971 // If one of records is a CXXRecordDecl we are in C++ mode, 6972 // thus the other one is a CXXRecordDecl, too. 6973 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 6974 // Check number of base classes. 6975 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 6976 return false; 6977 6978 // Check the base classes. 6979 for (CXXRecordDecl::base_class_const_iterator 6980 Base1 = D1CXX->bases_begin(), 6981 BaseEnd1 = D1CXX->bases_end(), 6982 Base2 = D2CXX->bases_begin(); 6983 Base1 != BaseEnd1; 6984 ++Base1, ++Base2) { 6985 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 6986 return false; 6987 } 6988 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 6989 // If only RD2 is a C++ class, it should have zero base classes. 6990 if (D2CXX->getNumBases() > 0) 6991 return false; 6992 } 6993 6994 // Check the fields. 6995 RecordDecl::field_iterator Field2 = RD2->field_begin(), 6996 Field2End = RD2->field_end(), 6997 Field1 = RD1->field_begin(), 6998 Field1End = RD1->field_end(); 6999 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 7000 if (!isLayoutCompatible(C, *Field1, *Field2)) 7001 return false; 7002 } 7003 if (Field1 != Field1End || Field2 != Field2End) 7004 return false; 7005 7006 return true; 7007} 7008 7009/// \brief Check if two standard-layout unions are layout-compatible. 7010/// (C++11 [class.mem] p18) 7011bool isLayoutCompatibleUnion(ASTContext &C, 7012 RecordDecl *RD1, 7013 RecordDecl *RD2) { 7014 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 7015 for (RecordDecl::field_iterator Field2 = RD2->field_begin(), 7016 Field2End = RD2->field_end(); 7017 Field2 != Field2End; ++Field2) { 7018 UnmatchedFields.insert(*Field2); 7019 } 7020 7021 for (RecordDecl::field_iterator Field1 = RD1->field_begin(), 7022 Field1End = RD1->field_end(); 7023 Field1 != Field1End; ++Field1) { 7024 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 7025 I = UnmatchedFields.begin(), 7026 E = UnmatchedFields.end(); 7027 7028 for ( ; I != E; ++I) { 7029 if (isLayoutCompatible(C, *Field1, *I)) { 7030 bool Result = UnmatchedFields.erase(*I); 7031 (void) Result; 7032 assert(Result); 7033 break; 7034 } 7035 } 7036 if (I == E) 7037 return false; 7038 } 7039 7040 return UnmatchedFields.empty(); 7041} 7042 7043bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 7044 if (RD1->isUnion() != RD2->isUnion()) 7045 return false; 7046 7047 if (RD1->isUnion()) 7048 return isLayoutCompatibleUnion(C, RD1, RD2); 7049 else 7050 return isLayoutCompatibleStruct(C, RD1, RD2); 7051} 7052 7053/// \brief Check if two types are layout-compatible in C++11 sense. 7054bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 7055 if (T1.isNull() || T2.isNull()) 7056 return false; 7057 7058 // C++11 [basic.types] p11: 7059 // If two types T1 and T2 are the same type, then T1 and T2 are 7060 // layout-compatible types. 7061 if (C.hasSameType(T1, T2)) 7062 return true; 7063 7064 T1 = T1.getCanonicalType().getUnqualifiedType(); 7065 T2 = T2.getCanonicalType().getUnqualifiedType(); 7066 7067 const Type::TypeClass TC1 = T1->getTypeClass(); 7068 const Type::TypeClass TC2 = T2->getTypeClass(); 7069 7070 if (TC1 != TC2) 7071 return false; 7072 7073 if (TC1 == Type::Enum) { 7074 return isLayoutCompatible(C, 7075 cast<EnumType>(T1)->getDecl(), 7076 cast<EnumType>(T2)->getDecl()); 7077 } else if (TC1 == Type::Record) { 7078 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 7079 return false; 7080 7081 return isLayoutCompatible(C, 7082 cast<RecordType>(T1)->getDecl(), 7083 cast<RecordType>(T2)->getDecl()); 7084 } 7085 7086 return false; 7087} 7088} 7089 7090//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 7091 7092namespace { 7093/// \brief Given a type tag expression find the type tag itself. 7094/// 7095/// \param TypeExpr Type tag expression, as it appears in user's code. 7096/// 7097/// \param VD Declaration of an identifier that appears in a type tag. 7098/// 7099/// \param MagicValue Type tag magic value. 7100bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 7101 const ValueDecl **VD, uint64_t *MagicValue) { 7102 while(true) { 7103 if (!TypeExpr) 7104 return false; 7105 7106 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 7107 7108 switch (TypeExpr->getStmtClass()) { 7109 case Stmt::UnaryOperatorClass: { 7110 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 7111 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 7112 TypeExpr = UO->getSubExpr(); 7113 continue; 7114 } 7115 return false; 7116 } 7117 7118 case Stmt::DeclRefExprClass: { 7119 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 7120 *VD = DRE->getDecl(); 7121 return true; 7122 } 7123 7124 case Stmt::IntegerLiteralClass: { 7125 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 7126 llvm::APInt MagicValueAPInt = IL->getValue(); 7127 if (MagicValueAPInt.getActiveBits() <= 64) { 7128 *MagicValue = MagicValueAPInt.getZExtValue(); 7129 return true; 7130 } else 7131 return false; 7132 } 7133 7134 case Stmt::BinaryConditionalOperatorClass: 7135 case Stmt::ConditionalOperatorClass: { 7136 const AbstractConditionalOperator *ACO = 7137 cast<AbstractConditionalOperator>(TypeExpr); 7138 bool Result; 7139 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 7140 if (Result) 7141 TypeExpr = ACO->getTrueExpr(); 7142 else 7143 TypeExpr = ACO->getFalseExpr(); 7144 continue; 7145 } 7146 return false; 7147 } 7148 7149 case Stmt::BinaryOperatorClass: { 7150 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 7151 if (BO->getOpcode() == BO_Comma) { 7152 TypeExpr = BO->getRHS(); 7153 continue; 7154 } 7155 return false; 7156 } 7157 7158 default: 7159 return false; 7160 } 7161 } 7162} 7163 7164/// \brief Retrieve the C type corresponding to type tag TypeExpr. 7165/// 7166/// \param TypeExpr Expression that specifies a type tag. 7167/// 7168/// \param MagicValues Registered magic values. 7169/// 7170/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 7171/// kind. 7172/// 7173/// \param TypeInfo Information about the corresponding C type. 7174/// 7175/// \returns true if the corresponding C type was found. 7176bool GetMatchingCType( 7177 const IdentifierInfo *ArgumentKind, 7178 const Expr *TypeExpr, const ASTContext &Ctx, 7179 const llvm::DenseMap<Sema::TypeTagMagicValue, 7180 Sema::TypeTagData> *MagicValues, 7181 bool &FoundWrongKind, 7182 Sema::TypeTagData &TypeInfo) { 7183 FoundWrongKind = false; 7184 7185 // Variable declaration that has type_tag_for_datatype attribute. 7186 const ValueDecl *VD = NULL; 7187 7188 uint64_t MagicValue; 7189 7190 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 7191 return false; 7192 7193 if (VD) { 7194 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7195 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(), 7196 E = VD->specific_attr_end<TypeTagForDatatypeAttr>(); 7197 I != E; ++I) { 7198 if (I->getArgumentKind() != ArgumentKind) { 7199 FoundWrongKind = true; 7200 return false; 7201 } 7202 TypeInfo.Type = I->getMatchingCType(); 7203 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 7204 TypeInfo.MustBeNull = I->getMustBeNull(); 7205 return true; 7206 } 7207 return false; 7208 } 7209 7210 if (!MagicValues) 7211 return false; 7212 7213 llvm::DenseMap<Sema::TypeTagMagicValue, 7214 Sema::TypeTagData>::const_iterator I = 7215 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 7216 if (I == MagicValues->end()) 7217 return false; 7218 7219 TypeInfo = I->second; 7220 return true; 7221} 7222} // unnamed namespace 7223 7224void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 7225 uint64_t MagicValue, QualType Type, 7226 bool LayoutCompatible, 7227 bool MustBeNull) { 7228 if (!TypeTagForDatatypeMagicValues) 7229 TypeTagForDatatypeMagicValues.reset( 7230 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 7231 7232 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 7233 (*TypeTagForDatatypeMagicValues)[Magic] = 7234 TypeTagData(Type, LayoutCompatible, MustBeNull); 7235} 7236 7237namespace { 7238bool IsSameCharType(QualType T1, QualType T2) { 7239 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 7240 if (!BT1) 7241 return false; 7242 7243 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 7244 if (!BT2) 7245 return false; 7246 7247 BuiltinType::Kind T1Kind = BT1->getKind(); 7248 BuiltinType::Kind T2Kind = BT2->getKind(); 7249 7250 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 7251 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 7252 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 7253 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 7254} 7255} // unnamed namespace 7256 7257void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 7258 const Expr * const *ExprArgs) { 7259 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 7260 bool IsPointerAttr = Attr->getIsPointer(); 7261 7262 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 7263 bool FoundWrongKind; 7264 TypeTagData TypeInfo; 7265 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 7266 TypeTagForDatatypeMagicValues.get(), 7267 FoundWrongKind, TypeInfo)) { 7268 if (FoundWrongKind) 7269 Diag(TypeTagExpr->getExprLoc(), 7270 diag::warn_type_tag_for_datatype_wrong_kind) 7271 << TypeTagExpr->getSourceRange(); 7272 return; 7273 } 7274 7275 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 7276 if (IsPointerAttr) { 7277 // Skip implicit cast of pointer to `void *' (as a function argument). 7278 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 7279 if (ICE->getType()->isVoidPointerType() && 7280 ICE->getCastKind() == CK_BitCast) 7281 ArgumentExpr = ICE->getSubExpr(); 7282 } 7283 QualType ArgumentType = ArgumentExpr->getType(); 7284 7285 // Passing a `void*' pointer shouldn't trigger a warning. 7286 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 7287 return; 7288 7289 if (TypeInfo.MustBeNull) { 7290 // Type tag with matching void type requires a null pointer. 7291 if (!ArgumentExpr->isNullPointerConstant(Context, 7292 Expr::NPC_ValueDependentIsNotNull)) { 7293 Diag(ArgumentExpr->getExprLoc(), 7294 diag::warn_type_safety_null_pointer_required) 7295 << ArgumentKind->getName() 7296 << ArgumentExpr->getSourceRange() 7297 << TypeTagExpr->getSourceRange(); 7298 } 7299 return; 7300 } 7301 7302 QualType RequiredType = TypeInfo.Type; 7303 if (IsPointerAttr) 7304 RequiredType = Context.getPointerType(RequiredType); 7305 7306 bool mismatch = false; 7307 if (!TypeInfo.LayoutCompatible) { 7308 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 7309 7310 // C++11 [basic.fundamental] p1: 7311 // Plain char, signed char, and unsigned char are three distinct types. 7312 // 7313 // But we treat plain `char' as equivalent to `signed char' or `unsigned 7314 // char' depending on the current char signedness mode. 7315 if (mismatch) 7316 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 7317 RequiredType->getPointeeType())) || 7318 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 7319 mismatch = false; 7320 } else 7321 if (IsPointerAttr) 7322 mismatch = !isLayoutCompatible(Context, 7323 ArgumentType->getPointeeType(), 7324 RequiredType->getPointeeType()); 7325 else 7326 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 7327 7328 if (mismatch) 7329 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 7330 << ArgumentType << ArgumentKind->getName() 7331 << TypeInfo.LayoutCompatible << RequiredType 7332 << ArgumentExpr->getSourceRange() 7333 << TypeTagExpr->getSourceRange(); 7334} 7335