SemaChecking.cpp revision c0cd21d2a3301a7a88e0052aebdd09c2441f826d
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 "Sema.h" 16#include "clang/Analysis/AnalysisContext.h" 17#include "clang/Analysis/CFG.h" 18#include "clang/Analysis/Analyses/ReachableCode.h" 19#include "clang/Analysis/Analyses/PrintfFormatString.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CharUnits.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/LiteralSupport.h" 29#include "clang/Lex/Preprocessor.h" 30#include "llvm/ADT/BitVector.h" 31#include "llvm/ADT/STLExtras.h" 32#include <limits> 33#include <queue> 34using namespace clang; 35 36/// getLocationOfStringLiteralByte - Return a source location that points to the 37/// specified byte of the specified string literal. 38/// 39/// Strings are amazingly complex. They can be formed from multiple tokens and 40/// can have escape sequences in them in addition to the usual trigraph and 41/// escaped newline business. This routine handles this complexity. 42/// 43SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 44 unsigned ByteNo) const { 45 assert(!SL->isWide() && "This doesn't work for wide strings yet"); 46 47 // Loop over all of the tokens in this string until we find the one that 48 // contains the byte we're looking for. 49 unsigned TokNo = 0; 50 while (1) { 51 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); 52 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); 53 54 // Get the spelling of the string so that we can get the data that makes up 55 // the string literal, not the identifier for the macro it is potentially 56 // expanded through. 57 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); 58 59 // Re-lex the token to get its length and original spelling. 60 std::pair<FileID, unsigned> LocInfo = 61 SourceMgr.getDecomposedLoc(StrTokSpellingLoc); 62 std::pair<const char *,const char *> Buffer = 63 SourceMgr.getBufferData(LocInfo.first); 64 const char *StrData = Buffer.first+LocInfo.second; 65 66 // Create a langops struct and enable trigraphs. This is sufficient for 67 // relexing tokens. 68 LangOptions LangOpts; 69 LangOpts.Trigraphs = true; 70 71 // Create a lexer starting at the beginning of this token. 72 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData, 73 Buffer.second); 74 Token TheTok; 75 TheLexer.LexFromRawLexer(TheTok); 76 77 // Use the StringLiteralParser to compute the length of the string in bytes. 78 StringLiteralParser SLP(&TheTok, 1, PP); 79 unsigned TokNumBytes = SLP.GetStringLength(); 80 81 // If the byte is in this token, return the location of the byte. 82 if (ByteNo < TokNumBytes || 83 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { 84 unsigned Offset = 85 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); 86 87 // Now that we know the offset of the token in the spelling, use the 88 // preprocessor to get the offset in the original source. 89 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); 90 } 91 92 // Move to the next string token. 93 ++TokNo; 94 ByteNo -= TokNumBytes; 95 } 96} 97 98/// CheckablePrintfAttr - does a function call have a "printf" attribute 99/// and arguments that merit checking? 100bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 101 if (Format->getType() == "printf") return true; 102 if (Format->getType() == "printf0") { 103 // printf0 allows null "format" string; if so don't check format/args 104 unsigned format_idx = Format->getFormatIdx() - 1; 105 // Does the index refer to the implicit object argument? 106 if (isa<CXXMemberCallExpr>(TheCall)) { 107 if (format_idx == 0) 108 return false; 109 --format_idx; 110 } 111 if (format_idx < TheCall->getNumArgs()) { 112 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 113 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 114 return true; 115 } 116 } 117 return false; 118} 119 120Action::OwningExprResult 121Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 122 OwningExprResult TheCallResult(Owned(TheCall)); 123 124 switch (BuiltinID) { 125 case Builtin::BI__builtin___CFStringMakeConstantString: 126 assert(TheCall->getNumArgs() == 1 && 127 "Wrong # arguments to builtin CFStringMakeConstantString"); 128 if (CheckObjCString(TheCall->getArg(0))) 129 return ExprError(); 130 break; 131 case Builtin::BI__builtin_stdarg_start: 132 case Builtin::BI__builtin_va_start: 133 if (SemaBuiltinVAStart(TheCall)) 134 return ExprError(); 135 break; 136 case Builtin::BI__builtin_isgreater: 137 case Builtin::BI__builtin_isgreaterequal: 138 case Builtin::BI__builtin_isless: 139 case Builtin::BI__builtin_islessequal: 140 case Builtin::BI__builtin_islessgreater: 141 case Builtin::BI__builtin_isunordered: 142 if (SemaBuiltinUnorderedCompare(TheCall)) 143 return ExprError(); 144 break; 145 case Builtin::BI__builtin_fpclassify: 146 if (SemaBuiltinFPClassification(TheCall, 6)) 147 return ExprError(); 148 break; 149 case Builtin::BI__builtin_isfinite: 150 case Builtin::BI__builtin_isinf: 151 case Builtin::BI__builtin_isinf_sign: 152 case Builtin::BI__builtin_isnan: 153 case Builtin::BI__builtin_isnormal: 154 if (SemaBuiltinFPClassification(TheCall, 1)) 155 return ExprError(); 156 break; 157 case Builtin::BI__builtin_return_address: 158 case Builtin::BI__builtin_frame_address: 159 if (SemaBuiltinStackAddress(TheCall)) 160 return ExprError(); 161 break; 162 case Builtin::BI__builtin_eh_return_data_regno: 163 if (SemaBuiltinEHReturnDataRegNo(TheCall)) 164 return ExprError(); 165 break; 166 case Builtin::BI__builtin_shufflevector: 167 return SemaBuiltinShuffleVector(TheCall); 168 // TheCall will be freed by the smart pointer here, but that's fine, since 169 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 170 case Builtin::BI__builtin_prefetch: 171 if (SemaBuiltinPrefetch(TheCall)) 172 return ExprError(); 173 break; 174 case Builtin::BI__builtin_object_size: 175 if (SemaBuiltinObjectSize(TheCall)) 176 return ExprError(); 177 break; 178 case Builtin::BI__builtin_longjmp: 179 if (SemaBuiltinLongjmp(TheCall)) 180 return ExprError(); 181 break; 182 case Builtin::BI__sync_fetch_and_add: 183 case Builtin::BI__sync_fetch_and_sub: 184 case Builtin::BI__sync_fetch_and_or: 185 case Builtin::BI__sync_fetch_and_and: 186 case Builtin::BI__sync_fetch_and_xor: 187 case Builtin::BI__sync_fetch_and_nand: 188 case Builtin::BI__sync_add_and_fetch: 189 case Builtin::BI__sync_sub_and_fetch: 190 case Builtin::BI__sync_and_and_fetch: 191 case Builtin::BI__sync_or_and_fetch: 192 case Builtin::BI__sync_xor_and_fetch: 193 case Builtin::BI__sync_nand_and_fetch: 194 case Builtin::BI__sync_val_compare_and_swap: 195 case Builtin::BI__sync_bool_compare_and_swap: 196 case Builtin::BI__sync_lock_test_and_set: 197 case Builtin::BI__sync_lock_release: 198 if (SemaBuiltinAtomicOverloaded(TheCall)) 199 return ExprError(); 200 break; 201 } 202 203 return move(TheCallResult); 204} 205 206/// CheckFunctionCall - Check a direct function call for various correctness 207/// and safety properties not strictly enforced by the C type system. 208bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 209 // Get the IdentifierInfo* for the called function. 210 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 211 212 // None of the checks below are needed for functions that don't have 213 // simple names (e.g., C++ conversion functions). 214 if (!FnInfo) 215 return false; 216 217 // FIXME: This mechanism should be abstracted to be less fragile and 218 // more efficient. For example, just map function ids to custom 219 // handlers. 220 221 // Printf checking. 222 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) { 223 if (CheckablePrintfAttr(Format, TheCall)) { 224 bool HasVAListArg = Format->getFirstArg() == 0; 225 if (!HasVAListArg) { 226 if (const FunctionProtoType *Proto 227 = FDecl->getType()->getAs<FunctionProtoType>()) 228 HasVAListArg = !Proto->isVariadic(); 229 } 230 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 231 HasVAListArg ? 0 : Format->getFirstArg() - 1); 232 } 233 } 234 235 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull; 236 NonNull = NonNull->getNext<NonNullAttr>()) 237 CheckNonNullArguments(NonNull, TheCall); 238 239 return false; 240} 241 242bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 243 // Printf checking. 244 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 245 if (!Format) 246 return false; 247 248 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 249 if (!V) 250 return false; 251 252 QualType Ty = V->getType(); 253 if (!Ty->isBlockPointerType()) 254 return false; 255 256 if (!CheckablePrintfAttr(Format, TheCall)) 257 return false; 258 259 bool HasVAListArg = Format->getFirstArg() == 0; 260 if (!HasVAListArg) { 261 const FunctionType *FT = 262 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 263 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 264 HasVAListArg = !Proto->isVariadic(); 265 } 266 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 267 HasVAListArg ? 0 : Format->getFirstArg() - 1); 268 269 return false; 270} 271 272/// SemaBuiltinAtomicOverloaded - We have a call to a function like 273/// __sync_fetch_and_add, which is an overloaded function based on the pointer 274/// type of its first argument. The main ActOnCallExpr routines have already 275/// promoted the types of arguments because all of these calls are prototyped as 276/// void(...). 277/// 278/// This function goes through and does final semantic checking for these 279/// builtins, 280bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) { 281 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 282 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 283 284 // Ensure that we have at least one argument to do type inference from. 285 if (TheCall->getNumArgs() < 1) 286 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 287 << 0 << TheCall->getCallee()->getSourceRange(); 288 289 // Inspect the first argument of the atomic builtin. This should always be 290 // a pointer type, whose element is an integral scalar or pointer type. 291 // Because it is a pointer type, we don't have to worry about any implicit 292 // casts here. 293 Expr *FirstArg = TheCall->getArg(0); 294 if (!FirstArg->getType()->isPointerType()) 295 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 296 << FirstArg->getType() << FirstArg->getSourceRange(); 297 298 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType(); 299 if (!ValType->isIntegerType() && !ValType->isPointerType() && 300 !ValType->isBlockPointerType()) 301 return Diag(DRE->getLocStart(), 302 diag::err_atomic_builtin_must_be_pointer_intptr) 303 << FirstArg->getType() << FirstArg->getSourceRange(); 304 305 // We need to figure out which concrete builtin this maps onto. For example, 306 // __sync_fetch_and_add with a 2 byte object turns into 307 // __sync_fetch_and_add_2. 308#define BUILTIN_ROW(x) \ 309 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 310 Builtin::BI##x##_8, Builtin::BI##x##_16 } 311 312 static const unsigned BuiltinIndices[][5] = { 313 BUILTIN_ROW(__sync_fetch_and_add), 314 BUILTIN_ROW(__sync_fetch_and_sub), 315 BUILTIN_ROW(__sync_fetch_and_or), 316 BUILTIN_ROW(__sync_fetch_and_and), 317 BUILTIN_ROW(__sync_fetch_and_xor), 318 BUILTIN_ROW(__sync_fetch_and_nand), 319 320 BUILTIN_ROW(__sync_add_and_fetch), 321 BUILTIN_ROW(__sync_sub_and_fetch), 322 BUILTIN_ROW(__sync_and_and_fetch), 323 BUILTIN_ROW(__sync_or_and_fetch), 324 BUILTIN_ROW(__sync_xor_and_fetch), 325 BUILTIN_ROW(__sync_nand_and_fetch), 326 327 BUILTIN_ROW(__sync_val_compare_and_swap), 328 BUILTIN_ROW(__sync_bool_compare_and_swap), 329 BUILTIN_ROW(__sync_lock_test_and_set), 330 BUILTIN_ROW(__sync_lock_release) 331 }; 332#undef BUILTIN_ROW 333 334 // Determine the index of the size. 335 unsigned SizeIndex; 336 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 337 case 1: SizeIndex = 0; break; 338 case 2: SizeIndex = 1; break; 339 case 4: SizeIndex = 2; break; 340 case 8: SizeIndex = 3; break; 341 case 16: SizeIndex = 4; break; 342 default: 343 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 344 << FirstArg->getType() << FirstArg->getSourceRange(); 345 } 346 347 // Each of these builtins has one pointer argument, followed by some number of 348 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 349 // that we ignore. Find out which row of BuiltinIndices to read from as well 350 // as the number of fixed args. 351 unsigned BuiltinID = FDecl->getBuiltinID(); 352 unsigned BuiltinIndex, NumFixed = 1; 353 switch (BuiltinID) { 354 default: assert(0 && "Unknown overloaded atomic builtin!"); 355 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break; 356 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break; 357 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break; 358 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break; 359 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break; 360 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break; 361 362 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break; 363 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break; 364 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break; 365 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break; 366 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break; 367 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break; 368 369 case Builtin::BI__sync_val_compare_and_swap: 370 BuiltinIndex = 12; 371 NumFixed = 2; 372 break; 373 case Builtin::BI__sync_bool_compare_and_swap: 374 BuiltinIndex = 13; 375 NumFixed = 2; 376 break; 377 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break; 378 case Builtin::BI__sync_lock_release: 379 BuiltinIndex = 15; 380 NumFixed = 0; 381 break; 382 } 383 384 // Now that we know how many fixed arguments we expect, first check that we 385 // have at least that many. 386 if (TheCall->getNumArgs() < 1+NumFixed) 387 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 388 << 0 << TheCall->getCallee()->getSourceRange(); 389 390 391 // Get the decl for the concrete builtin from this, we can tell what the 392 // concrete integer type we should convert to is. 393 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 394 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 395 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 396 FunctionDecl *NewBuiltinDecl = 397 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 398 TUScope, false, DRE->getLocStart())); 399 const FunctionProtoType *BuiltinFT = 400 NewBuiltinDecl->getType()->getAs<FunctionProtoType>(); 401 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType(); 402 403 // If the first type needs to be converted (e.g. void** -> int*), do it now. 404 if (BuiltinFT->getArgType(0) != FirstArg->getType()) { 405 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast); 406 TheCall->setArg(0, FirstArg); 407 } 408 409 // Next, walk the valid ones promoting to the right type. 410 for (unsigned i = 0; i != NumFixed; ++i) { 411 Expr *Arg = TheCall->getArg(i+1); 412 413 // If the argument is an implicit cast, then there was a promotion due to 414 // "...", just remove it now. 415 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 416 Arg = ICE->getSubExpr(); 417 ICE->setSubExpr(0); 418 ICE->Destroy(Context); 419 TheCall->setArg(i+1, Arg); 420 } 421 422 // GCC does an implicit conversion to the pointer or integer ValType. This 423 // can fail in some cases (1i -> int**), check for this error case now. 424 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 425 CXXMethodDecl *ConversionDecl = 0; 426 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, 427 ConversionDecl)) 428 return true; 429 430 // Okay, we have something that *can* be converted to the right type. Check 431 // to see if there is a potentially weird extension going on here. This can 432 // happen when you do an atomic operation on something like an char* and 433 // pass in 42. The 42 gets converted to char. This is even more strange 434 // for things like 45.123 -> char, etc. 435 // FIXME: Do this check. 436 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false); 437 TheCall->setArg(i+1, Arg); 438 } 439 440 // Switch the DeclRefExpr to refer to the new decl. 441 DRE->setDecl(NewBuiltinDecl); 442 DRE->setType(NewBuiltinDecl->getType()); 443 444 // Set the callee in the CallExpr. 445 // FIXME: This leaks the original parens and implicit casts. 446 Expr *PromotedCall = DRE; 447 UsualUnaryConversions(PromotedCall); 448 TheCall->setCallee(PromotedCall); 449 450 451 // Change the result type of the call to match the result type of the decl. 452 TheCall->setType(NewBuiltinDecl->getResultType()); 453 return false; 454} 455 456 457/// CheckObjCString - Checks that the argument to the builtin 458/// CFString constructor is correct 459/// FIXME: GCC currently emits the following warning: 460/// "warning: input conversion stopped due to an input byte that does not 461/// belong to the input codeset UTF-8" 462/// Note: It might also make sense to do the UTF-16 conversion here (would 463/// simplify the backend). 464bool Sema::CheckObjCString(Expr *Arg) { 465 Arg = Arg->IgnoreParenCasts(); 466 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 467 468 if (!Literal || Literal->isWide()) { 469 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 470 << Arg->getSourceRange(); 471 return true; 472 } 473 474 const char *Data = Literal->getStrData(); 475 unsigned Length = Literal->getByteLength(); 476 477 for (unsigned i = 0; i < Length; ++i) { 478 if (!Data[i]) { 479 Diag(getLocationOfStringLiteralByte(Literal, i), 480 diag::warn_cfstring_literal_contains_nul_character) 481 << Arg->getSourceRange(); 482 break; 483 } 484 } 485 486 return false; 487} 488 489/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 490/// Emit an error and return true on failure, return false on success. 491bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 492 Expr *Fn = TheCall->getCallee(); 493 if (TheCall->getNumArgs() > 2) { 494 Diag(TheCall->getArg(2)->getLocStart(), 495 diag::err_typecheck_call_too_many_args) 496 << 0 /*function call*/ << Fn->getSourceRange() 497 << SourceRange(TheCall->getArg(2)->getLocStart(), 498 (*(TheCall->arg_end()-1))->getLocEnd()); 499 return true; 500 } 501 502 if (TheCall->getNumArgs() < 2) { 503 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 504 << 0 /*function call*/; 505 } 506 507 // Determine whether the current function is variadic or not. 508 bool isVariadic; 509 if (CurBlock) 510 isVariadic = CurBlock->isVariadic; 511 else if (getCurFunctionDecl()) { 512 if (FunctionProtoType* FTP = 513 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) 514 isVariadic = FTP->isVariadic(); 515 else 516 isVariadic = false; 517 } else { 518 isVariadic = getCurMethodDecl()->isVariadic(); 519 } 520 521 if (!isVariadic) { 522 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 523 return true; 524 } 525 526 // Verify that the second argument to the builtin is the last argument of the 527 // current function or method. 528 bool SecondArgIsLastNamedArgument = false; 529 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 530 531 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 532 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 533 // FIXME: This isn't correct for methods (results in bogus warning). 534 // Get the last formal in the current function. 535 const ParmVarDecl *LastArg; 536 if (CurBlock) 537 LastArg = *(CurBlock->TheDecl->param_end()-1); 538 else if (FunctionDecl *FD = getCurFunctionDecl()) 539 LastArg = *(FD->param_end()-1); 540 else 541 LastArg = *(getCurMethodDecl()->param_end()-1); 542 SecondArgIsLastNamedArgument = PV == LastArg; 543 } 544 } 545 546 if (!SecondArgIsLastNamedArgument) 547 Diag(TheCall->getArg(1)->getLocStart(), 548 diag::warn_second_parameter_of_va_start_not_last_named_argument); 549 return false; 550} 551 552/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 553/// friends. This is declared to take (...), so we have to check everything. 554bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 555 if (TheCall->getNumArgs() < 2) 556 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 557 << 0 /*function call*/; 558 if (TheCall->getNumArgs() > 2) 559 return Diag(TheCall->getArg(2)->getLocStart(), 560 diag::err_typecheck_call_too_many_args) 561 << 0 /*function call*/ 562 << SourceRange(TheCall->getArg(2)->getLocStart(), 563 (*(TheCall->arg_end()-1))->getLocEnd()); 564 565 Expr *OrigArg0 = TheCall->getArg(0); 566 Expr *OrigArg1 = TheCall->getArg(1); 567 568 // Do standard promotions between the two arguments, returning their common 569 // type. 570 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 571 572 // Make sure any conversions are pushed back into the call; this is 573 // type safe since unordered compare builtins are declared as "_Bool 574 // foo(...)". 575 TheCall->setArg(0, OrigArg0); 576 TheCall->setArg(1, OrigArg1); 577 578 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent()) 579 return false; 580 581 // If the common type isn't a real floating type, then the arguments were 582 // invalid for this operation. 583 if (!Res->isRealFloatingType()) 584 return Diag(OrigArg0->getLocStart(), 585 diag::err_typecheck_call_invalid_ordered_compare) 586 << OrigArg0->getType() << OrigArg1->getType() 587 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); 588 589 return false; 590} 591 592/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 593/// __builtin_isnan and friends. This is declared to take (...), so we have 594/// to check everything. We expect the last argument to be a floating point 595/// value. 596bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 597 if (TheCall->getNumArgs() < NumArgs) 598 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 599 << 0 /*function call*/; 600 if (TheCall->getNumArgs() > NumArgs) 601 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 602 diag::err_typecheck_call_too_many_args) 603 << 0 /*function call*/ 604 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 605 (*(TheCall->arg_end()-1))->getLocEnd()); 606 607 Expr *OrigArg = TheCall->getArg(NumArgs-1); 608 609 if (OrigArg->isTypeDependent()) 610 return false; 611 612 // This operation requires a floating-point number 613 if (!OrigArg->getType()->isRealFloatingType()) 614 return Diag(OrigArg->getLocStart(), 615 diag::err_typecheck_call_invalid_unary_fp) 616 << OrigArg->getType() << OrigArg->getSourceRange(); 617 618 return false; 619} 620 621bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { 622 // The signature for these builtins is exact; the only thing we need 623 // to check is that the argument is a constant. 624 SourceLocation Loc; 625 if (!TheCall->getArg(0)->isTypeDependent() && 626 !TheCall->getArg(0)->isValueDependent() && 627 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) 628 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); 629 630 return false; 631} 632 633/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 634// This is declared to take (...), so we have to check everything. 635Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 636 if (TheCall->getNumArgs() < 3) 637 return ExprError(Diag(TheCall->getLocEnd(), 638 diag::err_typecheck_call_too_few_args) 639 << 0 /*function call*/ << TheCall->getSourceRange()); 640 641 unsigned numElements = std::numeric_limits<unsigned>::max(); 642 if (!TheCall->getArg(0)->isTypeDependent() && 643 !TheCall->getArg(1)->isTypeDependent()) { 644 QualType FAType = TheCall->getArg(0)->getType(); 645 QualType SAType = TheCall->getArg(1)->getType(); 646 647 if (!FAType->isVectorType() || !SAType->isVectorType()) { 648 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 649 << SourceRange(TheCall->getArg(0)->getLocStart(), 650 TheCall->getArg(1)->getLocEnd()); 651 return ExprError(); 652 } 653 654 if (!Context.hasSameUnqualifiedType(FAType, SAType)) { 655 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 656 << SourceRange(TheCall->getArg(0)->getLocStart(), 657 TheCall->getArg(1)->getLocEnd()); 658 return ExprError(); 659 } 660 661 numElements = FAType->getAs<VectorType>()->getNumElements(); 662 if (TheCall->getNumArgs() != numElements+2) { 663 if (TheCall->getNumArgs() < numElements+2) 664 return ExprError(Diag(TheCall->getLocEnd(), 665 diag::err_typecheck_call_too_few_args) 666 << 0 /*function call*/ << TheCall->getSourceRange()); 667 return ExprError(Diag(TheCall->getLocEnd(), 668 diag::err_typecheck_call_too_many_args) 669 << 0 /*function call*/ << TheCall->getSourceRange()); 670 } 671 } 672 673 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 674 if (TheCall->getArg(i)->isTypeDependent() || 675 TheCall->getArg(i)->isValueDependent()) 676 continue; 677 678 llvm::APSInt Result(32); 679 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 680 return ExprError(Diag(TheCall->getLocStart(), 681 diag::err_shufflevector_nonconstant_argument) 682 << TheCall->getArg(i)->getSourceRange()); 683 684 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 685 return ExprError(Diag(TheCall->getLocStart(), 686 diag::err_shufflevector_argument_too_large) 687 << TheCall->getArg(i)->getSourceRange()); 688 } 689 690 llvm::SmallVector<Expr*, 32> exprs; 691 692 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 693 exprs.push_back(TheCall->getArg(i)); 694 TheCall->setArg(i, 0); 695 } 696 697 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 698 exprs.size(), exprs[0]->getType(), 699 TheCall->getCallee()->getLocStart(), 700 TheCall->getRParenLoc())); 701} 702 703/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 704// This is declared to take (const void*, ...) and can take two 705// optional constant int args. 706bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 707 unsigned NumArgs = TheCall->getNumArgs(); 708 709 if (NumArgs > 3) 710 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) 711 << 0 /*function call*/ << TheCall->getSourceRange(); 712 713 // Argument 0 is checked for us and the remaining arguments must be 714 // constant integers. 715 for (unsigned i = 1; i != NumArgs; ++i) { 716 Expr *Arg = TheCall->getArg(i); 717 if (Arg->isTypeDependent()) 718 continue; 719 720 if (!Arg->getType()->isIntegralType()) 721 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type) 722 << Arg->getSourceRange(); 723 724 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast); 725 TheCall->setArg(i, Arg); 726 727 if (Arg->isValueDependent()) 728 continue; 729 730 llvm::APSInt Result; 731 if (!Arg->isIntegerConstantExpr(Result, Context)) 732 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice) 733 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 734 735 // FIXME: gcc issues a warning and rewrites these to 0. These 736 // seems especially odd for the third argument since the default 737 // is 3. 738 if (i == 1) { 739 if (Result.getLimitedValue() > 1) 740 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 741 << "0" << "1" << Arg->getSourceRange(); 742 } else { 743 if (Result.getLimitedValue() > 3) 744 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 745 << "0" << "3" << Arg->getSourceRange(); 746 } 747 } 748 749 return false; 750} 751 752/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the 753/// operand must be an integer constant. 754bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) { 755 llvm::APSInt Result; 756 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context)) 757 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice) 758 << TheCall->getArg(0)->getSourceRange(); 759 760 return false; 761} 762 763 764/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 765/// int type). This simply type checks that type is one of the defined 766/// constants (0-3). 767// For compatability check 0-3, llvm only handles 0 and 2. 768bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 769 Expr *Arg = TheCall->getArg(1); 770 if (Arg->isTypeDependent()) 771 return false; 772 773 QualType ArgType = Arg->getType(); 774 const BuiltinType *BT = ArgType->getAs<BuiltinType>(); 775 llvm::APSInt Result(32); 776 if (!BT || BT->getKind() != BuiltinType::Int) 777 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 778 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 779 780 if (Arg->isValueDependent()) 781 return false; 782 783 if (!Arg->isIntegerConstantExpr(Result, Context)) { 784 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) 785 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 786 } 787 788 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 789 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 790 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 791 } 792 793 return false; 794} 795 796/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 797/// This checks that val is a constant 1. 798bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 799 Expr *Arg = TheCall->getArg(1); 800 if (Arg->isTypeDependent() || Arg->isValueDependent()) 801 return false; 802 803 llvm::APSInt Result(32); 804 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1) 805 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 806 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 807 808 return false; 809} 810 811// Handle i > 1 ? "x" : "y", recursivelly 812bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 813 bool HasVAListArg, 814 unsigned format_idx, unsigned firstDataArg) { 815 if (E->isTypeDependent() || E->isValueDependent()) 816 return false; 817 818 switch (E->getStmtClass()) { 819 case Stmt::ConditionalOperatorClass: { 820 const ConditionalOperator *C = cast<ConditionalOperator>(E); 821 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, 822 HasVAListArg, format_idx, firstDataArg) 823 && SemaCheckStringLiteral(C->getRHS(), TheCall, 824 HasVAListArg, format_idx, firstDataArg); 825 } 826 827 case Stmt::ImplicitCastExprClass: { 828 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); 829 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 830 format_idx, firstDataArg); 831 } 832 833 case Stmt::ParenExprClass: { 834 const ParenExpr *Expr = cast<ParenExpr>(E); 835 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, 836 format_idx, firstDataArg); 837 } 838 839 case Stmt::DeclRefExprClass: { 840 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 841 842 // As an exception, do not flag errors for variables binding to 843 // const string literals. 844 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 845 bool isConstant = false; 846 QualType T = DR->getType(); 847 848 if (const ArrayType *AT = Context.getAsArrayType(T)) { 849 isConstant = AT->getElementType().isConstant(Context); 850 } else if (const PointerType *PT = T->getAs<PointerType>()) { 851 isConstant = T.isConstant(Context) && 852 PT->getPointeeType().isConstant(Context); 853 } 854 855 if (isConstant) { 856 if (const Expr *Init = VD->getAnyInitializer()) 857 return SemaCheckStringLiteral(Init, TheCall, 858 HasVAListArg, format_idx, firstDataArg); 859 } 860 861 // For vprintf* functions (i.e., HasVAListArg==true), we add a 862 // special check to see if the format string is a function parameter 863 // of the function calling the printf function. If the function 864 // has an attribute indicating it is a printf-like function, then we 865 // should suppress warnings concerning non-literals being used in a call 866 // to a vprintf function. For example: 867 // 868 // void 869 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 870 // va_list ap; 871 // va_start(ap, fmt); 872 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 873 // ... 874 // 875 // 876 // FIXME: We don't have full attribute support yet, so just check to see 877 // if the argument is a DeclRefExpr that references a parameter. We'll 878 // add proper support for checking the attribute later. 879 if (HasVAListArg) 880 if (isa<ParmVarDecl>(VD)) 881 return true; 882 } 883 884 return false; 885 } 886 887 case Stmt::CallExprClass: { 888 const CallExpr *CE = cast<CallExpr>(E); 889 if (const ImplicitCastExpr *ICE 890 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 893 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 894 unsigned ArgIndex = FA->getFormatIdx(); 895 const Expr *Arg = CE->getArg(ArgIndex - 1); 896 897 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 898 format_idx, firstDataArg); 899 } 900 } 901 } 902 } 903 904 return false; 905 } 906 case Stmt::ObjCStringLiteralClass: 907 case Stmt::StringLiteralClass: { 908 const StringLiteral *StrE = NULL; 909 910 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 911 StrE = ObjCFExpr->getString(); 912 else 913 StrE = cast<StringLiteral>(E); 914 915 if (StrE) { 916 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, 917 firstDataArg); 918 return true; 919 } 920 921 return false; 922 } 923 924 default: 925 return false; 926 } 927} 928 929void 930Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 931 const CallExpr *TheCall) { 932 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end(); 933 i != e; ++i) { 934 const Expr *ArgExpr = TheCall->getArg(*i); 935 if (ArgExpr->isNullPointerConstant(Context, 936 Expr::NPC_ValueDependentIsNotNull)) 937 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg) 938 << ArgExpr->getSourceRange(); 939 } 940} 941 942/// CheckPrintfArguments - Check calls to printf (and similar functions) for 943/// correct use of format strings. 944/// 945/// HasVAListArg - A predicate indicating whether the printf-like 946/// function is passed an explicit va_arg argument (e.g., vprintf) 947/// 948/// format_idx - The index into Args for the format string. 949/// 950/// Improper format strings to functions in the printf family can be 951/// the source of bizarre bugs and very serious security holes. A 952/// good source of information is available in the following paper 953/// (which includes additional references): 954/// 955/// FormatGuard: Automatic Protection From printf Format String 956/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. 957/// 958/// Functionality implemented: 959/// 960/// We can statically check the following properties for string 961/// literal format strings for non v.*printf functions (where the 962/// arguments are passed directly): 963// 964/// (1) Are the number of format conversions equal to the number of 965/// data arguments? 966/// 967/// (2) Does each format conversion correctly match the type of the 968/// corresponding data argument? (TODO) 969/// 970/// Moreover, for all printf functions we can: 971/// 972/// (3) Check for a missing format string (when not caught by type checking). 973/// 974/// (4) Check for no-operation flags; e.g. using "#" with format 975/// conversion 'c' (TODO) 976/// 977/// (5) Check the use of '%n', a major source of security holes. 978/// 979/// (6) Check for malformed format conversions that don't specify anything. 980/// 981/// (7) Check for empty format strings. e.g: printf(""); 982/// 983/// (8) Check that the format string is a wide literal. 984/// 985/// All of these checks can be done by parsing the format string. 986/// 987/// For now, we ONLY do (1), (3), (5), (6), (7), and (8). 988void 989Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, 990 unsigned format_idx, unsigned firstDataArg) { 991 const Expr *Fn = TheCall->getCallee(); 992 993 // The way the format attribute works in GCC, the implicit this argument 994 // of member functions is counted. However, it doesn't appear in our own 995 // lists, so decrement format_idx in that case. 996 if (isa<CXXMemberCallExpr>(TheCall)) { 997 // Catch a format attribute mistakenly referring to the object argument. 998 if (format_idx == 0) 999 return; 1000 --format_idx; 1001 if(firstDataArg != 0) 1002 --firstDataArg; 1003 } 1004 1005 // CHECK: printf-like function is called with no format string. 1006 if (format_idx >= TheCall->getNumArgs()) { 1007 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) 1008 << Fn->getSourceRange(); 1009 return; 1010 } 1011 1012 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 1013 1014 // CHECK: format string is not a string literal. 1015 // 1016 // Dynamically generated format strings are difficult to 1017 // automatically vet at compile time. Requiring that format strings 1018 // are string literals: (1) permits the checking of format strings by 1019 // the compiler and thereby (2) can practically remove the source of 1020 // many format string exploits. 1021 1022 // Format string can be either ObjC string (e.g. @"%d") or 1023 // C string (e.g. "%d") 1024 // ObjC string uses the same format specifiers as C string, so we can use 1025 // the same format string checking logic for both ObjC and C strings. 1026 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1027 firstDataArg)) 1028 return; // Literal format string found, check done! 1029 1030 // If there are no arguments specified, warn with -Wformat-security, otherwise 1031 // warn only with -Wformat-nonliteral. 1032 if (TheCall->getNumArgs() == format_idx+1) 1033 Diag(TheCall->getArg(format_idx)->getLocStart(), 1034 diag::warn_printf_nonliteral_noargs) 1035 << OrigFormatExpr->getSourceRange(); 1036 else 1037 Diag(TheCall->getArg(format_idx)->getLocStart(), 1038 diag::warn_printf_nonliteral) 1039 << OrigFormatExpr->getSourceRange(); 1040} 1041 1042namespace { 1043class CheckPrintfHandler : public analyze_printf::FormatStringHandler { 1044 Sema &S; 1045 const StringLiteral *FExpr; 1046 const Expr *OrigFormatExpr; 1047 unsigned NumConversions; 1048 const unsigned NumDataArgs; 1049 const bool IsObjCLiteral; 1050 const char *Beg; // Start of format string. 1051 const bool HasVAListArg; 1052 const CallExpr *TheCall; 1053 unsigned FormatIdx; 1054public: 1055 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1056 const Expr *origFormatExpr, 1057 unsigned numDataArgs, bool isObjCLiteral, 1058 const char *beg, bool hasVAListArg, 1059 const CallExpr *theCall, unsigned formatIdx) 1060 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1061 NumConversions(0), NumDataArgs(numDataArgs), 1062 IsObjCLiteral(isObjCLiteral), Beg(beg), 1063 HasVAListArg(hasVAListArg), 1064 TheCall(theCall), FormatIdx(formatIdx) {} 1065 1066 void DoneProcessing(); 1067 1068 void HandleIncompleteFormatSpecifier(const char *startSpecifier, 1069 unsigned specifierLen); 1070 1071 void 1072 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS, 1073 const char *startSpecifier, 1074 unsigned specifierLen); 1075 1076 void HandleNullChar(const char *nullCharacter); 1077 1078 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS, 1079 const char *startSpecifier, 1080 unsigned specifierLen); 1081private: 1082 SourceRange getFormatStringRange(); 1083 SourceRange getFormatSpecifierRange(const char *startSpecifier, 1084 unsigned specifierLen); 1085 SourceLocation getLocationOfByte(const char *x); 1086 1087 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, 1088 unsigned MissingArgDiag, unsigned BadTypeDiag, 1089 const char *startSpecifier, unsigned specifierLen); 1090 void HandleFlags(const analyze_printf::FormatSpecifier &FS, 1091 llvm::StringRef flag, llvm::StringRef cspec, 1092 const char *startSpecifier, unsigned specifierLen); 1093 1094 const Expr *getDataArg(unsigned i) const; 1095}; 1096} 1097 1098SourceRange CheckPrintfHandler::getFormatStringRange() { 1099 return OrigFormatExpr->getSourceRange(); 1100} 1101 1102SourceRange CheckPrintfHandler:: 1103getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1104 return SourceRange(getLocationOfByte(startSpecifier), 1105 getLocationOfByte(startSpecifier+specifierLen-1)); 1106} 1107 1108SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) { 1109 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1110} 1111 1112void CheckPrintfHandler:: 1113HandleIncompleteFormatSpecifier(const char *startSpecifier, 1114 unsigned specifierLen) { 1115 SourceLocation Loc = getLocationOfByte(startSpecifier); 1116 S.Diag(Loc, diag::warn_printf_incomplete_specifier) 1117 << getFormatSpecifierRange(startSpecifier, specifierLen); 1118} 1119 1120void CheckPrintfHandler:: 1121HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS, 1122 const char *startSpecifier, 1123 unsigned specifierLen) { 1124 1125 ++NumConversions; 1126 const analyze_printf::ConversionSpecifier &CS = 1127 FS.getConversionSpecifier(); 1128 SourceLocation Loc = getLocationOfByte(CS.getStart()); 1129 S.Diag(Loc, diag::warn_printf_invalid_conversion) 1130 << llvm::StringRef(CS.getStart(), CS.getLength()) 1131 << getFormatSpecifierRange(startSpecifier, specifierLen); 1132} 1133 1134void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) { 1135 // The presence of a null character is likely an error. 1136 S.Diag(getLocationOfByte(nullCharacter), 1137 diag::warn_printf_format_string_contains_null_char) 1138 << getFormatStringRange(); 1139} 1140 1141const Expr *CheckPrintfHandler::getDataArg(unsigned i) const { 1142 return TheCall->getArg(FormatIdx + i); 1143} 1144 1145 1146 1147void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS, 1148 llvm::StringRef flag, 1149 llvm::StringRef cspec, 1150 const char *startSpecifier, 1151 unsigned specifierLen) { 1152 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier(); 1153 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag) 1154 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen); 1155} 1156 1157bool 1158CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt, 1159 unsigned MissingArgDiag, 1160 unsigned BadTypeDiag, 1161 const char *startSpecifier, 1162 unsigned specifierLen) { 1163 1164 if (Amt.hasDataArgument()) { 1165 ++NumConversions; 1166 if (!HasVAListArg) { 1167 if (NumConversions > NumDataArgs) { 1168 S.Diag(getLocationOfByte(Amt.getStart()), MissingArgDiag) 1169 << getFormatSpecifierRange(startSpecifier, specifierLen); 1170 // Don't do any more checking. We will just emit 1171 // spurious errors. 1172 return false; 1173 } 1174 1175 // Type check the data argument. It should be an 'int'. 1176 // Although not in conformance with C99, we also allow the argument to be 1177 // an 'unsigned int' as that is a reasonably safe case. GCC also 1178 // doesn't emit a warning for that case. 1179 const Expr *Arg = getDataArg(NumConversions); 1180 QualType T = Arg->getType(); 1181 1182 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1183 assert(ATR.isValid()); 1184 1185 if (!ATR.matchesType(S.Context, T)) { 1186 S.Diag(getLocationOfByte(Amt.getStart()), BadTypeDiag) 1187 << ATR.getRepresentativeType(S.Context) << T 1188 << getFormatSpecifierRange(startSpecifier, specifierLen) 1189 << Arg->getSourceRange(); 1190 // Don't do any more checking. We will just emit 1191 // spurious errors. 1192 return false; 1193 } 1194 } 1195 } 1196 return true; 1197} 1198 1199bool 1200CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier 1201 &FS, 1202 const char *startSpecifier, 1203 unsigned specifierLen) { 1204 1205 using namespace analyze_printf; 1206 const ConversionSpecifier &CS = FS.getConversionSpecifier(); 1207 1208 // First check if the field width, precision, and conversion specifier 1209 // have matching data arguments. 1210 if (!HandleAmount(FS.getFieldWidth(), 1211 diag::warn_printf_asterisk_width_missing_arg, 1212 diag::warn_printf_asterisk_width_wrong_type, 1213 startSpecifier, specifierLen)) { 1214 return false; 1215 } 1216 1217 if (!HandleAmount(FS.getPrecision(), 1218 diag::warn_printf_asterisk_precision_missing_arg, 1219 diag::warn_printf_asterisk_precision_wrong_type, 1220 startSpecifier, specifierLen)) { 1221 return false; 1222 } 1223 1224 // Check for using an Objective-C specific conversion specifier 1225 // in a non-ObjC literal. 1226 if (!IsObjCLiteral && CS.isObjCArg()) { 1227 HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen); 1228 1229 // Continue checking the other format specifiers. 1230 return true; 1231 } 1232 1233 if (!CS.consumesDataArgument()) { 1234 // FIXME: Technically specifying a precision or field width here 1235 // makes no sense. Worth issuing a warning at some point. 1236 return true; 1237 } 1238 1239 ++NumConversions; 1240 1241 // Are we using '%n'? Issue a warning about this being 1242 // a possible security issue. 1243 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) { 1244 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back) 1245 << getFormatSpecifierRange(startSpecifier, specifierLen); 1246 // Continue checking the other format specifiers. 1247 return true; 1248 } 1249 1250 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) { 1251 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified) 1252 S.Diag(getLocationOfByte(CS.getStart()), 1253 diag::warn_printf_nonsensical_precision) 1254 << CS.getCharacters() 1255 << getFormatSpecifierRange(startSpecifier, specifierLen); 1256 } 1257 if (CS.getKind() == ConversionSpecifier::VoidPtrArg || 1258 CS.getKind() == ConversionSpecifier::CStrArg) { 1259 // FIXME: Instead of using "0", "+", etc., eventually get them from 1260 // the FormatSpecifier. 1261 if (FS.hasLeadingZeros()) 1262 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen); 1263 if (FS.hasPlusPrefix()) 1264 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen); 1265 if (FS.hasSpacePrefix()) 1266 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen); 1267 } 1268 1269 // The remaining checks depend on the data arguments. 1270 if (HasVAListArg) 1271 return true; 1272 1273 if (NumConversions > NumDataArgs) { 1274 S.Diag(getLocationOfByte(CS.getStart()), 1275 diag::warn_printf_insufficient_data_args) 1276 << getFormatSpecifierRange(startSpecifier, specifierLen); 1277 // Don't do any more checking. 1278 return false; 1279 } 1280 1281 // Now type check the data expression that matches the 1282 // format specifier. 1283 const Expr *Ex = getDataArg(NumConversions); 1284 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 1285 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 1286 // Check if we didn't match because of an implicit cast from a 'char' 1287 // or 'short' to an 'int'. This is done because printf is a varargs 1288 // function. 1289 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 1290 if (ICE->getType() == S.Context.IntTy) 1291 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType())) 1292 return true; 1293 1294 S.Diag(getLocationOfByte(CS.getStart()), 1295 diag::warn_printf_conversion_argument_type_mismatch) 1296 << ATR.getRepresentativeType(S.Context) << Ex->getType() 1297 << getFormatSpecifierRange(startSpecifier, specifierLen) 1298 << Ex->getSourceRange(); 1299 } 1300 1301 return true; 1302} 1303 1304void CheckPrintfHandler::DoneProcessing() { 1305 // Does the number of data arguments exceed the number of 1306 // format conversions in the format string? 1307 if (!HasVAListArg && NumConversions < NumDataArgs) 1308 S.Diag(getDataArg(NumConversions+1)->getLocStart(), 1309 diag::warn_printf_too_many_data_args) 1310 << getFormatStringRange(); 1311} 1312 1313void Sema::CheckPrintfString(const StringLiteral *FExpr, 1314 const Expr *OrigFormatExpr, 1315 const CallExpr *TheCall, bool HasVAListArg, 1316 unsigned format_idx, unsigned firstDataArg) { 1317 1318 // CHECK: is the format string a wide literal? 1319 if (FExpr->isWide()) { 1320 Diag(FExpr->getLocStart(), 1321 diag::warn_printf_format_string_is_wide_literal) 1322 << OrigFormatExpr->getSourceRange(); 1323 return; 1324 } 1325 1326 // Str - The format string. NOTE: this is NOT null-terminated! 1327 const char *Str = FExpr->getStrData(); 1328 1329 // CHECK: empty format string? 1330 unsigned StrLen = FExpr->getByteLength(); 1331 1332 if (StrLen == 0) { 1333 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) 1334 << OrigFormatExpr->getSourceRange(); 1335 return; 1336 } 1337 1338 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, 1339 TheCall->getNumArgs() - firstDataArg, 1340 isa<ObjCStringLiteral>(OrigFormatExpr), Str, 1341 HasVAListArg, TheCall, format_idx); 1342 1343 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen)) 1344 H.DoneProcessing(); 1345} 1346 1347//===--- CHECK: Return Address of Stack Variable --------------------------===// 1348 1349static DeclRefExpr* EvalVal(Expr *E); 1350static DeclRefExpr* EvalAddr(Expr* E); 1351 1352/// CheckReturnStackAddr - Check if a return statement returns the address 1353/// of a stack variable. 1354void 1355Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 1356 SourceLocation ReturnLoc) { 1357 1358 // Perform checking for returned stack addresses. 1359 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { 1360 if (DeclRefExpr *DR = EvalAddr(RetValExp)) 1361 Diag(DR->getLocStart(), diag::warn_ret_stack_addr) 1362 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1363 1364 // Skip over implicit cast expressions when checking for block expressions. 1365 RetValExp = RetValExp->IgnoreParenCasts(); 1366 1367 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp)) 1368 if (C->hasBlockDeclRefExprs()) 1369 Diag(C->getLocStart(), diag::err_ret_local_block) 1370 << C->getSourceRange(); 1371 1372 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp)) 1373 Diag(ALE->getLocStart(), diag::warn_ret_addr_label) 1374 << ALE->getSourceRange(); 1375 1376 } else if (lhsType->isReferenceType()) { 1377 // Perform checking for stack values returned by reference. 1378 // Check for a reference to the stack 1379 if (DeclRefExpr *DR = EvalVal(RetValExp)) 1380 Diag(DR->getLocStart(), diag::warn_ret_stack_ref) 1381 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); 1382 } 1383} 1384 1385/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 1386/// check if the expression in a return statement evaluates to an address 1387/// to a location on the stack. The recursion is used to traverse the 1388/// AST of the return expression, with recursion backtracking when we 1389/// encounter a subexpression that (1) clearly does not lead to the address 1390/// of a stack variable or (2) is something we cannot determine leads to 1391/// the address of a stack variable based on such local checking. 1392/// 1393/// EvalAddr processes expressions that are pointers that are used as 1394/// references (and not L-values). EvalVal handles all other values. 1395/// At the base case of the recursion is a check for a DeclRefExpr* in 1396/// the refers to a stack variable. 1397/// 1398/// This implementation handles: 1399/// 1400/// * pointer-to-pointer casts 1401/// * implicit conversions from array references to pointers 1402/// * taking the address of fields 1403/// * arbitrary interplay between "&" and "*" operators 1404/// * pointer arithmetic from an address of a stack variable 1405/// * taking the address of an array element where the array is on the stack 1406static DeclRefExpr* EvalAddr(Expr *E) { 1407 // We should only be called for evaluating pointer expressions. 1408 assert((E->getType()->isAnyPointerType() || 1409 E->getType()->isBlockPointerType() || 1410 E->getType()->isObjCQualifiedIdType()) && 1411 "EvalAddr only works on pointers"); 1412 1413 // Our "symbolic interpreter" is just a dispatch off the currently 1414 // viewed AST node. We then recursively traverse the AST by calling 1415 // EvalAddr and EvalVal appropriately. 1416 switch (E->getStmtClass()) { 1417 case Stmt::ParenExprClass: 1418 // Ignore parentheses. 1419 return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); 1420 1421 case Stmt::UnaryOperatorClass: { 1422 // The only unary operator that make sense to handle here 1423 // is AddrOf. All others don't make sense as pointers. 1424 UnaryOperator *U = cast<UnaryOperator>(E); 1425 1426 if (U->getOpcode() == UnaryOperator::AddrOf) 1427 return EvalVal(U->getSubExpr()); 1428 else 1429 return NULL; 1430 } 1431 1432 case Stmt::BinaryOperatorClass: { 1433 // Handle pointer arithmetic. All other binary operators are not valid 1434 // in this context. 1435 BinaryOperator *B = cast<BinaryOperator>(E); 1436 BinaryOperator::Opcode op = B->getOpcode(); 1437 1438 if (op != BinaryOperator::Add && op != BinaryOperator::Sub) 1439 return NULL; 1440 1441 Expr *Base = B->getLHS(); 1442 1443 // Determine which argument is the real pointer base. It could be 1444 // the RHS argument instead of the LHS. 1445 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 1446 1447 assert (Base->getType()->isPointerType()); 1448 return EvalAddr(Base); 1449 } 1450 1451 // For conditional operators we need to see if either the LHS or RHS are 1452 // valid DeclRefExpr*s. If one of them is valid, we return it. 1453 case Stmt::ConditionalOperatorClass: { 1454 ConditionalOperator *C = cast<ConditionalOperator>(E); 1455 1456 // Handle the GNU extension for missing LHS. 1457 if (Expr *lhsExpr = C->getLHS()) 1458 if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) 1459 return LHS; 1460 1461 return EvalAddr(C->getRHS()); 1462 } 1463 1464 // For casts, we need to handle conversions from arrays to 1465 // pointer values, and pointer-to-pointer conversions. 1466 case Stmt::ImplicitCastExprClass: 1467 case Stmt::CStyleCastExprClass: 1468 case Stmt::CXXFunctionalCastExprClass: { 1469 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1470 QualType T = SubExpr->getType(); 1471 1472 if (SubExpr->getType()->isPointerType() || 1473 SubExpr->getType()->isBlockPointerType() || 1474 SubExpr->getType()->isObjCQualifiedIdType()) 1475 return EvalAddr(SubExpr); 1476 else if (T->isArrayType()) 1477 return EvalVal(SubExpr); 1478 else 1479 return 0; 1480 } 1481 1482 // C++ casts. For dynamic casts, static casts, and const casts, we 1483 // are always converting from a pointer-to-pointer, so we just blow 1484 // through the cast. In the case the dynamic cast doesn't fail (and 1485 // return NULL), we take the conservative route and report cases 1486 // where we return the address of a stack variable. For Reinterpre 1487 // FIXME: The comment about is wrong; we're not always converting 1488 // from pointer to pointer. I'm guessing that this code should also 1489 // handle references to objects. 1490 case Stmt::CXXStaticCastExprClass: 1491 case Stmt::CXXDynamicCastExprClass: 1492 case Stmt::CXXConstCastExprClass: 1493 case Stmt::CXXReinterpretCastExprClass: { 1494 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 1495 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 1496 return EvalAddr(S); 1497 else 1498 return NULL; 1499 } 1500 1501 // Everything else: we simply don't reason about them. 1502 default: 1503 return NULL; 1504 } 1505} 1506 1507 1508/// EvalVal - This function is complements EvalAddr in the mutual recursion. 1509/// See the comments for EvalAddr for more details. 1510static DeclRefExpr* EvalVal(Expr *E) { 1511 1512 // We should only be called for evaluating non-pointer expressions, or 1513 // expressions with a pointer type that are not used as references but instead 1514 // are l-values (e.g., DeclRefExpr with a pointer type). 1515 1516 // Our "symbolic interpreter" is just a dispatch off the currently 1517 // viewed AST node. We then recursively traverse the AST by calling 1518 // EvalAddr and EvalVal appropriately. 1519 switch (E->getStmtClass()) { 1520 case Stmt::DeclRefExprClass: { 1521 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking 1522 // at code that refers to a variable's name. We check if it has local 1523 // storage within the function, and if so, return the expression. 1524 DeclRefExpr *DR = cast<DeclRefExpr>(E); 1525 1526 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 1527 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; 1528 1529 return NULL; 1530 } 1531 1532 case Stmt::ParenExprClass: 1533 // Ignore parentheses. 1534 return EvalVal(cast<ParenExpr>(E)->getSubExpr()); 1535 1536 case Stmt::UnaryOperatorClass: { 1537 // The only unary operator that make sense to handle here 1538 // is Deref. All others don't resolve to a "name." This includes 1539 // handling all sorts of rvalues passed to a unary operator. 1540 UnaryOperator *U = cast<UnaryOperator>(E); 1541 1542 if (U->getOpcode() == UnaryOperator::Deref) 1543 return EvalAddr(U->getSubExpr()); 1544 1545 return NULL; 1546 } 1547 1548 case Stmt::ArraySubscriptExprClass: { 1549 // Array subscripts are potential references to data on the stack. We 1550 // retrieve the DeclRefExpr* for the array variable if it indeed 1551 // has local storage. 1552 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); 1553 } 1554 1555 case Stmt::ConditionalOperatorClass: { 1556 // For conditional operators we need to see if either the LHS or RHS are 1557 // non-NULL DeclRefExpr's. If one is non-NULL, we return it. 1558 ConditionalOperator *C = cast<ConditionalOperator>(E); 1559 1560 // Handle the GNU extension for missing LHS. 1561 if (Expr *lhsExpr = C->getLHS()) 1562 if (DeclRefExpr *LHS = EvalVal(lhsExpr)) 1563 return LHS; 1564 1565 return EvalVal(C->getRHS()); 1566 } 1567 1568 // Accesses to members are potential references to data on the stack. 1569 case Stmt::MemberExprClass: { 1570 MemberExpr *M = cast<MemberExpr>(E); 1571 1572 // Check for indirect access. We only want direct field accesses. 1573 if (!M->isArrow()) 1574 return EvalVal(M->getBase()); 1575 else 1576 return NULL; 1577 } 1578 1579 // Everything else: we simply don't reason about them. 1580 default: 1581 return NULL; 1582 } 1583} 1584 1585//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 1586 1587/// Check for comparisons of floating point operands using != and ==. 1588/// Issue a warning if these are no self-comparisons, as they are not likely 1589/// to do what the programmer intended. 1590void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { 1591 bool EmitWarning = true; 1592 1593 Expr* LeftExprSansParen = lex->IgnoreParens(); 1594 Expr* RightExprSansParen = rex->IgnoreParens(); 1595 1596 // Special case: check for x == x (which is OK). 1597 // Do not emit warnings for such cases. 1598 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 1599 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 1600 if (DRL->getDecl() == DRR->getDecl()) 1601 EmitWarning = false; 1602 1603 1604 // Special case: check for comparisons against literals that can be exactly 1605 // represented by APFloat. In such cases, do not emit a warning. This 1606 // is a heuristic: often comparison against such literals are used to 1607 // detect if a value in a variable has not changed. This clearly can 1608 // lead to false negatives. 1609 if (EmitWarning) { 1610 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 1611 if (FLL->isExact()) 1612 EmitWarning = false; 1613 } else 1614 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 1615 if (FLR->isExact()) 1616 EmitWarning = false; 1617 } 1618 } 1619 1620 // Check for comparisons with builtin types. 1621 if (EmitWarning) 1622 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 1623 if (CL->isBuiltinCall(Context)) 1624 EmitWarning = false; 1625 1626 if (EmitWarning) 1627 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 1628 if (CR->isBuiltinCall(Context)) 1629 EmitWarning = false; 1630 1631 // Emit the diagnostic. 1632 if (EmitWarning) 1633 Diag(loc, diag::warn_floatingpoint_eq) 1634 << lex->getSourceRange() << rex->getSourceRange(); 1635} 1636 1637//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 1638//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 1639 1640namespace { 1641 1642/// Structure recording the 'active' range of an integer-valued 1643/// expression. 1644struct IntRange { 1645 /// The number of bits active in the int. 1646 unsigned Width; 1647 1648 /// True if the int is known not to have negative values. 1649 bool NonNegative; 1650 1651 IntRange() {} 1652 IntRange(unsigned Width, bool NonNegative) 1653 : Width(Width), NonNegative(NonNegative) 1654 {} 1655 1656 // Returns the range of the bool type. 1657 static IntRange forBoolType() { 1658 return IntRange(1, true); 1659 } 1660 1661 // Returns the range of an integral type. 1662 static IntRange forType(ASTContext &C, QualType T) { 1663 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr()); 1664 } 1665 1666 // Returns the range of an integeral type based on its canonical 1667 // representation. 1668 static IntRange forCanonicalType(ASTContext &C, const Type *T) { 1669 assert(T->isCanonicalUnqualified()); 1670 1671 if (const VectorType *VT = dyn_cast<VectorType>(T)) 1672 T = VT->getElementType().getTypePtr(); 1673 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 1674 T = CT->getElementType().getTypePtr(); 1675 if (const EnumType *ET = dyn_cast<EnumType>(T)) 1676 T = ET->getDecl()->getIntegerType().getTypePtr(); 1677 1678 const BuiltinType *BT = cast<BuiltinType>(T); 1679 assert(BT->isInteger()); 1680 1681 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 1682 } 1683 1684 // Returns the supremum of two ranges: i.e. their conservative merge. 1685 static IntRange join(IntRange L, IntRange R) { 1686 return IntRange(std::max(L.Width, R.Width), 1687 L.NonNegative && R.NonNegative); 1688 } 1689 1690 // Returns the infinum of two ranges: i.e. their aggressive merge. 1691 static IntRange meet(IntRange L, IntRange R) { 1692 return IntRange(std::min(L.Width, R.Width), 1693 L.NonNegative || R.NonNegative); 1694 } 1695}; 1696 1697IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 1698 if (value.isSigned() && value.isNegative()) 1699 return IntRange(value.getMinSignedBits(), false); 1700 1701 if (value.getBitWidth() > MaxWidth) 1702 value.trunc(MaxWidth); 1703 1704 // isNonNegative() just checks the sign bit without considering 1705 // signedness. 1706 return IntRange(value.getActiveBits(), true); 1707} 1708 1709IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 1710 unsigned MaxWidth) { 1711 if (result.isInt()) 1712 return GetValueRange(C, result.getInt(), MaxWidth); 1713 1714 if (result.isVector()) { 1715 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 1716 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 1717 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 1718 R = IntRange::join(R, El); 1719 } 1720 return R; 1721 } 1722 1723 if (result.isComplexInt()) { 1724 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 1725 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 1726 return IntRange::join(R, I); 1727 } 1728 1729 // This can happen with lossless casts to intptr_t of "based" lvalues. 1730 // Assume it might use arbitrary bits. 1731 // FIXME: The only reason we need to pass the type in here is to get 1732 // the sign right on this one case. It would be nice if APValue 1733 // preserved this. 1734 assert(result.isLValue()); 1735 return IntRange(MaxWidth, Ty->isUnsignedIntegerType()); 1736} 1737 1738/// Pseudo-evaluate the given integer expression, estimating the 1739/// range of values it might take. 1740/// 1741/// \param MaxWidth - the width to which the value will be truncated 1742IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 1743 E = E->IgnoreParens(); 1744 1745 // Try a full evaluation first. 1746 Expr::EvalResult result; 1747 if (E->Evaluate(result, C)) 1748 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 1749 1750 // I think we only want to look through implicit casts here; if the 1751 // user has an explicit widening cast, we should treat the value as 1752 // being of the new, wider type. 1753 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 1754 if (CE->getCastKind() == CastExpr::CK_NoOp) 1755 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 1756 1757 IntRange OutputTypeRange = IntRange::forType(C, CE->getType()); 1758 1759 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast); 1760 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown) 1761 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType(); 1762 1763 // Assume that non-integer casts can span the full range of the type. 1764 if (!isIntegerCast) 1765 return OutputTypeRange; 1766 1767 IntRange SubRange 1768 = GetExprRange(C, CE->getSubExpr(), 1769 std::min(MaxWidth, OutputTypeRange.Width)); 1770 1771 // Bail out if the subexpr's range is as wide as the cast type. 1772 if (SubRange.Width >= OutputTypeRange.Width) 1773 return OutputTypeRange; 1774 1775 // Otherwise, we take the smaller width, and we're non-negative if 1776 // either the output type or the subexpr is. 1777 return IntRange(SubRange.Width, 1778 SubRange.NonNegative || OutputTypeRange.NonNegative); 1779 } 1780 1781 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1782 // If we can fold the condition, just take that operand. 1783 bool CondResult; 1784 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 1785 return GetExprRange(C, CondResult ? CO->getTrueExpr() 1786 : CO->getFalseExpr(), 1787 MaxWidth); 1788 1789 // Otherwise, conservatively merge. 1790 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 1791 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 1792 return IntRange::join(L, R); 1793 } 1794 1795 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 1796 switch (BO->getOpcode()) { 1797 1798 // Boolean-valued operations are single-bit and positive. 1799 case BinaryOperator::LAnd: 1800 case BinaryOperator::LOr: 1801 case BinaryOperator::LT: 1802 case BinaryOperator::GT: 1803 case BinaryOperator::LE: 1804 case BinaryOperator::GE: 1805 case BinaryOperator::EQ: 1806 case BinaryOperator::NE: 1807 return IntRange::forBoolType(); 1808 1809 // The type of these compound assignments is the type of the LHS, 1810 // so the RHS is not necessarily an integer. 1811 case BinaryOperator::MulAssign: 1812 case BinaryOperator::DivAssign: 1813 case BinaryOperator::RemAssign: 1814 case BinaryOperator::AddAssign: 1815 case BinaryOperator::SubAssign: 1816 return IntRange::forType(C, E->getType()); 1817 1818 // Operations with opaque sources are black-listed. 1819 case BinaryOperator::PtrMemD: 1820 case BinaryOperator::PtrMemI: 1821 return IntRange::forType(C, E->getType()); 1822 1823 // Bitwise-and uses the *infinum* of the two source ranges. 1824 case BinaryOperator::And: 1825 case BinaryOperator::AndAssign: 1826 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 1827 GetExprRange(C, BO->getRHS(), MaxWidth)); 1828 1829 // Left shift gets black-listed based on a judgement call. 1830 case BinaryOperator::Shl: 1831 case BinaryOperator::ShlAssign: 1832 return IntRange::forType(C, E->getType()); 1833 1834 // Right shift by a constant can narrow its left argument. 1835 case BinaryOperator::Shr: 1836 case BinaryOperator::ShrAssign: { 1837 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 1838 1839 // If the shift amount is a positive constant, drop the width by 1840 // that much. 1841 llvm::APSInt shift; 1842 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 1843 shift.isNonNegative()) { 1844 unsigned zext = shift.getZExtValue(); 1845 if (zext >= L.Width) 1846 L.Width = (L.NonNegative ? 0 : 1); 1847 else 1848 L.Width -= zext; 1849 } 1850 1851 return L; 1852 } 1853 1854 // Comma acts as its right operand. 1855 case BinaryOperator::Comma: 1856 return GetExprRange(C, BO->getRHS(), MaxWidth); 1857 1858 // Black-list pointer subtractions. 1859 case BinaryOperator::Sub: 1860 if (BO->getLHS()->getType()->isPointerType()) 1861 return IntRange::forType(C, E->getType()); 1862 // fallthrough 1863 1864 default: 1865 break; 1866 } 1867 1868 // Treat every other operator as if it were closed on the 1869 // narrowest type that encompasses both operands. 1870 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 1871 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 1872 return IntRange::join(L, R); 1873 } 1874 1875 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1876 switch (UO->getOpcode()) { 1877 // Boolean-valued operations are white-listed. 1878 case UnaryOperator::LNot: 1879 return IntRange::forBoolType(); 1880 1881 // Operations with opaque sources are black-listed. 1882 case UnaryOperator::Deref: 1883 case UnaryOperator::AddrOf: // should be impossible 1884 case UnaryOperator::OffsetOf: 1885 return IntRange::forType(C, E->getType()); 1886 1887 default: 1888 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 1889 } 1890 } 1891 1892 FieldDecl *BitField = E->getBitField(); 1893 if (BitField) { 1894 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C); 1895 unsigned BitWidth = BitWidthAP.getZExtValue(); 1896 1897 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType()); 1898 } 1899 1900 return IntRange::forType(C, E->getType()); 1901} 1902 1903/// Checks whether the given value, which currently has the given 1904/// source semantics, has the same value when coerced through the 1905/// target semantics. 1906bool IsSameFloatAfterCast(const llvm::APFloat &value, 1907 const llvm::fltSemantics &Src, 1908 const llvm::fltSemantics &Tgt) { 1909 llvm::APFloat truncated = value; 1910 1911 bool ignored; 1912 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 1913 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 1914 1915 return truncated.bitwiseIsEqual(value); 1916} 1917 1918/// Checks whether the given value, which currently has the given 1919/// source semantics, has the same value when coerced through the 1920/// target semantics. 1921/// 1922/// The value might be a vector of floats (or a complex number). 1923bool IsSameFloatAfterCast(const APValue &value, 1924 const llvm::fltSemantics &Src, 1925 const llvm::fltSemantics &Tgt) { 1926 if (value.isFloat()) 1927 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 1928 1929 if (value.isVector()) { 1930 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 1931 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 1932 return false; 1933 return true; 1934 } 1935 1936 assert(value.isComplexFloat()); 1937 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 1938 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 1939} 1940 1941} // end anonymous namespace 1942 1943/// \brief Implements -Wsign-compare. 1944/// 1945/// \param lex the left-hand expression 1946/// \param rex the right-hand expression 1947/// \param OpLoc the location of the joining operator 1948/// \param Equality whether this is an "equality-like" join, which 1949/// suppresses the warning in some cases 1950void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc, 1951 const PartialDiagnostic &PD, bool Equality) { 1952 // Don't warn if we're in an unevaluated context. 1953 if (ExprEvalContexts.back().Context == Unevaluated) 1954 return; 1955 1956 // If either expression is value-dependent, don't warn. We'll get another 1957 // chance at instantiation time. 1958 if (lex->isValueDependent() || rex->isValueDependent()) 1959 return; 1960 1961 QualType lt = lex->getType(), rt = rex->getType(); 1962 1963 // Only warn if both operands are integral. 1964 if (!lt->isIntegerType() || !rt->isIntegerType()) 1965 return; 1966 1967 // In C, the width of a bitfield determines its type, and the 1968 // declared type only contributes the signedness. This duplicates 1969 // the work that will later be done by UsualUnaryConversions. 1970 // Eventually, this check will be reorganized in a way that avoids 1971 // this duplication. 1972 if (!getLangOptions().CPlusPlus) { 1973 QualType tmp; 1974 tmp = Context.isPromotableBitField(lex); 1975 if (!tmp.isNull()) lt = tmp; 1976 tmp = Context.isPromotableBitField(rex); 1977 if (!tmp.isNull()) rt = tmp; 1978 } 1979 1980 // The rule is that the signed operand becomes unsigned, so isolate the 1981 // signed operand. 1982 Expr *signedOperand = lex, *unsignedOperand = rex; 1983 QualType signedType = lt, unsignedType = rt; 1984 if (lt->isSignedIntegerType()) { 1985 if (rt->isSignedIntegerType()) return; 1986 } else { 1987 if (!rt->isSignedIntegerType()) return; 1988 std::swap(signedOperand, unsignedOperand); 1989 std::swap(signedType, unsignedType); 1990 } 1991 1992 unsigned unsignedWidth = Context.getIntWidth(unsignedType); 1993 unsigned signedWidth = Context.getIntWidth(signedType); 1994 1995 // If the unsigned type is strictly smaller than the signed type, 1996 // then (1) the result type will be signed and (2) the unsigned 1997 // value will fit fully within the signed type, and thus the result 1998 // of the comparison will be exact. 1999 if (signedWidth > unsignedWidth) 2000 return; 2001 2002 // Otherwise, calculate the effective ranges. 2003 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth); 2004 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth); 2005 2006 // We should never be unable to prove that the unsigned operand is 2007 // non-negative. 2008 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 2009 2010 // If the signed operand is non-negative, then the signed->unsigned 2011 // conversion won't change it. 2012 if (signedRange.NonNegative) 2013 return; 2014 2015 // For (in)equality comparisons, if the unsigned operand is a 2016 // constant which cannot collide with a overflowed signed operand, 2017 // then reinterpreting the signed operand as unsigned will not 2018 // change the result of the comparison. 2019 if (Equality && unsignedRange.Width < unsignedWidth) 2020 return; 2021 2022 Diag(OpLoc, PD) 2023 << lt << rt << lex->getSourceRange() << rex->getSourceRange(); 2024} 2025 2026/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 2027static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) { 2028 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange(); 2029} 2030 2031/// Implements -Wconversion. 2032void Sema::CheckImplicitConversion(Expr *E, QualType T) { 2033 // Don't diagnose in unevaluated contexts. 2034 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 2035 return; 2036 2037 // Don't diagnose for value-dependent expressions. 2038 if (E->isValueDependent()) 2039 return; 2040 2041 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr(); 2042 const Type *Target = Context.getCanonicalType(T).getTypePtr(); 2043 2044 // Never diagnose implicit casts to bool. 2045 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 2046 return; 2047 2048 // Strip vector types. 2049 if (isa<VectorType>(Source)) { 2050 if (!isa<VectorType>(Target)) 2051 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar); 2052 2053 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 2054 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 2055 } 2056 2057 // Strip complex types. 2058 if (isa<ComplexType>(Source)) { 2059 if (!isa<ComplexType>(Target)) 2060 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar); 2061 2062 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 2063 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 2064 } 2065 2066 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 2067 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 2068 2069 // If the source is floating point... 2070 if (SourceBT && SourceBT->isFloatingPoint()) { 2071 // ...and the target is floating point... 2072 if (TargetBT && TargetBT->isFloatingPoint()) { 2073 // ...then warn if we're dropping FP rank. 2074 2075 // Builtin FP kinds are ordered by increasing FP rank. 2076 if (SourceBT->getKind() > TargetBT->getKind()) { 2077 // Don't warn about float constants that are precisely 2078 // representable in the target type. 2079 Expr::EvalResult result; 2080 if (E->Evaluate(result, Context)) { 2081 // Value might be a float, a float vector, or a float complex. 2082 if (IsSameFloatAfterCast(result.Val, 2083 Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 2084 Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 2085 return; 2086 } 2087 2088 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision); 2089 } 2090 return; 2091 } 2092 2093 // If the target is integral, always warn. 2094 if ((TargetBT && TargetBT->isInteger())) 2095 // TODO: don't warn for integer values? 2096 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer); 2097 2098 return; 2099 } 2100 2101 if (!Source->isIntegerType() || !Target->isIntegerType()) 2102 return; 2103 2104 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType())); 2105 IntRange TargetRange = IntRange::forCanonicalType(Context, Target); 2106 2107 // FIXME: also signed<->unsigned? 2108 2109 if (SourceRange.Width > TargetRange.Width) { 2110 // People want to build with -Wshorten-64-to-32 and not -Wconversion 2111 // and by god we'll let them. 2112 if (SourceRange.Width == 64 && TargetRange.Width == 32) 2113 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32); 2114 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision); 2115 } 2116 2117 return; 2118} 2119 2120 2121 2122namespace { 2123class UnreachableCodeHandler : public reachable_code::Callback { 2124 Sema &S; 2125public: 2126 UnreachableCodeHandler(Sema *s) : S(*s) {} 2127 2128 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) { 2129 S.Diag(L, diag::warn_unreachable) << R1 << R2; 2130 } 2131}; 2132} 2133 2134/// CheckUnreachable - Check for unreachable code. 2135void Sema::CheckUnreachable(AnalysisContext &AC) { 2136 // We avoid checking when there are errors, as the CFG won't faithfully match 2137 // the user's code. 2138 if (getDiagnostics().hasErrorOccurred() || 2139 Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored) 2140 return; 2141 2142 UnreachableCodeHandler UC(this); 2143 reachable_code::FindUnreachableCode(AC, UC); 2144} 2145 2146/// CheckFallThrough - Check that we don't fall off the end of a 2147/// Statement that should return a value. 2148/// 2149/// \returns AlwaysFallThrough iff we always fall off the end of the statement, 2150/// MaybeFallThrough iff we might or might not fall off the end, 2151/// NeverFallThroughOrReturn iff we never fall off the end of the statement or 2152/// return. We assume NeverFallThrough iff we never fall off the end of the 2153/// statement but we may return. We assume that functions not marked noreturn 2154/// will return. 2155Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) { 2156 CFG *cfg = AC.getCFG(); 2157 if (cfg == 0) 2158 // FIXME: This should be NeverFallThrough 2159 return NeverFallThroughOrReturn; 2160 2161 // The CFG leaves in dead things, and we don't want the dead code paths to 2162 // confuse us, so we mark all live things first. 2163 std::queue<CFGBlock*> workq; 2164 llvm::BitVector live(cfg->getNumBlockIDs()); 2165 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(), 2166 live); 2167 2168 bool AddEHEdges = AC.getAddEHEdges(); 2169 if (!AddEHEdges && count != cfg->getNumBlockIDs()) 2170 // When there are things remaining dead, and we didn't add EH edges 2171 // from CallExprs to the catch clauses, we have to go back and 2172 // mark them as live. 2173 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { 2174 CFGBlock &b = **I; 2175 if (!live[b.getBlockID()]) { 2176 if (b.pred_begin() == b.pred_end()) { 2177 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator())) 2178 // When not adding EH edges from calls, catch clauses 2179 // can otherwise seem dead. Avoid noting them as dead. 2180 count += reachable_code::ScanReachableFromBlock(b, live); 2181 continue; 2182 } 2183 } 2184 } 2185 2186 // Now we know what is live, we check the live precessors of the exit block 2187 // and look for fall through paths, being careful to ignore normal returns, 2188 // and exceptional paths. 2189 bool HasLiveReturn = false; 2190 bool HasFakeEdge = false; 2191 bool HasPlainEdge = false; 2192 bool HasAbnormalEdge = false; 2193 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(), 2194 E = cfg->getExit().pred_end(); 2195 I != E; 2196 ++I) { 2197 CFGBlock& B = **I; 2198 if (!live[B.getBlockID()]) 2199 continue; 2200 if (B.size() == 0) { 2201 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) { 2202 HasAbnormalEdge = true; 2203 continue; 2204 } 2205 2206 // A labeled empty statement, or the entry block... 2207 HasPlainEdge = true; 2208 continue; 2209 } 2210 Stmt *S = B[B.size()-1]; 2211 if (isa<ReturnStmt>(S)) { 2212 HasLiveReturn = true; 2213 continue; 2214 } 2215 if (isa<ObjCAtThrowStmt>(S)) { 2216 HasFakeEdge = true; 2217 continue; 2218 } 2219 if (isa<CXXThrowExpr>(S)) { 2220 HasFakeEdge = true; 2221 continue; 2222 } 2223 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) { 2224 if (AS->isMSAsm()) { 2225 HasFakeEdge = true; 2226 HasLiveReturn = true; 2227 continue; 2228 } 2229 } 2230 if (isa<CXXTryStmt>(S)) { 2231 HasAbnormalEdge = true; 2232 continue; 2233 } 2234 2235 bool NoReturnEdge = false; 2236 if (CallExpr *C = dyn_cast<CallExpr>(S)) { 2237 if (B.succ_begin()[0] != &cfg->getExit()) { 2238 HasAbnormalEdge = true; 2239 continue; 2240 } 2241 Expr *CEE = C->getCallee()->IgnoreParenCasts(); 2242 if (CEE->getType().getNoReturnAttr()) { 2243 NoReturnEdge = true; 2244 HasFakeEdge = true; 2245 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { 2246 ValueDecl *VD = DRE->getDecl(); 2247 if (VD->hasAttr<NoReturnAttr>()) { 2248 NoReturnEdge = true; 2249 HasFakeEdge = true; 2250 } 2251 } 2252 } 2253 // FIXME: Add noreturn message sends. 2254 if (NoReturnEdge == false) 2255 HasPlainEdge = true; 2256 } 2257 if (!HasPlainEdge) { 2258 if (HasLiveReturn) 2259 return NeverFallThrough; 2260 return NeverFallThroughOrReturn; 2261 } 2262 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) 2263 return MaybeFallThrough; 2264 // This says AlwaysFallThrough for calls to functions that are not marked 2265 // noreturn, that don't return. If people would like this warning to be more 2266 // accurate, such functions should be marked as noreturn. 2267 return AlwaysFallThrough; 2268} 2269 2270/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a 2271/// function that should return a value. Check that we don't fall off the end 2272/// of a noreturn function. We assume that functions and blocks not marked 2273/// noreturn will return. 2274void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body, 2275 AnalysisContext &AC) { 2276 // FIXME: Would be nice if we had a better way to control cascading errors, 2277 // but for now, avoid them. The problem is that when Parse sees: 2278 // int foo() { return a; } 2279 // The return is eaten and the Sema code sees just: 2280 // int foo() { } 2281 // which this code would then warn about. 2282 if (getDiagnostics().hasErrorOccurred()) 2283 return; 2284 2285 bool ReturnsVoid = false; 2286 bool HasNoReturn = false; 2287 2288 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2289 // For function templates, class templates and member function templates 2290 // we'll do the analysis at instantiation time. 2291 if (FD->isDependentContext()) 2292 return; 2293 2294 ReturnsVoid = FD->getResultType()->isVoidType(); 2295 HasNoReturn = FD->hasAttr<NoReturnAttr>() || 2296 FD->getType()->getAs<FunctionType>()->getNoReturnAttr(); 2297 2298 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2299 ReturnsVoid = MD->getResultType()->isVoidType(); 2300 HasNoReturn = MD->hasAttr<NoReturnAttr>(); 2301 } 2302 2303 // Short circuit for compilation speed. 2304 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) 2305 == Diagnostic::Ignored || ReturnsVoid) 2306 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) 2307 == Diagnostic::Ignored || !HasNoReturn) 2308 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 2309 == Diagnostic::Ignored || !ReturnsVoid)) 2310 return; 2311 // FIXME: Function try block 2312 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 2313 switch (CheckFallThrough(AC)) { 2314 case MaybeFallThrough: 2315 if (HasNoReturn) 2316 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 2317 else if (!ReturnsVoid) 2318 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function); 2319 break; 2320 case AlwaysFallThrough: 2321 if (HasNoReturn) 2322 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 2323 else if (!ReturnsVoid) 2324 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function); 2325 break; 2326 case NeverFallThroughOrReturn: 2327 if (ReturnsVoid && !HasNoReturn) 2328 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function); 2329 break; 2330 case NeverFallThrough: 2331 break; 2332 } 2333 } 2334} 2335 2336/// CheckFallThroughForBlock - Check that we don't fall off the end of a block 2337/// that should return a value. Check that we don't fall off the end of a 2338/// noreturn block. We assume that functions and blocks not marked noreturn 2339/// will return. 2340void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body, 2341 AnalysisContext &AC) { 2342 // FIXME: Would be nice if we had a better way to control cascading errors, 2343 // but for now, avoid them. The problem is that when Parse sees: 2344 // int foo() { return a; } 2345 // The return is eaten and the Sema code sees just: 2346 // int foo() { } 2347 // which this code would then warn about. 2348 if (getDiagnostics().hasErrorOccurred()) 2349 return; 2350 bool ReturnsVoid = false; 2351 bool HasNoReturn = false; 2352 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){ 2353 if (FT->getResultType()->isVoidType()) 2354 ReturnsVoid = true; 2355 if (FT->getNoReturnAttr()) 2356 HasNoReturn = true; 2357 } 2358 2359 // Short circuit for compilation speed. 2360 if (ReturnsVoid 2361 && !HasNoReturn 2362 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 2363 == Diagnostic::Ignored || !ReturnsVoid)) 2364 return; 2365 // FIXME: Funtion try block 2366 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 2367 switch (CheckFallThrough(AC)) { 2368 case MaybeFallThrough: 2369 if (HasNoReturn) 2370 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 2371 else if (!ReturnsVoid) 2372 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block); 2373 break; 2374 case AlwaysFallThrough: 2375 if (HasNoReturn) 2376 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 2377 else if (!ReturnsVoid) 2378 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block); 2379 break; 2380 case NeverFallThroughOrReturn: 2381 if (ReturnsVoid) 2382 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block); 2383 break; 2384 case NeverFallThrough: 2385 break; 2386 } 2387 } 2388} 2389 2390/// CheckParmsForFunctionDef - Check that the parameters of the given 2391/// function are appropriate for the definition of a function. This 2392/// takes care of any checks that cannot be performed on the 2393/// declaration itself, e.g., that the types of each of the function 2394/// parameters are complete. 2395bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 2396 bool HasInvalidParm = false; 2397 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2398 ParmVarDecl *Param = FD->getParamDecl(p); 2399 2400 // C99 6.7.5.3p4: the parameters in a parameter type list in a 2401 // function declarator that is part of a function definition of 2402 // that function shall not have incomplete type. 2403 // 2404 // This is also C++ [dcl.fct]p6. 2405 if (!Param->isInvalidDecl() && 2406 RequireCompleteType(Param->getLocation(), Param->getType(), 2407 diag::err_typecheck_decl_incomplete_type)) { 2408 Param->setInvalidDecl(); 2409 HasInvalidParm = true; 2410 } 2411 2412 // C99 6.9.1p5: If the declarator includes a parameter type list, the 2413 // declaration of each parameter shall include an identifier. 2414 if (Param->getIdentifier() == 0 && 2415 !Param->isImplicit() && 2416 !getLangOptions().CPlusPlus) 2417 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 2418 2419 // C99 6.7.5.3p12: 2420 // If the function declarator is not part of a definition of that 2421 // function, parameters may have incomplete type and may use the [*] 2422 // notation in their sequences of declarator specifiers to specify 2423 // variable length array types. 2424 QualType PType = Param->getOriginalType(); 2425 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 2426 if (AT->getSizeModifier() == ArrayType::Star) { 2427 // FIXME: This diagnosic should point the the '[*]' if source-location 2428 // information is added for it. 2429 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 2430 } 2431 } 2432 2433 if (getLangOptions().CPlusPlus) 2434 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) 2435 FinalizeVarWithDestructor(Param, RT); 2436 } 2437 2438 return HasInvalidParm; 2439} 2440