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