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