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