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