SemaChecking.cpp revision 2a053a33707eba9e642adedb557b1a6aace103b5
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements extra semantic analysis beyond what is enforced 11// by the C type system. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/Sema.h" 16#include "clang/Sema/SemaInternal.h" 17#include "clang/Sema/ScopeInfo.h" 18#include "clang/Analysis/Analyses/FormatString.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/DeclCXX.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/ExprObjC.h" 25#include "clang/AST/DeclObjC.h" 26#include "clang/AST/StmtCXX.h" 27#include "clang/AST/StmtObjC.h" 28#include "clang/Lex/Preprocessor.h" 29#include "llvm/ADT/BitVector.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/Support/raw_ostream.h" 32#include "clang/Basic/TargetBuiltins.h" 33#include "clang/Basic/TargetInfo.h" 34#include "clang/Basic/ConvertUTF.h" 35#include <limits> 36using namespace clang; 37using namespace sema; 38 39SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 40 unsigned ByteNo) const { 41 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 42 PP.getLangOptions(), PP.getTargetInfo()); 43} 44 45 46/// CheckablePrintfAttr - does a function call have a "printf" attribute 47/// and arguments that merit checking? 48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 49 if (Format->getType() == "printf") return true; 50 if (Format->getType() == "printf0") { 51 // printf0 allows null "format" string; if so don't check format/args 52 unsigned format_idx = Format->getFormatIdx() - 1; 53 // Does the index refer to the implicit object argument? 54 if (isa<CXXMemberCallExpr>(TheCall)) { 55 if (format_idx == 0) 56 return false; 57 --format_idx; 58 } 59 if (format_idx < TheCall->getNumArgs()) { 60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 61 if (!Format->isNullPointerConstant(Context, 62 Expr::NPC_ValueDependentIsNull)) 63 return true; 64 } 65 } 66 return false; 67} 68 69/// Checks that a call expression's argument count is the desired number. 70/// This is useful when doing custom type-checking. Returns true on error. 71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 72 unsigned argCount = call->getNumArgs(); 73 if (argCount == desiredArgCount) return false; 74 75 if (argCount < desiredArgCount) 76 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 77 << 0 /*function call*/ << desiredArgCount << argCount 78 << call->getSourceRange(); 79 80 // Highlight all the excess arguments. 81 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 82 call->getArg(argCount - 1)->getLocEnd()); 83 84 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 85 << 0 /*function call*/ << desiredArgCount << argCount 86 << call->getArg(1)->getSourceRange(); 87} 88 89ExprResult 90Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 91 ExprResult TheCallResult(Owned(TheCall)); 92 93 // Find out if any arguments are required to be integer constant expressions. 94 unsigned ICEArguments = 0; 95 ASTContext::GetBuiltinTypeError Error; 96 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 97 if (Error != ASTContext::GE_None) 98 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 99 100 // If any arguments are required to be ICE's, check and diagnose. 101 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 102 // Skip arguments not required to be ICE's. 103 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 104 105 llvm::APSInt Result; 106 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 107 return true; 108 ICEArguments &= ~(1 << ArgNo); 109 } 110 111 switch (BuiltinID) { 112 case Builtin::BI__builtin___CFStringMakeConstantString: 113 assert(TheCall->getNumArgs() == 1 && 114 "Wrong # arguments to builtin CFStringMakeConstantString"); 115 if (CheckObjCString(TheCall->getArg(0))) 116 return ExprError(); 117 break; 118 case Builtin::BI__builtin_stdarg_start: 119 case Builtin::BI__builtin_va_start: 120 if (SemaBuiltinVAStart(TheCall)) 121 return ExprError(); 122 break; 123 case Builtin::BI__builtin_isgreater: 124 case Builtin::BI__builtin_isgreaterequal: 125 case Builtin::BI__builtin_isless: 126 case Builtin::BI__builtin_islessequal: 127 case Builtin::BI__builtin_islessgreater: 128 case Builtin::BI__builtin_isunordered: 129 if (SemaBuiltinUnorderedCompare(TheCall)) 130 return ExprError(); 131 break; 132 case Builtin::BI__builtin_fpclassify: 133 if (SemaBuiltinFPClassification(TheCall, 6)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_isfinite: 137 case Builtin::BI__builtin_isinf: 138 case Builtin::BI__builtin_isinf_sign: 139 case Builtin::BI__builtin_isnan: 140 case Builtin::BI__builtin_isnormal: 141 if (SemaBuiltinFPClassification(TheCall, 1)) 142 return ExprError(); 143 break; 144 case Builtin::BI__builtin_shufflevector: 145 return SemaBuiltinShuffleVector(TheCall); 146 // TheCall will be freed by the smart pointer here, but that's fine, since 147 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 148 case Builtin::BI__builtin_prefetch: 149 if (SemaBuiltinPrefetch(TheCall)) 150 return ExprError(); 151 break; 152 case Builtin::BI__builtin_object_size: 153 if (SemaBuiltinObjectSize(TheCall)) 154 return ExprError(); 155 break; 156 case Builtin::BI__builtin_longjmp: 157 if (SemaBuiltinLongjmp(TheCall)) 158 return ExprError(); 159 break; 160 161 case Builtin::BI__builtin_classify_type: 162 if (checkArgCount(*this, TheCall, 1)) return true; 163 TheCall->setType(Context.IntTy); 164 break; 165 case Builtin::BI__builtin_constant_p: 166 if (checkArgCount(*this, TheCall, 1)) return true; 167 TheCall->setType(Context.IntTy); 168 break; 169 case Builtin::BI__sync_fetch_and_add: 170 case Builtin::BI__sync_fetch_and_sub: 171 case Builtin::BI__sync_fetch_and_or: 172 case Builtin::BI__sync_fetch_and_and: 173 case Builtin::BI__sync_fetch_and_xor: 174 case Builtin::BI__sync_add_and_fetch: 175 case Builtin::BI__sync_sub_and_fetch: 176 case Builtin::BI__sync_and_and_fetch: 177 case Builtin::BI__sync_or_and_fetch: 178 case Builtin::BI__sync_xor_and_fetch: 179 case Builtin::BI__sync_val_compare_and_swap: 180 case Builtin::BI__sync_bool_compare_and_swap: 181 case Builtin::BI__sync_lock_test_and_set: 182 case Builtin::BI__sync_lock_release: 183 case Builtin::BI__sync_swap: 184 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 185 } 186 187 // Since the target specific builtins for each arch overlap, only check those 188 // of the arch we are compiling for. 189 if (BuiltinID >= Builtin::FirstTSBuiltin) { 190 switch (Context.Target.getTriple().getArch()) { 191 case llvm::Triple::arm: 192 case llvm::Triple::thumb: 193 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 194 return ExprError(); 195 break; 196 default: 197 break; 198 } 199 } 200 201 return move(TheCallResult); 202} 203 204// Get the valid immediate range for the specified NEON type code. 205static unsigned RFT(unsigned t, bool shift = false) { 206 bool quad = t & 0x10; 207 208 switch (t & 0x7) { 209 case 0: // i8 210 return shift ? 7 : (8 << (int)quad) - 1; 211 case 1: // i16 212 return shift ? 15 : (4 << (int)quad) - 1; 213 case 2: // i32 214 return shift ? 31 : (2 << (int)quad) - 1; 215 case 3: // i64 216 return shift ? 63 : (1 << (int)quad) - 1; 217 case 4: // f32 218 assert(!shift && "cannot shift float types!"); 219 return (2 << (int)quad) - 1; 220 case 5: // poly8 221 return shift ? 7 : (8 << (int)quad) - 1; 222 case 6: // poly16 223 return shift ? 15 : (4 << (int)quad) - 1; 224 case 7: // float16 225 assert(!shift && "cannot shift float types!"); 226 return (4 << (int)quad) - 1; 227 } 228 return 0; 229} 230 231bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 232 llvm::APSInt Result; 233 234 unsigned mask = 0; 235 unsigned TV = 0; 236 switch (BuiltinID) { 237#define GET_NEON_OVERLOAD_CHECK 238#include "clang/Basic/arm_neon.inc" 239#undef GET_NEON_OVERLOAD_CHECK 240 } 241 242 // For NEON intrinsics which are overloaded on vector element type, validate 243 // the immediate which specifies which variant to emit. 244 if (mask) { 245 unsigned ArgNo = TheCall->getNumArgs()-1; 246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 247 return true; 248 249 TV = Result.getLimitedValue(32); 250 if ((TV > 31) || (mask & (1 << TV)) == 0) 251 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 252 << TheCall->getArg(ArgNo)->getSourceRange(); 253 } 254 255 // For NEON intrinsics which take an immediate value as part of the 256 // instruction, range check them here. 257 unsigned i = 0, l = 0, u = 0; 258 switch (BuiltinID) { 259 default: return false; 260 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 261 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 262 case ARM::BI__builtin_arm_vcvtr_f: 263 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 264#define GET_NEON_IMMEDIATE_CHECK 265#include "clang/Basic/arm_neon.inc" 266#undef GET_NEON_IMMEDIATE_CHECK 267 }; 268 269 // Check that the immediate argument is actually a constant. 270 if (SemaBuiltinConstantArg(TheCall, i, Result)) 271 return true; 272 273 // Range check against the upper/lower values for this isntruction. 274 unsigned Val = Result.getZExtValue(); 275 if (Val < l || Val > (u + l)) 276 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 277 << l << u+l << TheCall->getArg(i)->getSourceRange(); 278 279 // FIXME: VFP Intrinsics should error if VFP not present. 280 return false; 281} 282 283/// CheckFunctionCall - Check a direct function call for various correctness 284/// and safety properties not strictly enforced by the C type system. 285bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 286 // Get the IdentifierInfo* for the called function. 287 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 288 289 // None of the checks below are needed for functions that don't have 290 // simple names (e.g., C++ conversion functions). 291 if (!FnInfo) 292 return false; 293 294 // FIXME: This mechanism should be abstracted to be less fragile and 295 // more efficient. For example, just map function ids to custom 296 // handlers. 297 298 // Printf and scanf checking. 299 for (specific_attr_iterator<FormatAttr> 300 i = FDecl->specific_attr_begin<FormatAttr>(), 301 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 302 303 const FormatAttr *Format = *i; 304 const bool b = Format->getType() == "scanf"; 305 if (b || CheckablePrintfAttr(Format, TheCall)) { 306 bool HasVAListArg = Format->getFirstArg() == 0; 307 CheckPrintfScanfArguments(TheCall, HasVAListArg, 308 Format->getFormatIdx() - 1, 309 HasVAListArg ? 0 : Format->getFirstArg() - 1, 310 !b); 311 } 312 } 313 314 for (specific_attr_iterator<NonNullAttr> 315 i = FDecl->specific_attr_begin<NonNullAttr>(), 316 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 317 CheckNonNullArguments(*i, TheCall->getArgs(), 318 TheCall->getCallee()->getLocStart()); 319 } 320 321 // Memset handling 322 if (FnInfo->isStr("memset") && 323 FDecl->getLinkage() == ExternalLinkage && 324 (!getLangOptions().CPlusPlus || FDecl->isExternC())) 325 CheckMemsetArguments(TheCall); 326 327 return false; 328} 329 330bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 331 // Printf checking. 332 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 333 if (!Format) 334 return false; 335 336 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 337 if (!V) 338 return false; 339 340 QualType Ty = V->getType(); 341 if (!Ty->isBlockPointerType()) 342 return false; 343 344 const bool b = Format->getType() == "scanf"; 345 if (!b && !CheckablePrintfAttr(Format, TheCall)) 346 return false; 347 348 bool HasVAListArg = Format->getFirstArg() == 0; 349 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 350 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b); 351 352 return false; 353} 354 355/// SemaBuiltinAtomicOverloaded - We have a call to a function like 356/// __sync_fetch_and_add, which is an overloaded function based on the pointer 357/// type of its first argument. The main ActOnCallExpr routines have already 358/// promoted the types of arguments because all of these calls are prototyped as 359/// void(...). 360/// 361/// This function goes through and does final semantic checking for these 362/// builtins, 363ExprResult 364Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 365 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 366 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 367 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 368 369 // Ensure that we have at least one argument to do type inference from. 370 if (TheCall->getNumArgs() < 1) { 371 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 372 << 0 << 1 << TheCall->getNumArgs() 373 << TheCall->getCallee()->getSourceRange(); 374 return ExprError(); 375 } 376 377 // Inspect the first argument of the atomic builtin. This should always be 378 // a pointer type, whose element is an integral scalar or pointer type. 379 // Because it is a pointer type, we don't have to worry about any implicit 380 // casts here. 381 // FIXME: We don't allow floating point scalars as input. 382 Expr *FirstArg = TheCall->getArg(0); 383 if (!FirstArg->getType()->isPointerType()) { 384 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 385 << FirstArg->getType() << FirstArg->getSourceRange(); 386 return ExprError(); 387 } 388 389 QualType ValType = 390 FirstArg->getType()->getAs<PointerType>()->getPointeeType(); 391 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 392 !ValType->isBlockPointerType()) { 393 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 394 << FirstArg->getType() << FirstArg->getSourceRange(); 395 return ExprError(); 396 } 397 398 // The majority of builtins return a value, but a few have special return 399 // types, so allow them to override appropriately below. 400 QualType ResultType = ValType; 401 402 // We need to figure out which concrete builtin this maps onto. For example, 403 // __sync_fetch_and_add with a 2 byte object turns into 404 // __sync_fetch_and_add_2. 405#define BUILTIN_ROW(x) \ 406 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 407 Builtin::BI##x##_8, Builtin::BI##x##_16 } 408 409 static const unsigned BuiltinIndices[][5] = { 410 BUILTIN_ROW(__sync_fetch_and_add), 411 BUILTIN_ROW(__sync_fetch_and_sub), 412 BUILTIN_ROW(__sync_fetch_and_or), 413 BUILTIN_ROW(__sync_fetch_and_and), 414 BUILTIN_ROW(__sync_fetch_and_xor), 415 416 BUILTIN_ROW(__sync_add_and_fetch), 417 BUILTIN_ROW(__sync_sub_and_fetch), 418 BUILTIN_ROW(__sync_and_and_fetch), 419 BUILTIN_ROW(__sync_or_and_fetch), 420 BUILTIN_ROW(__sync_xor_and_fetch), 421 422 BUILTIN_ROW(__sync_val_compare_and_swap), 423 BUILTIN_ROW(__sync_bool_compare_and_swap), 424 BUILTIN_ROW(__sync_lock_test_and_set), 425 BUILTIN_ROW(__sync_lock_release), 426 BUILTIN_ROW(__sync_swap) 427 }; 428#undef BUILTIN_ROW 429 430 // Determine the index of the size. 431 unsigned SizeIndex; 432 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 433 case 1: SizeIndex = 0; break; 434 case 2: SizeIndex = 1; break; 435 case 4: SizeIndex = 2; break; 436 case 8: SizeIndex = 3; break; 437 case 16: SizeIndex = 4; break; 438 default: 439 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 440 << FirstArg->getType() << FirstArg->getSourceRange(); 441 return ExprError(); 442 } 443 444 // Each of these builtins has one pointer argument, followed by some number of 445 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 446 // that we ignore. Find out which row of BuiltinIndices to read from as well 447 // as the number of fixed args. 448 unsigned BuiltinID = FDecl->getBuiltinID(); 449 unsigned BuiltinIndex, NumFixed = 1; 450 switch (BuiltinID) { 451 default: assert(0 && "Unknown overloaded atomic builtin!"); 452 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 453 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 454 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 455 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 456 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 457 458 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break; 459 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break; 460 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break; 461 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break; 462 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break; 463 464 case Builtin::BI__sync_val_compare_and_swap: 465 BuiltinIndex = 10; 466 NumFixed = 2; 467 break; 468 case Builtin::BI__sync_bool_compare_and_swap: 469 BuiltinIndex = 11; 470 NumFixed = 2; 471 ResultType = Context.BoolTy; 472 break; 473 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break; 474 case Builtin::BI__sync_lock_release: 475 BuiltinIndex = 13; 476 NumFixed = 0; 477 ResultType = Context.VoidTy; 478 break; 479 case Builtin::BI__sync_swap: BuiltinIndex = 14; break; 480 } 481 482 // Now that we know how many fixed arguments we expect, first check that we 483 // have at least that many. 484 if (TheCall->getNumArgs() < 1+NumFixed) { 485 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 486 << 0 << 1+NumFixed << TheCall->getNumArgs() 487 << TheCall->getCallee()->getSourceRange(); 488 return ExprError(); 489 } 490 491 // Get the decl for the concrete builtin from this, we can tell what the 492 // concrete integer type we should convert to is. 493 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 494 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 495 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 496 FunctionDecl *NewBuiltinDecl = 497 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 498 TUScope, false, DRE->getLocStart())); 499 500 // The first argument --- the pointer --- has a fixed type; we 501 // deduce the types of the rest of the arguments accordingly. Walk 502 // the remaining arguments, converting them to the deduced value type. 503 for (unsigned i = 0; i != NumFixed; ++i) { 504 ExprResult Arg = TheCall->getArg(i+1); 505 506 // If the argument is an implicit cast, then there was a promotion due to 507 // "...", just remove it now. 508 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) { 509 Arg = ICE->getSubExpr(); 510 ICE->setSubExpr(0); 511 TheCall->setArg(i+1, Arg.get()); 512 } 513 514 // GCC does an implicit conversion to the pointer or integer ValType. This 515 // can fail in some cases (1i -> int**), check for this error case now. 516 CastKind Kind = CK_Invalid; 517 ExprValueKind VK = VK_RValue; 518 CXXCastPath BasePath; 519 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath); 520 if (Arg.isInvalid()) 521 return ExprError(); 522 523 // Okay, we have something that *can* be converted to the right type. Check 524 // to see if there is a potentially weird extension going on here. This can 525 // happen when you do an atomic operation on something like an char* and 526 // pass in 42. The 42 gets converted to char. This is even more strange 527 // for things like 45.123 -> char, etc. 528 // FIXME: Do this check. 529 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath); 530 TheCall->setArg(i+1, Arg.get()); 531 } 532 533 // Switch the DeclRefExpr to refer to the new decl. 534 DRE->setDecl(NewBuiltinDecl); 535 DRE->setType(NewBuiltinDecl->getType()); 536 537 // Set the callee in the CallExpr. 538 // FIXME: This leaks the original parens and implicit casts. 539 ExprResult PromotedCall = UsualUnaryConversions(DRE); 540 if (PromotedCall.isInvalid()) 541 return ExprError(); 542 TheCall->setCallee(PromotedCall.take()); 543 544 // Change the result type of the call to match the original value type. This 545 // is arbitrary, but the codegen for these builtins ins design to handle it 546 // gracefully. 547 TheCall->setType(ResultType); 548 549 return move(TheCallResult); 550} 551 552 553/// CheckObjCString - Checks that the argument to the builtin 554/// CFString constructor is correct 555/// Note: It might also make sense to do the UTF-16 conversion here (would 556/// simplify the backend). 557bool Sema::CheckObjCString(Expr *Arg) { 558 Arg = Arg->IgnoreParenCasts(); 559 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 560 561 if (!Literal || Literal->isWide()) { 562 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 563 << Arg->getSourceRange(); 564 return true; 565 } 566 567 if (Literal->containsNonAsciiOrNull()) { 568 llvm::StringRef String = Literal->getString(); 569 unsigned NumBytes = String.size(); 570 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 571 const UTF8 *FromPtr = (UTF8 *)String.data(); 572 UTF16 *ToPtr = &ToBuf[0]; 573 574 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 575 &ToPtr, ToPtr + NumBytes, 576 strictConversion); 577 // Check for conversion failure. 578 if (Result != conversionOK) 579 Diag(Arg->getLocStart(), 580 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 581 } 582 return false; 583} 584 585/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 586/// Emit an error and return true on failure, return false on success. 587bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 588 Expr *Fn = TheCall->getCallee(); 589 if (TheCall->getNumArgs() > 2) { 590 Diag(TheCall->getArg(2)->getLocStart(), 591 diag::err_typecheck_call_too_many_args) 592 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 593 << Fn->getSourceRange() 594 << SourceRange(TheCall->getArg(2)->getLocStart(), 595 (*(TheCall->arg_end()-1))->getLocEnd()); 596 return true; 597 } 598 599 if (TheCall->getNumArgs() < 2) { 600 return Diag(TheCall->getLocEnd(), 601 diag::err_typecheck_call_too_few_args_at_least) 602 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 603 } 604 605 // Determine whether the current function is variadic or not. 606 BlockScopeInfo *CurBlock = getCurBlock(); 607 bool isVariadic; 608 if (CurBlock) 609 isVariadic = CurBlock->TheDecl->isVariadic(); 610 else if (FunctionDecl *FD = getCurFunctionDecl()) 611 isVariadic = FD->isVariadic(); 612 else 613 isVariadic = getCurMethodDecl()->isVariadic(); 614 615 if (!isVariadic) { 616 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 617 return true; 618 } 619 620 // Verify that the second argument to the builtin is the last argument of the 621 // current function or method. 622 bool SecondArgIsLastNamedArgument = false; 623 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 624 625 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 626 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 627 // FIXME: This isn't correct for methods (results in bogus warning). 628 // Get the last formal in the current function. 629 const ParmVarDecl *LastArg; 630 if (CurBlock) 631 LastArg = *(CurBlock->TheDecl->param_end()-1); 632 else if (FunctionDecl *FD = getCurFunctionDecl()) 633 LastArg = *(FD->param_end()-1); 634 else 635 LastArg = *(getCurMethodDecl()->param_end()-1); 636 SecondArgIsLastNamedArgument = PV == LastArg; 637 } 638 } 639 640 if (!SecondArgIsLastNamedArgument) 641 Diag(TheCall->getArg(1)->getLocStart(), 642 diag::warn_second_parameter_of_va_start_not_last_named_argument); 643 return false; 644} 645 646/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 647/// friends. This is declared to take (...), so we have to check everything. 648bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 649 if (TheCall->getNumArgs() < 2) 650 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 651 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 652 if (TheCall->getNumArgs() > 2) 653 return Diag(TheCall->getArg(2)->getLocStart(), 654 diag::err_typecheck_call_too_many_args) 655 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 656 << SourceRange(TheCall->getArg(2)->getLocStart(), 657 (*(TheCall->arg_end()-1))->getLocEnd()); 658 659 ExprResult OrigArg0 = TheCall->getArg(0); 660 ExprResult OrigArg1 = TheCall->getArg(1); 661 662 // Do standard promotions between the two arguments, returning their common 663 // type. 664 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 665 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 666 return true; 667 668 // Make sure any conversions are pushed back into the call; this is 669 // type safe since unordered compare builtins are declared as "_Bool 670 // foo(...)". 671 TheCall->setArg(0, OrigArg0.get()); 672 TheCall->setArg(1, OrigArg1.get()); 673 674 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 675 return false; 676 677 // If the common type isn't a real floating type, then the arguments were 678 // invalid for this operation. 679 if (!Res->isRealFloatingType()) 680 return Diag(OrigArg0.get()->getLocStart(), 681 diag::err_typecheck_call_invalid_ordered_compare) 682 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 683 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 684 685 return false; 686} 687 688/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 689/// __builtin_isnan and friends. This is declared to take (...), so we have 690/// to check everything. We expect the last argument to be a floating point 691/// value. 692bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 693 if (TheCall->getNumArgs() < NumArgs) 694 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 695 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 696 if (TheCall->getNumArgs() > NumArgs) 697 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 698 diag::err_typecheck_call_too_many_args) 699 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 700 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 701 (*(TheCall->arg_end()-1))->getLocEnd()); 702 703 Expr *OrigArg = TheCall->getArg(NumArgs-1); 704 705 if (OrigArg->isTypeDependent()) 706 return false; 707 708 // This operation requires a non-_Complex floating-point number. 709 if (!OrigArg->getType()->isRealFloatingType()) 710 return Diag(OrigArg->getLocStart(), 711 diag::err_typecheck_call_invalid_unary_fp) 712 << OrigArg->getType() << OrigArg->getSourceRange(); 713 714 // If this is an implicit conversion from float -> double, remove it. 715 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 716 Expr *CastArg = Cast->getSubExpr(); 717 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 718 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 719 "promotion from float to double is the only expected cast here"); 720 Cast->setSubExpr(0); 721 TheCall->setArg(NumArgs-1, CastArg); 722 OrigArg = CastArg; 723 } 724 } 725 726 return false; 727} 728 729/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 730// This is declared to take (...), so we have to check everything. 731ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 732 if (TheCall->getNumArgs() < 2) 733 return ExprError(Diag(TheCall->getLocEnd(), 734 diag::err_typecheck_call_too_few_args_at_least) 735 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 736 << TheCall->getSourceRange()); 737 738 // Determine which of the following types of shufflevector we're checking: 739 // 1) unary, vector mask: (lhs, mask) 740 // 2) binary, vector mask: (lhs, rhs, mask) 741 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 742 QualType resType = TheCall->getArg(0)->getType(); 743 unsigned numElements = 0; 744 745 if (!TheCall->getArg(0)->isTypeDependent() && 746 !TheCall->getArg(1)->isTypeDependent()) { 747 QualType LHSType = TheCall->getArg(0)->getType(); 748 QualType RHSType = TheCall->getArg(1)->getType(); 749 750 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 751 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 752 << SourceRange(TheCall->getArg(0)->getLocStart(), 753 TheCall->getArg(1)->getLocEnd()); 754 return ExprError(); 755 } 756 757 numElements = LHSType->getAs<VectorType>()->getNumElements(); 758 unsigned numResElements = TheCall->getNumArgs() - 2; 759 760 // Check to see if we have a call with 2 vector arguments, the unary shuffle 761 // with mask. If so, verify that RHS is an integer vector type with the 762 // same number of elts as lhs. 763 if (TheCall->getNumArgs() == 2) { 764 if (!RHSType->hasIntegerRepresentation() || 765 RHSType->getAs<VectorType>()->getNumElements() != numElements) 766 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 767 << SourceRange(TheCall->getArg(1)->getLocStart(), 768 TheCall->getArg(1)->getLocEnd()); 769 numResElements = numElements; 770 } 771 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 772 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 773 << SourceRange(TheCall->getArg(0)->getLocStart(), 774 TheCall->getArg(1)->getLocEnd()); 775 return ExprError(); 776 } else if (numElements != numResElements) { 777 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 778 resType = Context.getVectorType(eltType, numResElements, 779 VectorType::GenericVector); 780 } 781 } 782 783 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 784 if (TheCall->getArg(i)->isTypeDependent() || 785 TheCall->getArg(i)->isValueDependent()) 786 continue; 787 788 llvm::APSInt Result(32); 789 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 790 return ExprError(Diag(TheCall->getLocStart(), 791 diag::err_shufflevector_nonconstant_argument) 792 << TheCall->getArg(i)->getSourceRange()); 793 794 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 795 return ExprError(Diag(TheCall->getLocStart(), 796 diag::err_shufflevector_argument_too_large) 797 << TheCall->getArg(i)->getSourceRange()); 798 } 799 800 llvm::SmallVector<Expr*, 32> exprs; 801 802 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 803 exprs.push_back(TheCall->getArg(i)); 804 TheCall->setArg(i, 0); 805 } 806 807 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 808 exprs.size(), resType, 809 TheCall->getCallee()->getLocStart(), 810 TheCall->getRParenLoc())); 811} 812 813/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 814// This is declared to take (const void*, ...) and can take two 815// optional constant int args. 816bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 817 unsigned NumArgs = TheCall->getNumArgs(); 818 819 if (NumArgs > 3) 820 return Diag(TheCall->getLocEnd(), 821 diag::err_typecheck_call_too_many_args_at_most) 822 << 0 /*function call*/ << 3 << NumArgs 823 << TheCall->getSourceRange(); 824 825 // Argument 0 is checked for us and the remaining arguments must be 826 // constant integers. 827 for (unsigned i = 1; i != NumArgs; ++i) { 828 Expr *Arg = TheCall->getArg(i); 829 830 llvm::APSInt Result; 831 if (SemaBuiltinConstantArg(TheCall, i, Result)) 832 return true; 833 834 // FIXME: gcc issues a warning and rewrites these to 0. These 835 // seems especially odd for the third argument since the default 836 // is 3. 837 if (i == 1) { 838 if (Result.getLimitedValue() > 1) 839 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 840 << "0" << "1" << Arg->getSourceRange(); 841 } else { 842 if (Result.getLimitedValue() > 3) 843 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 844 << "0" << "3" << Arg->getSourceRange(); 845 } 846 } 847 848 return false; 849} 850 851/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 852/// TheCall is a constant expression. 853bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 854 llvm::APSInt &Result) { 855 Expr *Arg = TheCall->getArg(ArgNum); 856 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 857 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 858 859 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 860 861 if (!Arg->isIntegerConstantExpr(Result, Context)) 862 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 863 << FDecl->getDeclName() << Arg->getSourceRange(); 864 865 return false; 866} 867 868/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 869/// int type). This simply type checks that type is one of the defined 870/// constants (0-3). 871// For compatibility check 0-3, llvm only handles 0 and 2. 872bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 873 llvm::APSInt Result; 874 875 // Check constant-ness first. 876 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 877 return true; 878 879 Expr *Arg = TheCall->getArg(1); 880 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 881 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 882 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 883 } 884 885 return false; 886} 887 888/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 889/// This checks that val is a constant 1. 890bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 891 Expr *Arg = TheCall->getArg(1); 892 llvm::APSInt Result; 893 894 // TODO: This is less than ideal. Overload this to take a value. 895 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 896 return true; 897 898 if (Result != 1) 899 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 900 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 901 902 return false; 903} 904 905// Handle i > 1 ? "x" : "y", recursively. 906bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 907 bool HasVAListArg, 908 unsigned format_idx, unsigned firstDataArg, 909 bool isPrintf) { 910 tryAgain: 911 if (E->isTypeDependent() || E->isValueDependent()) 912 return false; 913 914 E = E->IgnoreParens(); 915 916 switch (E->getStmtClass()) { 917 case Stmt::BinaryConditionalOperatorClass: 918 case Stmt::ConditionalOperatorClass: { 919 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 920 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg, 921 format_idx, firstDataArg, isPrintf) 922 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg, 923 format_idx, firstDataArg, isPrintf); 924 } 925 926 case Stmt::IntegerLiteralClass: 927 // Technically -Wformat-nonliteral does not warn about this case. 928 // The behavior of printf and friends in this case is implementation 929 // dependent. Ideally if the format string cannot be null then 930 // it should have a 'nonnull' attribute in the function prototype. 931 return true; 932 933 case Stmt::ImplicitCastExprClass: { 934 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 935 goto tryAgain; 936 } 937 938 case Stmt::OpaqueValueExprClass: 939 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 940 E = src; 941 goto tryAgain; 942 } 943 return false; 944 945 case Stmt::PredefinedExprClass: 946 // While __func__, etc., are technically not string literals, they 947 // cannot contain format specifiers and thus are not a security 948 // liability. 949 return true; 950 951 case Stmt::DeclRefExprClass: { 952 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 953 954 // As an exception, do not flag errors for variables binding to 955 // const string literals. 956 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 957 bool isConstant = false; 958 QualType T = DR->getType(); 959 960 if (const ArrayType *AT = Context.getAsArrayType(T)) { 961 isConstant = AT->getElementType().isConstant(Context); 962 } else if (const PointerType *PT = T->getAs<PointerType>()) { 963 isConstant = T.isConstant(Context) && 964 PT->getPointeeType().isConstant(Context); 965 } 966 967 if (isConstant) { 968 if (const Expr *Init = VD->getAnyInitializer()) 969 return SemaCheckStringLiteral(Init, TheCall, 970 HasVAListArg, format_idx, firstDataArg, 971 isPrintf); 972 } 973 974 // For vprintf* functions (i.e., HasVAListArg==true), we add a 975 // special check to see if the format string is a function parameter 976 // of the function calling the printf function. If the function 977 // has an attribute indicating it is a printf-like function, then we 978 // should suppress warnings concerning non-literals being used in a call 979 // to a vprintf function. For example: 980 // 981 // void 982 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 983 // va_list ap; 984 // va_start(ap, fmt); 985 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 986 // ... 987 // 988 // 989 // FIXME: We don't have full attribute support yet, so just check to see 990 // if the argument is a DeclRefExpr that references a parameter. We'll 991 // add proper support for checking the attribute later. 992 if (HasVAListArg) 993 if (isa<ParmVarDecl>(VD)) 994 return true; 995 } 996 997 return false; 998 } 999 1000 case Stmt::CallExprClass: { 1001 const CallExpr *CE = cast<CallExpr>(E); 1002 if (const ImplicitCastExpr *ICE 1003 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 1004 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1006 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 1007 unsigned ArgIndex = FA->getFormatIdx(); 1008 const Expr *Arg = CE->getArg(ArgIndex - 1); 1009 1010 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 1011 format_idx, firstDataArg, isPrintf); 1012 } 1013 } 1014 } 1015 } 1016 1017 return false; 1018 } 1019 case Stmt::ObjCStringLiteralClass: 1020 case Stmt::StringLiteralClass: { 1021 const StringLiteral *StrE = NULL; 1022 1023 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1024 StrE = ObjCFExpr->getString(); 1025 else 1026 StrE = cast<StringLiteral>(E); 1027 1028 if (StrE) { 1029 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx, 1030 firstDataArg, isPrintf); 1031 return true; 1032 } 1033 1034 return false; 1035 } 1036 1037 default: 1038 return false; 1039 } 1040} 1041 1042void 1043Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1044 const Expr * const *ExprArgs, 1045 SourceLocation CallSiteLoc) { 1046 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1047 e = NonNull->args_end(); 1048 i != e; ++i) { 1049 const Expr *ArgExpr = ExprArgs[*i]; 1050 if (ArgExpr->isNullPointerConstant(Context, 1051 Expr::NPC_ValueDependentIsNotNull)) 1052 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1053 } 1054} 1055 1056/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1057/// functions) for correct use of format strings. 1058void 1059Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 1060 unsigned format_idx, unsigned firstDataArg, 1061 bool isPrintf) { 1062 1063 const Expr *Fn = TheCall->getCallee(); 1064 1065 // The way the format attribute works in GCC, the implicit this argument 1066 // of member functions is counted. However, it doesn't appear in our own 1067 // lists, so decrement format_idx in that case. 1068 if (isa<CXXMemberCallExpr>(TheCall)) { 1069 const CXXMethodDecl *method_decl = 1070 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1071 if (method_decl && method_decl->isInstance()) { 1072 // Catch a format attribute mistakenly referring to the object argument. 1073 if (format_idx == 0) 1074 return; 1075 --format_idx; 1076 if(firstDataArg != 0) 1077 --firstDataArg; 1078 } 1079 } 1080 1081 // CHECK: printf/scanf-like function is called with no format string. 1082 if (format_idx >= TheCall->getNumArgs()) { 1083 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string) 1084 << Fn->getSourceRange(); 1085 return; 1086 } 1087 1088 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 1089 1090 // CHECK: format string is not a string literal. 1091 // 1092 // Dynamically generated format strings are difficult to 1093 // automatically vet at compile time. Requiring that format strings 1094 // are string literals: (1) permits the checking of format strings by 1095 // the compiler and thereby (2) can practically remove the source of 1096 // many format string exploits. 1097 1098 // Format string can be either ObjC string (e.g. @"%d") or 1099 // C string (e.g. "%d") 1100 // ObjC string uses the same format specifiers as C string, so we can use 1101 // the same format string checking logic for both ObjC and C strings. 1102 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1103 firstDataArg, isPrintf)) 1104 return; // Literal format string found, check done! 1105 1106 // If there are no arguments specified, warn with -Wformat-security, otherwise 1107 // warn only with -Wformat-nonliteral. 1108 if (TheCall->getNumArgs() == format_idx+1) 1109 Diag(TheCall->getArg(format_idx)->getLocStart(), 1110 diag::warn_format_nonliteral_noargs) 1111 << OrigFormatExpr->getSourceRange(); 1112 else 1113 Diag(TheCall->getArg(format_idx)->getLocStart(), 1114 diag::warn_format_nonliteral) 1115 << OrigFormatExpr->getSourceRange(); 1116} 1117 1118namespace { 1119class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1120protected: 1121 Sema &S; 1122 const StringLiteral *FExpr; 1123 const Expr *OrigFormatExpr; 1124 const unsigned FirstDataArg; 1125 const unsigned NumDataArgs; 1126 const bool IsObjCLiteral; 1127 const char *Beg; // Start of format string. 1128 const bool HasVAListArg; 1129 const CallExpr *TheCall; 1130 unsigned FormatIdx; 1131 llvm::BitVector CoveredArgs; 1132 bool usesPositionalArgs; 1133 bool atFirstArg; 1134public: 1135 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1136 const Expr *origFormatExpr, unsigned firstDataArg, 1137 unsigned numDataArgs, bool isObjCLiteral, 1138 const char *beg, bool hasVAListArg, 1139 const CallExpr *theCall, unsigned formatIdx) 1140 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1141 FirstDataArg(firstDataArg), 1142 NumDataArgs(numDataArgs), 1143 IsObjCLiteral(isObjCLiteral), Beg(beg), 1144 HasVAListArg(hasVAListArg), 1145 TheCall(theCall), FormatIdx(formatIdx), 1146 usesPositionalArgs(false), atFirstArg(true) { 1147 CoveredArgs.resize(numDataArgs); 1148 CoveredArgs.reset(); 1149 } 1150 1151 void DoneProcessing(); 1152 1153 void HandleIncompleteSpecifier(const char *startSpecifier, 1154 unsigned specifierLen); 1155 1156 virtual void HandleInvalidPosition(const char *startSpecifier, 1157 unsigned specifierLen, 1158 analyze_format_string::PositionContext p); 1159 1160 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1161 1162 void HandleNullChar(const char *nullCharacter); 1163 1164protected: 1165 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1166 const char *startSpec, 1167 unsigned specifierLen, 1168 const char *csStart, unsigned csLen); 1169 1170 SourceRange getFormatStringRange(); 1171 CharSourceRange getSpecifierRange(const char *startSpecifier, 1172 unsigned specifierLen); 1173 SourceLocation getLocationOfByte(const char *x); 1174 1175 const Expr *getDataArg(unsigned i) const; 1176 1177 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1178 const analyze_format_string::ConversionSpecifier &CS, 1179 const char *startSpecifier, unsigned specifierLen, 1180 unsigned argIndex); 1181}; 1182} 1183 1184SourceRange CheckFormatHandler::getFormatStringRange() { 1185 return OrigFormatExpr->getSourceRange(); 1186} 1187 1188CharSourceRange CheckFormatHandler:: 1189getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1190 SourceLocation Start = getLocationOfByte(startSpecifier); 1191 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1192 1193 // Advance the end SourceLocation by one due to half-open ranges. 1194 End = End.getFileLocWithOffset(1); 1195 1196 return CharSourceRange::getCharRange(Start, End); 1197} 1198 1199SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1200 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1201} 1202 1203void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1204 unsigned specifierLen){ 1205 SourceLocation Loc = getLocationOfByte(startSpecifier); 1206 S.Diag(Loc, diag::warn_printf_incomplete_specifier) 1207 << getSpecifierRange(startSpecifier, specifierLen); 1208} 1209 1210void 1211CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1212 analyze_format_string::PositionContext p) { 1213 SourceLocation Loc = getLocationOfByte(startPos); 1214 S.Diag(Loc, diag::warn_format_invalid_positional_specifier) 1215 << (unsigned) p << getSpecifierRange(startPos, posLen); 1216} 1217 1218void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1219 unsigned posLen) { 1220 SourceLocation Loc = getLocationOfByte(startPos); 1221 S.Diag(Loc, diag::warn_format_zero_positional_specifier) 1222 << getSpecifierRange(startPos, posLen); 1223} 1224 1225void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1226 if (!IsObjCLiteral) { 1227 // The presence of a null character is likely an error. 1228 S.Diag(getLocationOfByte(nullCharacter), 1229 diag::warn_printf_format_string_contains_null_char) 1230 << getFormatStringRange(); 1231 } 1232} 1233 1234const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1235 return TheCall->getArg(FirstDataArg + i); 1236} 1237 1238void CheckFormatHandler::DoneProcessing() { 1239 // Does the number of data arguments exceed the number of 1240 // format conversions in the format string? 1241 if (!HasVAListArg) { 1242 // Find any arguments that weren't covered. 1243 CoveredArgs.flip(); 1244 signed notCoveredArg = CoveredArgs.find_first(); 1245 if (notCoveredArg >= 0) { 1246 assert((unsigned)notCoveredArg < NumDataArgs); 1247 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(), 1248 diag::warn_printf_data_arg_not_used) 1249 << getFormatStringRange(); 1250 } 1251 } 1252} 1253 1254bool 1255CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1256 SourceLocation Loc, 1257 const char *startSpec, 1258 unsigned specifierLen, 1259 const char *csStart, 1260 unsigned csLen) { 1261 1262 bool keepGoing = true; 1263 if (argIndex < NumDataArgs) { 1264 // Consider the argument coverered, even though the specifier doesn't 1265 // make sense. 1266 CoveredArgs.set(argIndex); 1267 } 1268 else { 1269 // If argIndex exceeds the number of data arguments we 1270 // don't issue a warning because that is just a cascade of warnings (and 1271 // they may have intended '%%' anyway). We don't want to continue processing 1272 // the format string after this point, however, as we will like just get 1273 // gibberish when trying to match arguments. 1274 keepGoing = false; 1275 } 1276 1277 S.Diag(Loc, diag::warn_format_invalid_conversion) 1278 << llvm::StringRef(csStart, csLen) 1279 << getSpecifierRange(startSpec, specifierLen); 1280 1281 return keepGoing; 1282} 1283 1284bool 1285CheckFormatHandler::CheckNumArgs( 1286 const analyze_format_string::FormatSpecifier &FS, 1287 const analyze_format_string::ConversionSpecifier &CS, 1288 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1289 1290 if (argIndex >= NumDataArgs) { 1291 if (FS.usesPositionalArg()) { 1292 S.Diag(getLocationOfByte(CS.getStart()), 1293 diag::warn_printf_positional_arg_exceeds_data_args) 1294 << (argIndex+1) << NumDataArgs 1295 << getSpecifierRange(startSpecifier, specifierLen); 1296 } 1297 else { 1298 S.Diag(getLocationOfByte(CS.getStart()), 1299 diag::warn_printf_insufficient_data_args) 1300 << getSpecifierRange(startSpecifier, specifierLen); 1301 } 1302 1303 return false; 1304 } 1305 return true; 1306} 1307 1308//===--- CHECK: Printf format string checking ------------------------------===// 1309 1310namespace { 1311class CheckPrintfHandler : public CheckFormatHandler { 1312public: 1313 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1314 const Expr *origFormatExpr, unsigned firstDataArg, 1315 unsigned numDataArgs, bool isObjCLiteral, 1316 const char *beg, bool hasVAListArg, 1317 const CallExpr *theCall, unsigned formatIdx) 1318 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1319 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1320 theCall, formatIdx) {} 1321 1322 1323 bool HandleInvalidPrintfConversionSpecifier( 1324 const analyze_printf::PrintfSpecifier &FS, 1325 const char *startSpecifier, 1326 unsigned specifierLen); 1327 1328 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1329 const char *startSpecifier, 1330 unsigned specifierLen); 1331 1332 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1333 const char *startSpecifier, unsigned specifierLen); 1334 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1335 const analyze_printf::OptionalAmount &Amt, 1336 unsigned type, 1337 const char *startSpecifier, unsigned specifierLen); 1338 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1339 const analyze_printf::OptionalFlag &flag, 1340 const char *startSpecifier, unsigned specifierLen); 1341 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1342 const analyze_printf::OptionalFlag &ignoredFlag, 1343 const analyze_printf::OptionalFlag &flag, 1344 const char *startSpecifier, unsigned specifierLen); 1345}; 1346} 1347 1348bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1349 const analyze_printf::PrintfSpecifier &FS, 1350 const char *startSpecifier, 1351 unsigned specifierLen) { 1352 const analyze_printf::PrintfConversionSpecifier &CS = 1353 FS.getConversionSpecifier(); 1354 1355 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1356 getLocationOfByte(CS.getStart()), 1357 startSpecifier, specifierLen, 1358 CS.getStart(), CS.getLength()); 1359} 1360 1361bool CheckPrintfHandler::HandleAmount( 1362 const analyze_format_string::OptionalAmount &Amt, 1363 unsigned k, const char *startSpecifier, 1364 unsigned specifierLen) { 1365 1366 if (Amt.hasDataArgument()) { 1367 if (!HasVAListArg) { 1368 unsigned argIndex = Amt.getArgIndex(); 1369 if (argIndex >= NumDataArgs) { 1370 S.Diag(getLocationOfByte(Amt.getStart()), 1371 diag::warn_printf_asterisk_missing_arg) 1372 << k << getSpecifierRange(startSpecifier, specifierLen); 1373 // Don't do any more checking. We will just emit 1374 // spurious errors. 1375 return false; 1376 } 1377 1378 // Type check the data argument. It should be an 'int'. 1379 // Although not in conformance with C99, we also allow the argument to be 1380 // an 'unsigned int' as that is a reasonably safe case. GCC also 1381 // doesn't emit a warning for that case. 1382 CoveredArgs.set(argIndex); 1383 const Expr *Arg = getDataArg(argIndex); 1384 QualType T = Arg->getType(); 1385 1386 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1387 assert(ATR.isValid()); 1388 1389 if (!ATR.matchesType(S.Context, T)) { 1390 S.Diag(getLocationOfByte(Amt.getStart()), 1391 diag::warn_printf_asterisk_wrong_type) 1392 << k 1393 << ATR.getRepresentativeType(S.Context) << T 1394 << getSpecifierRange(startSpecifier, specifierLen) 1395 << Arg->getSourceRange(); 1396 // Don't do any more checking. We will just emit 1397 // spurious errors. 1398 return false; 1399 } 1400 } 1401 } 1402 return true; 1403} 1404 1405void CheckPrintfHandler::HandleInvalidAmount( 1406 const analyze_printf::PrintfSpecifier &FS, 1407 const analyze_printf::OptionalAmount &Amt, 1408 unsigned type, 1409 const char *startSpecifier, 1410 unsigned specifierLen) { 1411 const analyze_printf::PrintfConversionSpecifier &CS = 1412 FS.getConversionSpecifier(); 1413 switch (Amt.getHowSpecified()) { 1414 case analyze_printf::OptionalAmount::Constant: 1415 S.Diag(getLocationOfByte(Amt.getStart()), 1416 diag::warn_printf_nonsensical_optional_amount) 1417 << type 1418 << CS.toString() 1419 << getSpecifierRange(startSpecifier, specifierLen) 1420 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 1421 Amt.getConstantLength())); 1422 break; 1423 1424 default: 1425 S.Diag(getLocationOfByte(Amt.getStart()), 1426 diag::warn_printf_nonsensical_optional_amount) 1427 << type 1428 << CS.toString() 1429 << getSpecifierRange(startSpecifier, specifierLen); 1430 break; 1431 } 1432} 1433 1434void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1435 const analyze_printf::OptionalFlag &flag, 1436 const char *startSpecifier, 1437 unsigned specifierLen) { 1438 // Warn about pointless flag with a fixit removal. 1439 const analyze_printf::PrintfConversionSpecifier &CS = 1440 FS.getConversionSpecifier(); 1441 S.Diag(getLocationOfByte(flag.getPosition()), 1442 diag::warn_printf_nonsensical_flag) 1443 << flag.toString() << CS.toString() 1444 << getSpecifierRange(startSpecifier, specifierLen) 1445 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)); 1446} 1447 1448void CheckPrintfHandler::HandleIgnoredFlag( 1449 const analyze_printf::PrintfSpecifier &FS, 1450 const analyze_printf::OptionalFlag &ignoredFlag, 1451 const analyze_printf::OptionalFlag &flag, 1452 const char *startSpecifier, 1453 unsigned specifierLen) { 1454 // Warn about ignored flag with a fixit removal. 1455 S.Diag(getLocationOfByte(ignoredFlag.getPosition()), 1456 diag::warn_printf_ignored_flag) 1457 << ignoredFlag.toString() << flag.toString() 1458 << getSpecifierRange(startSpecifier, specifierLen) 1459 << FixItHint::CreateRemoval(getSpecifierRange( 1460 ignoredFlag.getPosition(), 1)); 1461} 1462 1463bool 1464CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 1465 &FS, 1466 const char *startSpecifier, 1467 unsigned specifierLen) { 1468 1469 using namespace analyze_format_string; 1470 using namespace analyze_printf; 1471 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 1472 1473 if (FS.consumesDataArgument()) { 1474 if (atFirstArg) { 1475 atFirstArg = false; 1476 usesPositionalArgs = FS.usesPositionalArg(); 1477 } 1478 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1479 // Cannot mix-and-match positional and non-positional arguments. 1480 S.Diag(getLocationOfByte(CS.getStart()), 1481 diag::warn_format_mix_positional_nonpositional_args) 1482 << getSpecifierRange(startSpecifier, specifierLen); 1483 return false; 1484 } 1485 } 1486 1487 // First check if the field width, precision, and conversion specifier 1488 // have matching data arguments. 1489 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 1490 startSpecifier, specifierLen)) { 1491 return false; 1492 } 1493 1494 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 1495 startSpecifier, specifierLen)) { 1496 return false; 1497 } 1498 1499 if (!CS.consumesDataArgument()) { 1500 // FIXME: Technically specifying a precision or field width here 1501 // makes no sense. Worth issuing a warning at some point. 1502 return true; 1503 } 1504 1505 // Consume the argument. 1506 unsigned argIndex = FS.getArgIndex(); 1507 if (argIndex < NumDataArgs) { 1508 // The check to see if the argIndex is valid will come later. 1509 // We set the bit here because we may exit early from this 1510 // function if we encounter some other error. 1511 CoveredArgs.set(argIndex); 1512 } 1513 1514 // Check for using an Objective-C specific conversion specifier 1515 // in a non-ObjC literal. 1516 if (!IsObjCLiteral && CS.isObjCArg()) { 1517 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 1518 specifierLen); 1519 } 1520 1521 // Check for invalid use of field width 1522 if (!FS.hasValidFieldWidth()) { 1523 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 1524 startSpecifier, specifierLen); 1525 } 1526 1527 // Check for invalid use of precision 1528 if (!FS.hasValidPrecision()) { 1529 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 1530 startSpecifier, specifierLen); 1531 } 1532 1533 // Check each flag does not conflict with any other component. 1534 if (!FS.hasValidThousandsGroupingPrefix()) 1535 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 1536 if (!FS.hasValidLeadingZeros()) 1537 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 1538 if (!FS.hasValidPlusPrefix()) 1539 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 1540 if (!FS.hasValidSpacePrefix()) 1541 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 1542 if (!FS.hasValidAlternativeForm()) 1543 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 1544 if (!FS.hasValidLeftJustified()) 1545 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 1546 1547 // Check that flags are not ignored by another flag 1548 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 1549 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 1550 startSpecifier, specifierLen); 1551 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 1552 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 1553 startSpecifier, specifierLen); 1554 1555 // Check the length modifier is valid with the given conversion specifier. 1556 const LengthModifier &LM = FS.getLengthModifier(); 1557 if (!FS.hasValidLengthModifier()) 1558 S.Diag(getLocationOfByte(LM.getStart()), 1559 diag::warn_format_nonsensical_length) 1560 << LM.toString() << CS.toString() 1561 << getSpecifierRange(startSpecifier, specifierLen) 1562 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1563 LM.getLength())); 1564 1565 // Are we using '%n'? 1566 if (CS.getKind() == ConversionSpecifier::nArg) { 1567 // Issue a warning about this being a possible security issue. 1568 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back) 1569 << getSpecifierRange(startSpecifier, specifierLen); 1570 // Continue checking the other format specifiers. 1571 return true; 1572 } 1573 1574 // The remaining checks depend on the data arguments. 1575 if (HasVAListArg) 1576 return true; 1577 1578 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1579 return false; 1580 1581 // Now type check the data expression that matches the 1582 // format specifier. 1583 const Expr *Ex = getDataArg(argIndex); 1584 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 1585 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 1586 // Check if we didn't match because of an implicit cast from a 'char' 1587 // or 'short' to an 'int'. This is done because printf is a varargs 1588 // function. 1589 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 1590 if (ICE->getType() == S.Context.IntTy) { 1591 // All further checking is done on the subexpression. 1592 Ex = ICE->getSubExpr(); 1593 if (ATR.matchesType(S.Context, Ex->getType())) 1594 return true; 1595 } 1596 1597 // We may be able to offer a FixItHint if it is a supported type. 1598 PrintfSpecifier fixedFS = FS; 1599 bool success = fixedFS.fixType(Ex->getType()); 1600 1601 if (success) { 1602 // Get the fix string from the fixed format specifier 1603 llvm::SmallString<128> buf; 1604 llvm::raw_svector_ostream os(buf); 1605 fixedFS.toString(os); 1606 1607 // FIXME: getRepresentativeType() perhaps should return a string 1608 // instead of a QualType to better handle when the representative 1609 // type is 'wint_t' (which is defined in the system headers). 1610 S.Diag(getLocationOfByte(CS.getStart()), 1611 diag::warn_printf_conversion_argument_type_mismatch) 1612 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1613 << getSpecifierRange(startSpecifier, specifierLen) 1614 << Ex->getSourceRange() 1615 << FixItHint::CreateReplacement( 1616 getSpecifierRange(startSpecifier, specifierLen), 1617 os.str()); 1618 } 1619 else { 1620 S.Diag(getLocationOfByte(CS.getStart()), 1621 diag::warn_printf_conversion_argument_type_mismatch) 1622 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1623 << getSpecifierRange(startSpecifier, specifierLen) 1624 << Ex->getSourceRange(); 1625 } 1626 } 1627 1628 return true; 1629} 1630 1631//===--- CHECK: Scanf format string checking ------------------------------===// 1632 1633namespace { 1634class CheckScanfHandler : public CheckFormatHandler { 1635public: 1636 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 1637 const Expr *origFormatExpr, unsigned firstDataArg, 1638 unsigned numDataArgs, bool isObjCLiteral, 1639 const char *beg, bool hasVAListArg, 1640 const CallExpr *theCall, unsigned formatIdx) 1641 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1642 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1643 theCall, formatIdx) {} 1644 1645 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 1646 const char *startSpecifier, 1647 unsigned specifierLen); 1648 1649 bool HandleInvalidScanfConversionSpecifier( 1650 const analyze_scanf::ScanfSpecifier &FS, 1651 const char *startSpecifier, 1652 unsigned specifierLen); 1653 1654 void HandleIncompleteScanList(const char *start, const char *end); 1655}; 1656} 1657 1658void CheckScanfHandler::HandleIncompleteScanList(const char *start, 1659 const char *end) { 1660 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete) 1661 << getSpecifierRange(start, end - start); 1662} 1663 1664bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 1665 const analyze_scanf::ScanfSpecifier &FS, 1666 const char *startSpecifier, 1667 unsigned specifierLen) { 1668 1669 const analyze_scanf::ScanfConversionSpecifier &CS = 1670 FS.getConversionSpecifier(); 1671 1672 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1673 getLocationOfByte(CS.getStart()), 1674 startSpecifier, specifierLen, 1675 CS.getStart(), CS.getLength()); 1676} 1677 1678bool CheckScanfHandler::HandleScanfSpecifier( 1679 const analyze_scanf::ScanfSpecifier &FS, 1680 const char *startSpecifier, 1681 unsigned specifierLen) { 1682 1683 using namespace analyze_scanf; 1684 using namespace analyze_format_string; 1685 1686 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 1687 1688 // Handle case where '%' and '*' don't consume an argument. These shouldn't 1689 // be used to decide if we are using positional arguments consistently. 1690 if (FS.consumesDataArgument()) { 1691 if (atFirstArg) { 1692 atFirstArg = false; 1693 usesPositionalArgs = FS.usesPositionalArg(); 1694 } 1695 else if (usesPositionalArgs != FS.usesPositionalArg()) { 1696 // Cannot mix-and-match positional and non-positional arguments. 1697 S.Diag(getLocationOfByte(CS.getStart()), 1698 diag::warn_format_mix_positional_nonpositional_args) 1699 << getSpecifierRange(startSpecifier, specifierLen); 1700 return false; 1701 } 1702 } 1703 1704 // Check if the field with is non-zero. 1705 const OptionalAmount &Amt = FS.getFieldWidth(); 1706 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 1707 if (Amt.getConstantAmount() == 0) { 1708 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 1709 Amt.getConstantLength()); 1710 S.Diag(getLocationOfByte(Amt.getStart()), 1711 diag::warn_scanf_nonzero_width) 1712 << R << FixItHint::CreateRemoval(R); 1713 } 1714 } 1715 1716 if (!FS.consumesDataArgument()) { 1717 // FIXME: Technically specifying a precision or field width here 1718 // makes no sense. Worth issuing a warning at some point. 1719 return true; 1720 } 1721 1722 // Consume the argument. 1723 unsigned argIndex = FS.getArgIndex(); 1724 if (argIndex < NumDataArgs) { 1725 // The check to see if the argIndex is valid will come later. 1726 // We set the bit here because we may exit early from this 1727 // function if we encounter some other error. 1728 CoveredArgs.set(argIndex); 1729 } 1730 1731 // Check the length modifier is valid with the given conversion specifier. 1732 const LengthModifier &LM = FS.getLengthModifier(); 1733 if (!FS.hasValidLengthModifier()) { 1734 S.Diag(getLocationOfByte(LM.getStart()), 1735 diag::warn_format_nonsensical_length) 1736 << LM.toString() << CS.toString() 1737 << getSpecifierRange(startSpecifier, specifierLen) 1738 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 1739 LM.getLength())); 1740 } 1741 1742 // The remaining checks depend on the data arguments. 1743 if (HasVAListArg) 1744 return true; 1745 1746 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 1747 return false; 1748 1749 // FIXME: Check that the argument type matches the format specifier. 1750 1751 return true; 1752} 1753 1754void Sema::CheckFormatString(const StringLiteral *FExpr, 1755 const Expr *OrigFormatExpr, 1756 const CallExpr *TheCall, bool HasVAListArg, 1757 unsigned format_idx, unsigned firstDataArg, 1758 bool isPrintf) { 1759 1760 // CHECK: is the format string a wide literal? 1761 if (FExpr->isWide()) { 1762 Diag(FExpr->getLocStart(), 1763 diag::warn_format_string_is_wide_literal) 1764 << OrigFormatExpr->getSourceRange(); 1765 return; 1766 } 1767 1768 // Str - The format string. NOTE: this is NOT null-terminated! 1769 llvm::StringRef StrRef = FExpr->getString(); 1770 const char *Str = StrRef.data(); 1771 unsigned StrLen = StrRef.size(); 1772 1773 // CHECK: empty format string? 1774 if (StrLen == 0) { 1775 Diag(FExpr->getLocStart(), diag::warn_empty_format_string) 1776 << OrigFormatExpr->getSourceRange(); 1777 return; 1778 } 1779 1780 if (isPrintf) { 1781 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1782 TheCall->getNumArgs() - firstDataArg, 1783 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1784 HasVAListArg, TheCall, format_idx); 1785 1786 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen)) 1787 H.DoneProcessing(); 1788 } 1789 else { 1790 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 1791 TheCall->getNumArgs() - firstDataArg, 1792 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1793 HasVAListArg, TheCall, format_idx); 1794 1795 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen)) 1796 H.DoneProcessing(); 1797 } 1798} 1799 1800//===--- CHECK: Standard memory functions ---------------------------------===// 1801 1802/// \brief Determine whether the given type is a dynamic class type (e.g., 1803/// whether it has a vtable). 1804static bool isDynamicClassType(QualType T) { 1805 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 1806 if (CXXRecordDecl *Definition = Record->getDefinition()) 1807 if (Definition->isDynamicClass()) 1808 return true; 1809 1810 return false; 1811} 1812 1813/// \brief Check for dangerous or invalid arguments to memset(). 1814/// 1815/// This issues warnings on known problematic or dangerous or unspecified 1816/// arguments to the standard 'memset' function call. 1817/// 1818/// \param Call The call expression to diagnose. 1819void Sema::CheckMemsetArguments(const CallExpr *Call) { 1820 // It is possible to have a non-standard definition of memset. Validate 1821 // we have the proper number of arguments, and if not, abort further 1822 // checking. 1823 if (Call->getNumArgs() != 3) 1824 return; 1825 1826 const Expr *Dest = Call->getArg(0)->IgnoreParenImpCasts(); 1827 1828 QualType DestTy = Dest->getType(); 1829 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 1830 QualType PointeeTy = DestPtrTy->getPointeeType(); 1831 if (PointeeTy->isVoidType()) 1832 return; 1833 1834 unsigned DiagID = 0; 1835 // Always complain about dynamic classes. 1836 if (isDynamicClassType(PointeeTy)) 1837 DiagID = diag::warn_dyn_class_memset; 1838 // Check the C++11 POD definition regardless of language mode; it is more 1839 // relaxed than earlier definitions and we don't want spurious warnings. 1840 else if (!PointeeTy->isCXX11PODType()) 1841 DiagID = diag::warn_non_pod_memset; 1842 else 1843 return; 1844 1845 DiagRuntimeBehavior( 1846 Dest->getExprLoc(), Dest, 1847 PDiag(DiagID) 1848 << PointeeTy << Call->getCallee()->getSourceRange()); 1849 1850 SourceRange ArgRange = Call->getArg(0)->getSourceRange(); 1851 DiagRuntimeBehavior( 1852 Dest->getExprLoc(), Dest, 1853 PDiag(diag::note_non_pod_memset_silence) 1854 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 1855 } 1856} 1857 1858//===--- CHECK: Return Address of Stack Variable --------------------------===// 1859 1860static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars); 1861static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars); 1862 1863/// CheckReturnStackAddr - Check if a return statement returns the address 1864/// of a stack variable. 1865void 1866Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1867 SourceLocation ReturnLoc) { 1868 1869 Expr *stackE = 0; 1870 llvm::SmallVector<DeclRefExpr *, 8> refVars; 1871 1872 // Perform checking for returned stack addresses, local blocks, 1873 // label addresses or references to temporaries. 1874 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1875 stackE = EvalAddr(RetValExp, refVars); 1876 } else if (lhsType->isReferenceType()) { 1877 stackE = EvalVal(RetValExp, refVars); 1878 } 1879 1880 if (stackE == 0) 1881 return; // Nothing suspicious was found. 1882 1883 SourceLocation diagLoc; 1884 SourceRange diagRange; 1885 if (refVars.empty()) { 1886 diagLoc = stackE->getLocStart(); 1887 diagRange = stackE->getSourceRange(); 1888 } else { 1889 // We followed through a reference variable. 'stackE' contains the 1890 // problematic expression but we will warn at the return statement pointing 1891 // at the reference variable. We will later display the "trail" of 1892 // reference variables using notes. 1893 diagLoc = refVars[0]->getLocStart(); 1894 diagRange = refVars[0]->getSourceRange(); 1895 } 1896 1897 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 1898 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 1899 : diag::warn_ret_stack_addr) 1900 << DR->getDecl()->getDeclName() << diagRange; 1901 } else if (isa<BlockExpr>(stackE)) { // local block. 1902 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 1903 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 1904 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 1905 } else { // local temporary. 1906 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 1907 : diag::warn_ret_local_temp_addr) 1908 << diagRange; 1909 } 1910 1911 // Display the "trail" of reference variables that we followed until we 1912 // found the problematic expression using notes. 1913 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 1914 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 1915 // If this var binds to another reference var, show the range of the next 1916 // var, otherwise the var binds to the problematic expression, in which case 1917 // show the range of the expression. 1918 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 1919 : stackE->getSourceRange(); 1920 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 1921 << VD->getDeclName() << range; 1922 } 1923} 1924 1925/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1926/// check if the expression in a return statement evaluates to an address 1927/// to a location on the stack, a local block, an address of a label, or a 1928/// reference to local temporary. The recursion is used to traverse the 1929/// AST of the return expression, with recursion backtracking when we 1930/// encounter a subexpression that (1) clearly does not lead to one of the 1931/// above problematic expressions (2) is something we cannot determine leads to 1932/// a problematic expression based on such local checking. 1933/// 1934/// Both EvalAddr and EvalVal follow through reference variables to evaluate 1935/// the expression that they point to. Such variables are added to the 1936/// 'refVars' vector so that we know what the reference variable "trail" was. 1937/// 1938/// EvalAddr processes expressions that are pointers that are used as 1939/// references (and not L-values). EvalVal handles all other values. 1940/// At the base case of the recursion is a check for the above problematic 1941/// expressions. 1942/// 1943/// This implementation handles: 1944/// 1945/// * pointer-to-pointer casts 1946/// * implicit conversions from array references to pointers 1947/// * taking the address of fields 1948/// * arbitrary interplay between "&" and "*" operators 1949/// * pointer arithmetic from an address of a stack variable 1950/// * taking the address of an array element where the array is on the stack 1951static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) { 1952 if (E->isTypeDependent()) 1953 return NULL; 1954 1955 // We should only be called for evaluating pointer expressions. 1956 assert((E->getType()->isAnyPointerType() || 1957 E->getType()->isBlockPointerType() || 1958 E->getType()->isObjCQualifiedIdType()) && 1959 "EvalAddr only works on pointers"); 1960 1961 E = E->IgnoreParens(); 1962 1963 // Our "symbolic interpreter" is just a dispatch off the currently 1964 // viewed AST node. We then recursively traverse the AST by calling 1965 // EvalAddr and EvalVal appropriately. 1966 switch (E->getStmtClass()) { 1967 case Stmt::DeclRefExprClass: { 1968 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1969 1970 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1971 // If this is a reference variable, follow through to the expression that 1972 // it points to. 1973 if (V->hasLocalStorage() && 1974 V->getType()->isReferenceType() && V->hasInit()) { 1975 // Add the reference variable to the "trail". 1976 refVars.push_back(DR); 1977 return EvalAddr(V->getInit(), refVars); 1978 } 1979 1980 return NULL; 1981 } 1982 1983 case Stmt::UnaryOperatorClass: { 1984 // The only unary operator that make sense to handle here 1985 // is AddrOf. All others don't make sense as pointers. 1986 UnaryOperator *U = cast<UnaryOperator>(E); 1987 1988 if (U->getOpcode() == UO_AddrOf) 1989 return EvalVal(U->getSubExpr(), refVars); 1990 else 1991 return NULL; 1992 } 1993 1994 case Stmt::BinaryOperatorClass: { 1995 // Handle pointer arithmetic. All other binary operators are not valid 1996 // in this context. 1997 BinaryOperator *B = cast<BinaryOperator>(E); 1998 BinaryOperatorKind op = B->getOpcode(); 1999 2000 if (op != BO_Add && op != BO_Sub) 2001 return NULL; 2002 2003 Expr *Base = B->getLHS(); 2004 2005 // Determine which argument is the real pointer base. It could be 2006 // the RHS argument instead of the LHS. 2007 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 2008 2009 assert (Base->getType()->isPointerType()); 2010 return EvalAddr(Base, refVars); 2011 } 2012 2013 // For conditional operators we need to see if either the LHS or RHS are 2014 // valid DeclRefExpr*s. If one of them is valid, we return it. 2015 case Stmt::ConditionalOperatorClass: { 2016 ConditionalOperator *C = cast<ConditionalOperator>(E); 2017 2018 // Handle the GNU extension for missing LHS. 2019 if (Expr *lhsExpr = C->getLHS()) { 2020 // In C++, we can have a throw-expression, which has 'void' type. 2021 if (!lhsExpr->getType()->isVoidType()) 2022 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 2023 return LHS; 2024 } 2025 2026 // In C++, we can have a throw-expression, which has 'void' type. 2027 if (C->getRHS()->getType()->isVoidType()) 2028 return NULL; 2029 2030 return EvalAddr(C->getRHS(), refVars); 2031 } 2032 2033 case Stmt::BlockExprClass: 2034 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 2035 return E; // local block. 2036 return NULL; 2037 2038 case Stmt::AddrLabelExprClass: 2039 return E; // address of label. 2040 2041 // For casts, we need to handle conversions from arrays to 2042 // pointer values, and pointer-to-pointer conversions. 2043 case Stmt::ImplicitCastExprClass: 2044 case Stmt::CStyleCastExprClass: 2045 case Stmt::CXXFunctionalCastExprClass: { 2046 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2047 QualType T = SubExpr->getType(); 2048 2049 if (SubExpr->getType()->isPointerType() || 2050 SubExpr->getType()->isBlockPointerType() || 2051 SubExpr->getType()->isObjCQualifiedIdType()) 2052 return EvalAddr(SubExpr, refVars); 2053 else if (T->isArrayType()) 2054 return EvalVal(SubExpr, refVars); 2055 else 2056 return 0; 2057 } 2058 2059 // C++ casts. For dynamic casts, static casts, and const casts, we 2060 // are always converting from a pointer-to-pointer, so we just blow 2061 // through the cast. In the case the dynamic cast doesn't fail (and 2062 // return NULL), we take the conservative route and report cases 2063 // where we return the address of a stack variable. For Reinterpre 2064 // FIXME: The comment about is wrong; we're not always converting 2065 // from pointer to pointer. I'm guessing that this code should also 2066 // handle references to objects. 2067 case Stmt::CXXStaticCastExprClass: 2068 case Stmt::CXXDynamicCastExprClass: 2069 case Stmt::CXXConstCastExprClass: 2070 case Stmt::CXXReinterpretCastExprClass: { 2071 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2072 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2073 return EvalAddr(S, refVars); 2074 else 2075 return NULL; 2076 } 2077 2078 // Everything else: we simply don't reason about them. 2079 default: 2080 return NULL; 2081 } 2082} 2083 2084 2085/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2086/// See the comments for EvalAddr for more details. 2087static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) { 2088do { 2089 // We should only be called for evaluating non-pointer expressions, or 2090 // expressions with a pointer type that are not used as references but instead 2091 // are l-values (e.g., DeclRefExpr with a pointer type). 2092 2093 // Our "symbolic interpreter" is just a dispatch off the currently 2094 // viewed AST node. We then recursively traverse the AST by calling 2095 // EvalAddr and EvalVal appropriately. 2096 2097 E = E->IgnoreParens(); 2098 switch (E->getStmtClass()) { 2099 case Stmt::ImplicitCastExprClass: { 2100 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2101 if (IE->getValueKind() == VK_LValue) { 2102 E = IE->getSubExpr(); 2103 continue; 2104 } 2105 return NULL; 2106 } 2107 2108 case Stmt::DeclRefExprClass: { 2109 // When we hit a DeclRefExpr we are looking at code that refers to a 2110 // variable's name. If it's not a reference variable we check if it has 2111 // local storage within the function, and if so, return the expression. 2112 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2113 2114 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2115 if (V->hasLocalStorage()) { 2116 if (!V->getType()->isReferenceType()) 2117 return DR; 2118 2119 // Reference variable, follow through to the expression that 2120 // it points to. 2121 if (V->hasInit()) { 2122 // Add the reference variable to the "trail". 2123 refVars.push_back(DR); 2124 return EvalVal(V->getInit(), refVars); 2125 } 2126 } 2127 2128 return NULL; 2129 } 2130 2131 case Stmt::UnaryOperatorClass: { 2132 // The only unary operator that make sense to handle here 2133 // is Deref. All others don't resolve to a "name." This includes 2134 // handling all sorts of rvalues passed to a unary operator. 2135 UnaryOperator *U = cast<UnaryOperator>(E); 2136 2137 if (U->getOpcode() == UO_Deref) 2138 return EvalAddr(U->getSubExpr(), refVars); 2139 2140 return NULL; 2141 } 2142 2143 case Stmt::ArraySubscriptExprClass: { 2144 // Array subscripts are potential references to data on the stack. We 2145 // retrieve the DeclRefExpr* for the array variable if it indeed 2146 // has local storage. 2147 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2148 } 2149 2150 case Stmt::ConditionalOperatorClass: { 2151 // For conditional operators we need to see if either the LHS or RHS are 2152 // non-NULL Expr's. If one is non-NULL, we return it. 2153 ConditionalOperator *C = cast<ConditionalOperator>(E); 2154 2155 // Handle the GNU extension for missing LHS. 2156 if (Expr *lhsExpr = C->getLHS()) 2157 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 2158 return LHS; 2159 2160 return EvalVal(C->getRHS(), refVars); 2161 } 2162 2163 // Accesses to members are potential references to data on the stack. 2164 case Stmt::MemberExprClass: { 2165 MemberExpr *M = cast<MemberExpr>(E); 2166 2167 // Check for indirect access. We only want direct field accesses. 2168 if (M->isArrow()) 2169 return NULL; 2170 2171 // Check whether the member type is itself a reference, in which case 2172 // we're not going to refer to the member, but to what the member refers to. 2173 if (M->getMemberDecl()->getType()->isReferenceType()) 2174 return NULL; 2175 2176 return EvalVal(M->getBase(), refVars); 2177 } 2178 2179 default: 2180 // Check that we don't return or take the address of a reference to a 2181 // temporary. This is only useful in C++. 2182 if (!E->isTypeDependent() && E->isRValue()) 2183 return E; 2184 2185 // Everything else: we simply don't reason about them. 2186 return NULL; 2187 } 2188} while (true); 2189} 2190 2191//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 2192 2193/// Check for comparisons of floating point operands using != and ==. 2194/// Issue a warning if these are no self-comparisons, as they are not likely 2195/// to do what the programmer intended. 2196void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 2197 bool EmitWarning = true; 2198 2199 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts(); 2200 Expr* RightExprSansParen = rex->IgnoreParenImpCasts(); 2201 2202 // Special case: check for x == x (which is OK). 2203 // Do not emit warnings for such cases. 2204 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 2205 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 2206 if (DRL->getDecl() == DRR->getDecl()) 2207 EmitWarning = false; 2208 2209 2210 // Special case: check for comparisons against literals that can be exactly 2211 // represented by APFloat. In such cases, do not emit a warning. This 2212 // is a heuristic: often comparison against such literals are used to 2213 // detect if a value in a variable has not changed. This clearly can 2214 // lead to false negatives. 2215 if (EmitWarning) { 2216 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 2217 if (FLL->isExact()) 2218 EmitWarning = false; 2219 } else 2220 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 2221 if (FLR->isExact()) 2222 EmitWarning = false; 2223 } 2224 } 2225 2226 // Check for comparisons with builtin types. 2227 if (EmitWarning) 2228 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 2229 if (CL->isBuiltinCall(Context)) 2230 EmitWarning = false; 2231 2232 if (EmitWarning) 2233 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 2234 if (CR->isBuiltinCall(Context)) 2235 EmitWarning = false; 2236 2237 // Emit the diagnostic. 2238 if (EmitWarning) 2239 Diag(loc, diag::warn_floatingpoint_eq) 2240 << lex->getSourceRange() << rex->getSourceRange(); 2241} 2242 2243//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 2244//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 2245 2246namespace { 2247 2248/// Structure recording the 'active' range of an integer-valued 2249/// expression. 2250struct IntRange { 2251 /// The number of bits active in the int. 2252 unsigned Width; 2253 2254 /// True if the int is known not to have negative values. 2255 bool NonNegative; 2256 2257 IntRange(unsigned Width, bool NonNegative) 2258 : Width(Width), NonNegative(NonNegative) 2259 {} 2260 2261 /// Returns the range of the bool type. 2262 static IntRange forBoolType() { 2263 return IntRange(1, true); 2264 } 2265 2266 /// Returns the range of an opaque value of the given integral type. 2267 static IntRange forValueOfType(ASTContext &C, QualType T) { 2268 return forValueOfCanonicalType(C, 2269 T->getCanonicalTypeInternal().getTypePtr()); 2270 } 2271 2272 /// Returns the range of an opaque value of a canonical integral type. 2273 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 2274 assert(T->isCanonicalUnqualified()); 2275 2276 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2277 T = VT->getElementType().getTypePtr(); 2278 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2279 T = CT->getElementType().getTypePtr(); 2280 2281 // For enum types, use the known bit width of the enumerators. 2282 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 2283 EnumDecl *Enum = ET->getDecl(); 2284 if (!Enum->isDefinition()) 2285 return IntRange(C.getIntWidth(QualType(T, 0)), false); 2286 2287 unsigned NumPositive = Enum->getNumPositiveBits(); 2288 unsigned NumNegative = Enum->getNumNegativeBits(); 2289 2290 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 2291 } 2292 2293 const BuiltinType *BT = cast<BuiltinType>(T); 2294 assert(BT->isInteger()); 2295 2296 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2297 } 2298 2299 /// Returns the "target" range of a canonical integral type, i.e. 2300 /// the range of values expressible in the type. 2301 /// 2302 /// This matches forValueOfCanonicalType except that enums have the 2303 /// full range of their type, not the range of their enumerators. 2304 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 2305 assert(T->isCanonicalUnqualified()); 2306 2307 if (const VectorType *VT = dyn_cast<VectorType>(T)) 2308 T = VT->getElementType().getTypePtr(); 2309 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 2310 T = CT->getElementType().getTypePtr(); 2311 if (const EnumType *ET = dyn_cast<EnumType>(T)) 2312 T = ET->getDecl()->getIntegerType().getTypePtr(); 2313 2314 const BuiltinType *BT = cast<BuiltinType>(T); 2315 assert(BT->isInteger()); 2316 2317 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 2318 } 2319 2320 /// Returns the supremum of two ranges: i.e. their conservative merge. 2321 static IntRange join(IntRange L, IntRange R) { 2322 return IntRange(std::max(L.Width, R.Width), 2323 L.NonNegative && R.NonNegative); 2324 } 2325 2326 /// Returns the infinum of two ranges: i.e. their aggressive merge. 2327 static IntRange meet(IntRange L, IntRange R) { 2328 return IntRange(std::min(L.Width, R.Width), 2329 L.NonNegative || R.NonNegative); 2330 } 2331}; 2332 2333IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 2334 if (value.isSigned() && value.isNegative()) 2335 return IntRange(value.getMinSignedBits(), false); 2336 2337 if (value.getBitWidth() > MaxWidth) 2338 value = value.trunc(MaxWidth); 2339 2340 // isNonNegative() just checks the sign bit without considering 2341 // signedness. 2342 return IntRange(value.getActiveBits(), true); 2343} 2344 2345IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 2346 unsigned MaxWidth) { 2347 if (result.isInt()) 2348 return GetValueRange(C, result.getInt(), MaxWidth); 2349 2350 if (result.isVector()) { 2351 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 2352 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 2353 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 2354 R = IntRange::join(R, El); 2355 } 2356 return R; 2357 } 2358 2359 if (result.isComplexInt()) { 2360 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 2361 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 2362 return IntRange::join(R, I); 2363 } 2364 2365 // This can happen with lossless casts to intptr_t of "based" lvalues. 2366 // Assume it might use arbitrary bits. 2367 // FIXME: The only reason we need to pass the type in here is to get 2368 // the sign right on this one case. It would be nice if APValue 2369 // preserved this. 2370 assert(result.isLValue()); 2371 return IntRange(MaxWidth, Ty->isUnsignedIntegerType()); 2372} 2373 2374/// Pseudo-evaluate the given integer expression, estimating the 2375/// range of values it might take. 2376/// 2377/// \param MaxWidth - the width to which the value will be truncated 2378IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 2379 E = E->IgnoreParens(); 2380 2381 // Try a full evaluation first. 2382 Expr::EvalResult result; 2383 if (E->Evaluate(result, C)) 2384 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 2385 2386 // I think we only want to look through implicit casts here; if the 2387 // user has an explicit widening cast, we should treat the value as 2388 // being of the new, wider type. 2389 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 2390 if (CE->getCastKind() == CK_NoOp) 2391 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 2392 2393 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 2394 2395 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 2396 2397 // Assume that non-integer casts can span the full range of the type. 2398 if (!isIntegerCast) 2399 return OutputTypeRange; 2400 2401 IntRange SubRange 2402 = GetExprRange(C, CE->getSubExpr(), 2403 std::min(MaxWidth, OutputTypeRange.Width)); 2404 2405 // Bail out if the subexpr's range is as wide as the cast type. 2406 if (SubRange.Width >= OutputTypeRange.Width) 2407 return OutputTypeRange; 2408 2409 // Otherwise, we take the smaller width, and we're non-negative if 2410 // either the output type or the subexpr is. 2411 return IntRange(SubRange.Width, 2412 SubRange.NonNegative || OutputTypeRange.NonNegative); 2413 } 2414 2415 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2416 // If we can fold the condition, just take that operand. 2417 bool CondResult; 2418 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 2419 return GetExprRange(C, CondResult ? CO->getTrueExpr() 2420 : CO->getFalseExpr(), 2421 MaxWidth); 2422 2423 // Otherwise, conservatively merge. 2424 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 2425 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 2426 return IntRange::join(L, R); 2427 } 2428 2429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2430 switch (BO->getOpcode()) { 2431 2432 // Boolean-valued operations are single-bit and positive. 2433 case BO_LAnd: 2434 case BO_LOr: 2435 case BO_LT: 2436 case BO_GT: 2437 case BO_LE: 2438 case BO_GE: 2439 case BO_EQ: 2440 case BO_NE: 2441 return IntRange::forBoolType(); 2442 2443 // The type of these compound assignments is the type of the LHS, 2444 // so the RHS is not necessarily an integer. 2445 case BO_MulAssign: 2446 case BO_DivAssign: 2447 case BO_RemAssign: 2448 case BO_AddAssign: 2449 case BO_SubAssign: 2450 return IntRange::forValueOfType(C, E->getType()); 2451 2452 // Operations with opaque sources are black-listed. 2453 case BO_PtrMemD: 2454 case BO_PtrMemI: 2455 return IntRange::forValueOfType(C, E->getType()); 2456 2457 // Bitwise-and uses the *infinum* of the two source ranges. 2458 case BO_And: 2459 case BO_AndAssign: 2460 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 2461 GetExprRange(C, BO->getRHS(), MaxWidth)); 2462 2463 // Left shift gets black-listed based on a judgement call. 2464 case BO_Shl: 2465 // ...except that we want to treat '1 << (blah)' as logically 2466 // positive. It's an important idiom. 2467 if (IntegerLiteral *I 2468 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 2469 if (I->getValue() == 1) { 2470 IntRange R = IntRange::forValueOfType(C, E->getType()); 2471 return IntRange(R.Width, /*NonNegative*/ true); 2472 } 2473 } 2474 // fallthrough 2475 2476 case BO_ShlAssign: 2477 return IntRange::forValueOfType(C, E->getType()); 2478 2479 // Right shift by a constant can narrow its left argument. 2480 case BO_Shr: 2481 case BO_ShrAssign: { 2482 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2483 2484 // If the shift amount is a positive constant, drop the width by 2485 // that much. 2486 llvm::APSInt shift; 2487 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 2488 shift.isNonNegative()) { 2489 unsigned zext = shift.getZExtValue(); 2490 if (zext >= L.Width) 2491 L.Width = (L.NonNegative ? 0 : 1); 2492 else 2493 L.Width -= zext; 2494 } 2495 2496 return L; 2497 } 2498 2499 // Comma acts as its right operand. 2500 case BO_Comma: 2501 return GetExprRange(C, BO->getRHS(), MaxWidth); 2502 2503 // Black-list pointer subtractions. 2504 case BO_Sub: 2505 if (BO->getLHS()->getType()->isPointerType()) 2506 return IntRange::forValueOfType(C, E->getType()); 2507 // fallthrough 2508 2509 default: 2510 break; 2511 } 2512 2513 // Treat every other operator as if it were closed on the 2514 // narrowest type that encompasses both operands. 2515 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 2516 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 2517 return IntRange::join(L, R); 2518 } 2519 2520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 2521 switch (UO->getOpcode()) { 2522 // Boolean-valued operations are white-listed. 2523 case UO_LNot: 2524 return IntRange::forBoolType(); 2525 2526 // Operations with opaque sources are black-listed. 2527 case UO_Deref: 2528 case UO_AddrOf: // should be impossible 2529 return IntRange::forValueOfType(C, E->getType()); 2530 2531 default: 2532 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 2533 } 2534 } 2535 2536 if (dyn_cast<OffsetOfExpr>(E)) { 2537 IntRange::forValueOfType(C, E->getType()); 2538 } 2539 2540 FieldDecl *BitField = E->getBitField(); 2541 if (BitField) { 2542 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C); 2543 unsigned BitWidth = BitWidthAP.getZExtValue(); 2544 2545 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType()); 2546 } 2547 2548 return IntRange::forValueOfType(C, E->getType()); 2549} 2550 2551IntRange GetExprRange(ASTContext &C, Expr *E) { 2552 return GetExprRange(C, E, C.getIntWidth(E->getType())); 2553} 2554 2555/// Checks whether the given value, which currently has the given 2556/// source semantics, has the same value when coerced through the 2557/// target semantics. 2558bool IsSameFloatAfterCast(const llvm::APFloat &value, 2559 const llvm::fltSemantics &Src, 2560 const llvm::fltSemantics &Tgt) { 2561 llvm::APFloat truncated = value; 2562 2563 bool ignored; 2564 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 2565 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 2566 2567 return truncated.bitwiseIsEqual(value); 2568} 2569 2570/// Checks whether the given value, which currently has the given 2571/// source semantics, has the same value when coerced through the 2572/// target semantics. 2573/// 2574/// The value might be a vector of floats (or a complex number). 2575bool IsSameFloatAfterCast(const APValue &value, 2576 const llvm::fltSemantics &Src, 2577 const llvm::fltSemantics &Tgt) { 2578 if (value.isFloat()) 2579 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 2580 2581 if (value.isVector()) { 2582 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 2583 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 2584 return false; 2585 return true; 2586 } 2587 2588 assert(value.isComplexFloat()); 2589 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 2590 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 2591} 2592 2593void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 2594 2595static bool IsZero(Sema &S, Expr *E) { 2596 // Suppress cases where we are comparing against an enum constant. 2597 if (const DeclRefExpr *DR = 2598 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 2599 if (isa<EnumConstantDecl>(DR->getDecl())) 2600 return false; 2601 2602 // Suppress cases where the '0' value is expanded from a macro. 2603 if (E->getLocStart().isMacroID()) 2604 return false; 2605 2606 llvm::APSInt Value; 2607 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 2608} 2609 2610static bool HasEnumType(Expr *E) { 2611 // Strip off implicit integral promotions. 2612 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2613 if (ICE->getCastKind() != CK_IntegralCast && 2614 ICE->getCastKind() != CK_NoOp) 2615 break; 2616 E = ICE->getSubExpr(); 2617 } 2618 2619 return E->getType()->isEnumeralType(); 2620} 2621 2622void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 2623 BinaryOperatorKind op = E->getOpcode(); 2624 if (E->isValueDependent()) 2625 return; 2626 2627 if (op == BO_LT && IsZero(S, E->getRHS())) { 2628 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2629 << "< 0" << "false" << HasEnumType(E->getLHS()) 2630 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2631 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 2632 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 2633 << ">= 0" << "true" << HasEnumType(E->getLHS()) 2634 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2635 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 2636 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2637 << "0 >" << "false" << HasEnumType(E->getRHS()) 2638 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2639 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 2640 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 2641 << "0 <=" << "true" << HasEnumType(E->getRHS()) 2642 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 2643 } 2644} 2645 2646/// Analyze the operands of the given comparison. Implements the 2647/// fallback case from AnalyzeComparison. 2648void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 2649 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 2650 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 2651} 2652 2653/// \brief Implements -Wsign-compare. 2654/// 2655/// \param lex the left-hand expression 2656/// \param rex the right-hand expression 2657/// \param OpLoc the location of the joining operator 2658/// \param BinOpc binary opcode or 0 2659void AnalyzeComparison(Sema &S, BinaryOperator *E) { 2660 // The type the comparison is being performed in. 2661 QualType T = E->getLHS()->getType(); 2662 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 2663 && "comparison with mismatched types"); 2664 2665 // We don't do anything special if this isn't an unsigned integral 2666 // comparison: we're only interested in integral comparisons, and 2667 // signed comparisons only happen in cases we don't care to warn about. 2668 // 2669 // We also don't care about value-dependent expressions or expressions 2670 // whose result is a constant. 2671 if (!T->hasUnsignedIntegerRepresentation() 2672 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 2673 return AnalyzeImpConvsInComparison(S, E); 2674 2675 Expr *lex = E->getLHS()->IgnoreParenImpCasts(); 2676 Expr *rex = E->getRHS()->IgnoreParenImpCasts(); 2677 2678 // Check to see if one of the (unmodified) operands is of different 2679 // signedness. 2680 Expr *signedOperand, *unsignedOperand; 2681 if (lex->getType()->hasSignedIntegerRepresentation()) { 2682 assert(!rex->getType()->hasSignedIntegerRepresentation() && 2683 "unsigned comparison between two signed integer expressions?"); 2684 signedOperand = lex; 2685 unsignedOperand = rex; 2686 } else if (rex->getType()->hasSignedIntegerRepresentation()) { 2687 signedOperand = rex; 2688 unsignedOperand = lex; 2689 } else { 2690 CheckTrivialUnsignedComparison(S, E); 2691 return AnalyzeImpConvsInComparison(S, E); 2692 } 2693 2694 // Otherwise, calculate the effective range of the signed operand. 2695 IntRange signedRange = GetExprRange(S.Context, signedOperand); 2696 2697 // Go ahead and analyze implicit conversions in the operands. Note 2698 // that we skip the implicit conversions on both sides. 2699 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc()); 2700 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc()); 2701 2702 // If the signed range is non-negative, -Wsign-compare won't fire, 2703 // but we should still check for comparisons which are always true 2704 // or false. 2705 if (signedRange.NonNegative) 2706 return CheckTrivialUnsignedComparison(S, E); 2707 2708 // For (in)equality comparisons, if the unsigned operand is a 2709 // constant which cannot collide with a overflowed signed operand, 2710 // then reinterpreting the signed operand as unsigned will not 2711 // change the result of the comparison. 2712 if (E->isEqualityOp()) { 2713 unsigned comparisonWidth = S.Context.getIntWidth(T); 2714 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 2715 2716 // We should never be unable to prove that the unsigned operand is 2717 // non-negative. 2718 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 2719 2720 if (unsignedRange.Width < comparisonWidth) 2721 return; 2722 } 2723 2724 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 2725 << lex->getType() << rex->getType() 2726 << lex->getSourceRange() << rex->getSourceRange(); 2727} 2728 2729/// Analyzes an attempt to assign the given value to a bitfield. 2730/// 2731/// Returns true if there was something fishy about the attempt. 2732bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 2733 SourceLocation InitLoc) { 2734 assert(Bitfield->isBitField()); 2735 if (Bitfield->isInvalidDecl()) 2736 return false; 2737 2738 // White-list bool bitfields. 2739 if (Bitfield->getType()->isBooleanType()) 2740 return false; 2741 2742 // Ignore value- or type-dependent expressions. 2743 if (Bitfield->getBitWidth()->isValueDependent() || 2744 Bitfield->getBitWidth()->isTypeDependent() || 2745 Init->isValueDependent() || 2746 Init->isTypeDependent()) 2747 return false; 2748 2749 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 2750 2751 llvm::APSInt Width(32); 2752 Expr::EvalResult InitValue; 2753 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) || 2754 !OriginalInit->Evaluate(InitValue, S.Context) || 2755 !InitValue.Val.isInt()) 2756 return false; 2757 2758 const llvm::APSInt &Value = InitValue.Val.getInt(); 2759 unsigned OriginalWidth = Value.getBitWidth(); 2760 unsigned FieldWidth = Width.getZExtValue(); 2761 2762 if (OriginalWidth <= FieldWidth) 2763 return false; 2764 2765 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 2766 2767 // It's fairly common to write values into signed bitfields 2768 // that, if sign-extended, would end up becoming a different 2769 // value. We don't want to warn about that. 2770 if (Value.isSigned() && Value.isNegative()) 2771 TruncatedValue = TruncatedValue.sext(OriginalWidth); 2772 else 2773 TruncatedValue = TruncatedValue.zext(OriginalWidth); 2774 2775 if (Value == TruncatedValue) 2776 return false; 2777 2778 std::string PrettyValue = Value.toString(10); 2779 std::string PrettyTrunc = TruncatedValue.toString(10); 2780 2781 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 2782 << PrettyValue << PrettyTrunc << OriginalInit->getType() 2783 << Init->getSourceRange(); 2784 2785 return true; 2786} 2787 2788/// Analyze the given simple or compound assignment for warning-worthy 2789/// operations. 2790void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 2791 // Just recurse on the LHS. 2792 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 2793 2794 // We want to recurse on the RHS as normal unless we're assigning to 2795 // a bitfield. 2796 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 2797 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 2798 E->getOperatorLoc())) { 2799 // Recurse, ignoring any implicit conversions on the RHS. 2800 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 2801 E->getOperatorLoc()); 2802 } 2803 } 2804 2805 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 2806} 2807 2808/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2809void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 2810 SourceLocation CContext, unsigned diag) { 2811 S.Diag(E->getExprLoc(), diag) 2812 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 2813} 2814 2815/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2816void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 2817 unsigned diag) { 2818 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag); 2819} 2820 2821/// Diagnose an implicit cast from a literal expression. Also attemps to supply 2822/// fixit hints when the cast wouldn't lose information to simply write the 2823/// expression with the expected type. 2824void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 2825 SourceLocation CContext) { 2826 // Emit the primary warning first, then try to emit a fixit hint note if 2827 // reasonable. 2828 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 2829 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext); 2830 2831 const llvm::APFloat &Value = FL->getValue(); 2832 2833 // Don't attempt to fix PPC double double literals. 2834 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble) 2835 return; 2836 2837 // Try to convert this exactly to an 64-bit integer. FIXME: It would be 2838 // nice to support arbitrarily large integers here. 2839 bool isExact = false; 2840 uint64_t IntegerPart; 2841 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true, 2842 llvm::APFloat::rmTowardZero, &isExact) 2843 != llvm::APFloat::opOK || !isExact) 2844 return; 2845 2846 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true); 2847 2848 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true); 2849 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer) 2850 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue); 2851} 2852 2853std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 2854 if (!Range.Width) return "0"; 2855 2856 llvm::APSInt ValueInRange = Value; 2857 ValueInRange.setIsSigned(!Range.NonNegative); 2858 ValueInRange = ValueInRange.trunc(Range.Width); 2859 return ValueInRange.toString(10); 2860} 2861 2862static bool isFromSystemMacro(Sema &S, SourceLocation loc) { 2863 SourceManager &smgr = S.Context.getSourceManager(); 2864 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc)); 2865} 2866 2867void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 2868 SourceLocation CC, bool *ICContext = 0) { 2869 if (E->isTypeDependent() || E->isValueDependent()) return; 2870 2871 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 2872 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 2873 if (Source == Target) return; 2874 if (Target->isDependentType()) return; 2875 2876 // If the conversion context location is invalid don't complain. 2877 // We also don't want to emit a warning if the issue occurs from the 2878 // instantiation of a system macro. The problem is that 'getSpellingLoc()' 2879 // is slow, so we delay this check as long as possible. Once we detect 2880 // we are in that scenario, we just return. 2881 if (CC.isInvalid()) 2882 return; 2883 2884 // Never diagnose implicit casts to bool. 2885 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 2886 return; 2887 2888 // Strip vector types. 2889 if (isa<VectorType>(Source)) { 2890 if (!isa<VectorType>(Target)) { 2891 if (isFromSystemMacro(S, CC)) 2892 return; 2893 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 2894 } 2895 2896 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 2897 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 2898 } 2899 2900 // Strip complex types. 2901 if (isa<ComplexType>(Source)) { 2902 if (!isa<ComplexType>(Target)) { 2903 if (isFromSystemMacro(S, CC)) 2904 return; 2905 2906 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 2907 } 2908 2909 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 2910 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 2911 } 2912 2913 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 2914 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 2915 2916 // If the source is floating point... 2917 if (SourceBT && SourceBT->isFloatingPoint()) { 2918 // ...and the target is floating point... 2919 if (TargetBT && TargetBT->isFloatingPoint()) { 2920 // ...then warn if we're dropping FP rank. 2921 2922 // Builtin FP kinds are ordered by increasing FP rank. 2923 if (SourceBT->getKind() > TargetBT->getKind()) { 2924 // Don't warn about float constants that are precisely 2925 // representable in the target type. 2926 Expr::EvalResult result; 2927 if (E->Evaluate(result, S.Context)) { 2928 // Value might be a float, a float vector, or a float complex. 2929 if (IsSameFloatAfterCast(result.Val, 2930 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 2931 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 2932 return; 2933 } 2934 2935 if (isFromSystemMacro(S, CC)) 2936 return; 2937 2938 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 2939 } 2940 return; 2941 } 2942 2943 // If the target is integral, always warn. 2944 if ((TargetBT && TargetBT->isInteger())) { 2945 if (isFromSystemMacro(S, CC)) 2946 return; 2947 2948 Expr *InnerE = E->IgnoreParenImpCasts(); 2949 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 2950 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 2951 } else { 2952 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 2953 } 2954 } 2955 2956 return; 2957 } 2958 2959 if (!Source->isIntegerType() || !Target->isIntegerType()) 2960 return; 2961 2962 IntRange SourceRange = GetExprRange(S.Context, E); 2963 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 2964 2965 if (SourceRange.Width > TargetRange.Width) { 2966 // If the source is a constant, use a default-on diagnostic. 2967 // TODO: this should happen for bitfield stores, too. 2968 llvm::APSInt Value(32); 2969 if (E->isIntegerConstantExpr(Value, S.Context)) { 2970 if (isFromSystemMacro(S, CC)) 2971 return; 2972 2973 std::string PrettySourceValue = Value.toString(10); 2974 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 2975 2976 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant) 2977 << PrettySourceValue << PrettyTargetValue 2978 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC); 2979 return; 2980 } 2981 2982 // People want to build with -Wshorten-64-to-32 and not -Wconversion 2983 // and by god we'll let them. 2984 2985 if (isFromSystemMacro(S, CC)) 2986 return; 2987 2988 if (SourceRange.Width == 64 && TargetRange.Width == 32) 2989 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 2990 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 2991 } 2992 2993 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 2994 (!TargetRange.NonNegative && SourceRange.NonNegative && 2995 SourceRange.Width == TargetRange.Width)) { 2996 2997 if (isFromSystemMacro(S, CC)) 2998 return; 2999 3000 unsigned DiagID = diag::warn_impcast_integer_sign; 3001 3002 // Traditionally, gcc has warned about this under -Wsign-compare. 3003 // We also want to warn about it in -Wconversion. 3004 // So if -Wconversion is off, use a completely identical diagnostic 3005 // in the sign-compare group. 3006 // The conditional-checking code will 3007 if (ICContext) { 3008 DiagID = diag::warn_impcast_integer_sign_conditional; 3009 *ICContext = true; 3010 } 3011 3012 return DiagnoseImpCast(S, E, T, CC, DiagID); 3013 } 3014 3015 // Diagnose conversions between different enumeration types. 3016 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 3017 // type, to give us better diagnostics. 3018 QualType SourceType = E->getType(); 3019 if (!S.getLangOptions().CPlusPlus) { 3020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3021 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3022 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 3023 SourceType = S.Context.getTypeDeclType(Enum); 3024 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 3025 } 3026 } 3027 3028 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 3029 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 3030 if ((SourceEnum->getDecl()->getIdentifier() || 3031 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 3032 (TargetEnum->getDecl()->getIdentifier() || 3033 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 3034 SourceEnum != TargetEnum) { 3035 if (isFromSystemMacro(S, CC)) 3036 return; 3037 3038 return DiagnoseImpCast(S, E, SourceType, T, CC, 3039 diag::warn_impcast_different_enum_types); 3040 } 3041 3042 return; 3043} 3044 3045void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 3046 3047void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 3048 SourceLocation CC, bool &ICContext) { 3049 E = E->IgnoreParenImpCasts(); 3050 3051 if (isa<ConditionalOperator>(E)) 3052 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 3053 3054 AnalyzeImplicitConversions(S, E, CC); 3055 if (E->getType() != T) 3056 return CheckImplicitConversion(S, E, T, CC, &ICContext); 3057 return; 3058} 3059 3060void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 3061 SourceLocation CC = E->getQuestionLoc(); 3062 3063 AnalyzeImplicitConversions(S, E->getCond(), CC); 3064 3065 bool Suspicious = false; 3066 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 3067 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 3068 3069 // If -Wconversion would have warned about either of the candidates 3070 // for a signedness conversion to the context type... 3071 if (!Suspicious) return; 3072 3073 // ...but it's currently ignored... 3074 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 3075 CC)) 3076 return; 3077 3078 // ...and -Wsign-compare isn't... 3079 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC)) 3080 return; 3081 3082 // ...then check whether it would have warned about either of the 3083 // candidates for a signedness conversion to the condition type. 3084 if (E->getType() != T) { 3085 Suspicious = false; 3086 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 3087 E->getType(), CC, &Suspicious); 3088 if (!Suspicious) 3089 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 3090 E->getType(), CC, &Suspicious); 3091 if (!Suspicious) 3092 return; 3093 } 3094 3095 // If so, emit a diagnostic under -Wsign-compare. 3096 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts(); 3097 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts(); 3098 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional) 3099 << lex->getType() << rex->getType() 3100 << lex->getSourceRange() << rex->getSourceRange(); 3101} 3102 3103/// AnalyzeImplicitConversions - Find and report any interesting 3104/// implicit conversions in the given expression. There are a couple 3105/// of competing diagnostics here, -Wconversion and -Wsign-compare. 3106void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 3107 QualType T = OrigE->getType(); 3108 Expr *E = OrigE->IgnoreParenImpCasts(); 3109 3110 // For conditional operators, we analyze the arguments as if they 3111 // were being fed directly into the output. 3112 if (isa<ConditionalOperator>(E)) { 3113 ConditionalOperator *CO = cast<ConditionalOperator>(E); 3114 CheckConditionalOperator(S, CO, T); 3115 return; 3116 } 3117 3118 // Go ahead and check any implicit conversions we might have skipped. 3119 // The non-canonical typecheck is just an optimization; 3120 // CheckImplicitConversion will filter out dead implicit conversions. 3121 if (E->getType() != T) 3122 CheckImplicitConversion(S, E, T, CC); 3123 3124 // Now continue drilling into this expression. 3125 3126 // Skip past explicit casts. 3127 if (isa<ExplicitCastExpr>(E)) { 3128 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 3129 return AnalyzeImplicitConversions(S, E, CC); 3130 } 3131 3132 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3133 // Do a somewhat different check with comparison operators. 3134 if (BO->isComparisonOp()) 3135 return AnalyzeComparison(S, BO); 3136 3137 // And with assignments and compound assignments. 3138 if (BO->isAssignmentOp()) 3139 return AnalyzeAssignment(S, BO); 3140 } 3141 3142 // These break the otherwise-useful invariant below. Fortunately, 3143 // we don't really need to recurse into them, because any internal 3144 // expressions should have been analyzed already when they were 3145 // built into statements. 3146 if (isa<StmtExpr>(E)) return; 3147 3148 // Don't descend into unevaluated contexts. 3149 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 3150 3151 // Now just recurse over the expression's children. 3152 CC = E->getExprLoc(); 3153 for (Stmt::child_range I = E->children(); I; ++I) 3154 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC); 3155} 3156 3157} // end anonymous namespace 3158 3159/// Diagnoses "dangerous" implicit conversions within the given 3160/// expression (which is a full expression). Implements -Wconversion 3161/// and -Wsign-compare. 3162/// 3163/// \param CC the "context" location of the implicit conversion, i.e. 3164/// the most location of the syntactic entity requiring the implicit 3165/// conversion 3166void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 3167 // Don't diagnose in unevaluated contexts. 3168 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 3169 return; 3170 3171 // Don't diagnose for value- or type-dependent expressions. 3172 if (E->isTypeDependent() || E->isValueDependent()) 3173 return; 3174 3175 // This is not the right CC for (e.g.) a variable initialization. 3176 AnalyzeImplicitConversions(*this, E, CC); 3177} 3178 3179void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 3180 FieldDecl *BitField, 3181 Expr *Init) { 3182 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 3183} 3184 3185/// CheckParmsForFunctionDef - Check that the parameters of the given 3186/// function are appropriate for the definition of a function. This 3187/// takes care of any checks that cannot be performed on the 3188/// declaration itself, e.g., that the types of each of the function 3189/// parameters are complete. 3190bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 3191 bool CheckParameterNames) { 3192 bool HasInvalidParm = false; 3193 for (; P != PEnd; ++P) { 3194 ParmVarDecl *Param = *P; 3195 3196 // C99 6.7.5.3p4: the parameters in a parameter type list in a 3197 // function declarator that is part of a function definition of 3198 // that function shall not have incomplete type. 3199 // 3200 // This is also C++ [dcl.fct]p6. 3201 if (!Param->isInvalidDecl() && 3202 RequireCompleteType(Param->getLocation(), Param->getType(), 3203 diag::err_typecheck_decl_incomplete_type)) { 3204 Param->setInvalidDecl(); 3205 HasInvalidParm = true; 3206 } 3207 3208 // C99 6.9.1p5: If the declarator includes a parameter type list, the 3209 // declaration of each parameter shall include an identifier. 3210 if (CheckParameterNames && 3211 Param->getIdentifier() == 0 && 3212 !Param->isImplicit() && 3213 !getLangOptions().CPlusPlus) 3214 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 3215 3216 // C99 6.7.5.3p12: 3217 // If the function declarator is not part of a definition of that 3218 // function, parameters may have incomplete type and may use the [*] 3219 // notation in their sequences of declarator specifiers to specify 3220 // variable length array types. 3221 QualType PType = Param->getOriginalType(); 3222 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 3223 if (AT->getSizeModifier() == ArrayType::Star) { 3224 // FIXME: This diagnosic should point the the '[*]' if source-location 3225 // information is added for it. 3226 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 3227 } 3228 } 3229 } 3230 3231 return HasInvalidParm; 3232} 3233 3234/// CheckCastAlign - Implements -Wcast-align, which warns when a 3235/// pointer cast increases the alignment requirements. 3236void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 3237 // This is actually a lot of work to potentially be doing on every 3238 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 3239 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 3240 TRange.getBegin()) 3241 == Diagnostic::Ignored) 3242 return; 3243 3244 // Ignore dependent types. 3245 if (T->isDependentType() || Op->getType()->isDependentType()) 3246 return; 3247 3248 // Require that the destination be a pointer type. 3249 const PointerType *DestPtr = T->getAs<PointerType>(); 3250 if (!DestPtr) return; 3251 3252 // If the destination has alignment 1, we're done. 3253 QualType DestPointee = DestPtr->getPointeeType(); 3254 if (DestPointee->isIncompleteType()) return; 3255 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 3256 if (DestAlign.isOne()) return; 3257 3258 // Require that the source be a pointer type. 3259 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 3260 if (!SrcPtr) return; 3261 QualType SrcPointee = SrcPtr->getPointeeType(); 3262 3263 // Whitelist casts from cv void*. We already implicitly 3264 // whitelisted casts to cv void*, since they have alignment 1. 3265 // Also whitelist casts involving incomplete types, which implicitly 3266 // includes 'void'. 3267 if (SrcPointee->isIncompleteType()) return; 3268 3269 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 3270 if (SrcAlign >= DestAlign) return; 3271 3272 Diag(TRange.getBegin(), diag::warn_cast_align) 3273 << Op->getType() << T 3274 << static_cast<unsigned>(SrcAlign.getQuantity()) 3275 << static_cast<unsigned>(DestAlign.getQuantity()) 3276 << TRange << Op->getSourceRange(); 3277} 3278 3279static void CheckArrayAccess_Check(Sema &S, 3280 const clang::ArraySubscriptExpr *E) { 3281 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts(); 3282 const ConstantArrayType *ArrayTy = 3283 S.Context.getAsConstantArrayType(BaseExpr->getType()); 3284 if (!ArrayTy) 3285 return; 3286 3287 const Expr *IndexExpr = E->getIdx(); 3288 if (IndexExpr->isValueDependent()) 3289 return; 3290 llvm::APSInt index; 3291 if (!IndexExpr->isIntegerConstantExpr(index, S.Context)) 3292 return; 3293 3294 if (index.isUnsigned() || !index.isNegative()) { 3295 llvm::APInt size = ArrayTy->getSize(); 3296 if (!size.isStrictlyPositive()) 3297 return; 3298 if (size.getBitWidth() > index.getBitWidth()) 3299 index = index.sext(size.getBitWidth()); 3300 else if (size.getBitWidth() < index.getBitWidth()) 3301 size = size.sext(index.getBitWidth()); 3302 3303 if (index.slt(size)) 3304 return; 3305 3306 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr, 3307 S.PDiag(diag::warn_array_index_exceeds_bounds) 3308 << index.toString(10, true) 3309 << size.toString(10, true) 3310 << IndexExpr->getSourceRange()); 3311 } else { 3312 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr, 3313 S.PDiag(diag::warn_array_index_precedes_bounds) 3314 << index.toString(10, true) 3315 << IndexExpr->getSourceRange()); 3316 } 3317 3318 const NamedDecl *ND = NULL; 3319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 3320 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 3321 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 3322 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 3323 if (ND) 3324 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 3325 S.PDiag(diag::note_array_index_out_of_bounds) 3326 << ND->getDeclName()); 3327} 3328 3329void Sema::CheckArrayAccess(const Expr *expr) { 3330 while (true) { 3331 expr = expr->IgnoreParens(); 3332 switch (expr->getStmtClass()) { 3333 case Stmt::ArraySubscriptExprClass: 3334 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr)); 3335 return; 3336 case Stmt::ConditionalOperatorClass: { 3337 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 3338 if (const Expr *lhs = cond->getLHS()) 3339 CheckArrayAccess(lhs); 3340 if (const Expr *rhs = cond->getRHS()) 3341 CheckArrayAccess(rhs); 3342 return; 3343 } 3344 default: 3345 return; 3346 } 3347 } 3348} 3349