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