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