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