SemaChecking.cpp revision 6fcb3727e31280ba816dc86d024586b8c5933c13
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/Initialization.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/Initialization.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/Analysis/Analyses/FormatString.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/DeclCXX.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/Expr.h" 26#include "clang/AST/ExprCXX.h" 27#include "clang/AST/ExprObjC.h" 28#include "clang/AST/EvaluatedExprVisitor.h" 29#include "clang/AST/DeclObjC.h" 30#include "clang/AST/StmtCXX.h" 31#include "clang/AST/StmtObjC.h" 32#include "clang/Lex/Preprocessor.h" 33#include "llvm/ADT/BitVector.h" 34#include "llvm/ADT/SmallString.h" 35#include "llvm/ADT/STLExtras.h" 36#include "llvm/Support/raw_ostream.h" 37#include "clang/Basic/TargetBuiltins.h" 38#include "clang/Basic/TargetInfo.h" 39#include "clang/Basic/ConvertUTF.h" 40#include <limits> 41using namespace clang; 42using namespace sema; 43 44SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 45 unsigned ByteNo) const { 46 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 47 PP.getLangOpts(), PP.getTargetInfo()); 48} 49 50/// Checks that a call expression's argument count is the desired number. 51/// This is useful when doing custom type-checking. Returns true on error. 52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 53 unsigned argCount = call->getNumArgs(); 54 if (argCount == desiredArgCount) return false; 55 56 if (argCount < desiredArgCount) 57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 58 << 0 /*function call*/ << desiredArgCount << argCount 59 << call->getSourceRange(); 60 61 // Highlight all the excess arguments. 62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 63 call->getArg(argCount - 1)->getLocEnd()); 64 65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 66 << 0 /*function call*/ << desiredArgCount << argCount 67 << call->getArg(1)->getSourceRange(); 68} 69 70/// Check that the first argument to __builtin_annotation is an integer 71/// and the second argument is a non-wide string literal. 72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 73 if (checkArgCount(S, TheCall, 2)) 74 return true; 75 76 // First argument should be an integer. 77 Expr *ValArg = TheCall->getArg(0); 78 QualType Ty = ValArg->getType(); 79 if (!Ty->isIntegerType()) { 80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 81 << ValArg->getSourceRange(); 82 return true; 83 } 84 85 // Second argument should be a constant string. 86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 88 if (!Literal || !Literal->isAscii()) { 89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 90 << StrArg->getSourceRange(); 91 return true; 92 } 93 94 TheCall->setType(Ty); 95 return false; 96} 97 98ExprResult 99Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 100 ExprResult TheCallResult(Owned(TheCall)); 101 102 // Find out if any arguments are required to be integer constant expressions. 103 unsigned ICEArguments = 0; 104 ASTContext::GetBuiltinTypeError Error; 105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 106 if (Error != ASTContext::GE_None) 107 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 108 109 // If any arguments are required to be ICE's, check and diagnose. 110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 111 // Skip arguments not required to be ICE's. 112 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 113 114 llvm::APSInt Result; 115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 116 return true; 117 ICEArguments &= ~(1 << ArgNo); 118 } 119 120 switch (BuiltinID) { 121 case Builtin::BI__builtin___CFStringMakeConstantString: 122 assert(TheCall->getNumArgs() == 1 && 123 "Wrong # arguments to builtin CFStringMakeConstantString"); 124 if (CheckObjCString(TheCall->getArg(0))) 125 return ExprError(); 126 break; 127 case Builtin::BI__builtin_stdarg_start: 128 case Builtin::BI__builtin_va_start: 129 if (SemaBuiltinVAStart(TheCall)) 130 return ExprError(); 131 break; 132 case Builtin::BI__builtin_isgreater: 133 case Builtin::BI__builtin_isgreaterequal: 134 case Builtin::BI__builtin_isless: 135 case Builtin::BI__builtin_islessequal: 136 case Builtin::BI__builtin_islessgreater: 137 case Builtin::BI__builtin_isunordered: 138 if (SemaBuiltinUnorderedCompare(TheCall)) 139 return ExprError(); 140 break; 141 case Builtin::BI__builtin_fpclassify: 142 if (SemaBuiltinFPClassification(TheCall, 6)) 143 return ExprError(); 144 break; 145 case Builtin::BI__builtin_isfinite: 146 case Builtin::BI__builtin_isinf: 147 case Builtin::BI__builtin_isinf_sign: 148 case Builtin::BI__builtin_isnan: 149 case Builtin::BI__builtin_isnormal: 150 if (SemaBuiltinFPClassification(TheCall, 1)) 151 return ExprError(); 152 break; 153 case Builtin::BI__builtin_shufflevector: 154 return SemaBuiltinShuffleVector(TheCall); 155 // TheCall will be freed by the smart pointer here, but that's fine, since 156 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 157 case Builtin::BI__builtin_prefetch: 158 if (SemaBuiltinPrefetch(TheCall)) 159 return ExprError(); 160 break; 161 case Builtin::BI__builtin_object_size: 162 if (SemaBuiltinObjectSize(TheCall)) 163 return ExprError(); 164 break; 165 case Builtin::BI__builtin_longjmp: 166 if (SemaBuiltinLongjmp(TheCall)) 167 return ExprError(); 168 break; 169 170 case Builtin::BI__builtin_classify_type: 171 if (checkArgCount(*this, TheCall, 1)) return true; 172 TheCall->setType(Context.IntTy); 173 break; 174 case Builtin::BI__builtin_constant_p: 175 if (checkArgCount(*this, TheCall, 1)) return true; 176 TheCall->setType(Context.IntTy); 177 break; 178 case Builtin::BI__sync_fetch_and_add: 179 case Builtin::BI__sync_fetch_and_add_1: 180 case Builtin::BI__sync_fetch_and_add_2: 181 case Builtin::BI__sync_fetch_and_add_4: 182 case Builtin::BI__sync_fetch_and_add_8: 183 case Builtin::BI__sync_fetch_and_add_16: 184 case Builtin::BI__sync_fetch_and_sub: 185 case Builtin::BI__sync_fetch_and_sub_1: 186 case Builtin::BI__sync_fetch_and_sub_2: 187 case Builtin::BI__sync_fetch_and_sub_4: 188 case Builtin::BI__sync_fetch_and_sub_8: 189 case Builtin::BI__sync_fetch_and_sub_16: 190 case Builtin::BI__sync_fetch_and_or: 191 case Builtin::BI__sync_fetch_and_or_1: 192 case Builtin::BI__sync_fetch_and_or_2: 193 case Builtin::BI__sync_fetch_and_or_4: 194 case Builtin::BI__sync_fetch_and_or_8: 195 case Builtin::BI__sync_fetch_and_or_16: 196 case Builtin::BI__sync_fetch_and_and: 197 case Builtin::BI__sync_fetch_and_and_1: 198 case Builtin::BI__sync_fetch_and_and_2: 199 case Builtin::BI__sync_fetch_and_and_4: 200 case Builtin::BI__sync_fetch_and_and_8: 201 case Builtin::BI__sync_fetch_and_and_16: 202 case Builtin::BI__sync_fetch_and_xor: 203 case Builtin::BI__sync_fetch_and_xor_1: 204 case Builtin::BI__sync_fetch_and_xor_2: 205 case Builtin::BI__sync_fetch_and_xor_4: 206 case Builtin::BI__sync_fetch_and_xor_8: 207 case Builtin::BI__sync_fetch_and_xor_16: 208 case Builtin::BI__sync_add_and_fetch: 209 case Builtin::BI__sync_add_and_fetch_1: 210 case Builtin::BI__sync_add_and_fetch_2: 211 case Builtin::BI__sync_add_and_fetch_4: 212 case Builtin::BI__sync_add_and_fetch_8: 213 case Builtin::BI__sync_add_and_fetch_16: 214 case Builtin::BI__sync_sub_and_fetch: 215 case Builtin::BI__sync_sub_and_fetch_1: 216 case Builtin::BI__sync_sub_and_fetch_2: 217 case Builtin::BI__sync_sub_and_fetch_4: 218 case Builtin::BI__sync_sub_and_fetch_8: 219 case Builtin::BI__sync_sub_and_fetch_16: 220 case Builtin::BI__sync_and_and_fetch: 221 case Builtin::BI__sync_and_and_fetch_1: 222 case Builtin::BI__sync_and_and_fetch_2: 223 case Builtin::BI__sync_and_and_fetch_4: 224 case Builtin::BI__sync_and_and_fetch_8: 225 case Builtin::BI__sync_and_and_fetch_16: 226 case Builtin::BI__sync_or_and_fetch: 227 case Builtin::BI__sync_or_and_fetch_1: 228 case Builtin::BI__sync_or_and_fetch_2: 229 case Builtin::BI__sync_or_and_fetch_4: 230 case Builtin::BI__sync_or_and_fetch_8: 231 case Builtin::BI__sync_or_and_fetch_16: 232 case Builtin::BI__sync_xor_and_fetch: 233 case Builtin::BI__sync_xor_and_fetch_1: 234 case Builtin::BI__sync_xor_and_fetch_2: 235 case Builtin::BI__sync_xor_and_fetch_4: 236 case Builtin::BI__sync_xor_and_fetch_8: 237 case Builtin::BI__sync_xor_and_fetch_16: 238 case Builtin::BI__sync_val_compare_and_swap: 239 case Builtin::BI__sync_val_compare_and_swap_1: 240 case Builtin::BI__sync_val_compare_and_swap_2: 241 case Builtin::BI__sync_val_compare_and_swap_4: 242 case Builtin::BI__sync_val_compare_and_swap_8: 243 case Builtin::BI__sync_val_compare_and_swap_16: 244 case Builtin::BI__sync_bool_compare_and_swap: 245 case Builtin::BI__sync_bool_compare_and_swap_1: 246 case Builtin::BI__sync_bool_compare_and_swap_2: 247 case Builtin::BI__sync_bool_compare_and_swap_4: 248 case Builtin::BI__sync_bool_compare_and_swap_8: 249 case Builtin::BI__sync_bool_compare_and_swap_16: 250 case Builtin::BI__sync_lock_test_and_set: 251 case Builtin::BI__sync_lock_test_and_set_1: 252 case Builtin::BI__sync_lock_test_and_set_2: 253 case Builtin::BI__sync_lock_test_and_set_4: 254 case Builtin::BI__sync_lock_test_and_set_8: 255 case Builtin::BI__sync_lock_test_and_set_16: 256 case Builtin::BI__sync_lock_release: 257 case Builtin::BI__sync_lock_release_1: 258 case Builtin::BI__sync_lock_release_2: 259 case Builtin::BI__sync_lock_release_4: 260 case Builtin::BI__sync_lock_release_8: 261 case Builtin::BI__sync_lock_release_16: 262 case Builtin::BI__sync_swap: 263 case Builtin::BI__sync_swap_1: 264 case Builtin::BI__sync_swap_2: 265 case Builtin::BI__sync_swap_4: 266 case Builtin::BI__sync_swap_8: 267 case Builtin::BI__sync_swap_16: 268 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 269#define BUILTIN(ID, TYPE, ATTRS) 270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 271 case Builtin::BI##ID: \ 272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID); 273#include "clang/Basic/Builtins.def" 274 case Builtin::BI__builtin_annotation: 275 if (SemaBuiltinAnnotation(*this, TheCall)) 276 return ExprError(); 277 break; 278 } 279 280 // Since the target specific builtins for each arch overlap, only check those 281 // of the arch we are compiling for. 282 if (BuiltinID >= Builtin::FirstTSBuiltin) { 283 switch (Context.getTargetInfo().getTriple().getArch()) { 284 case llvm::Triple::arm: 285 case llvm::Triple::thumb: 286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 287 return ExprError(); 288 break; 289 default: 290 break; 291 } 292 } 293 294 return move(TheCallResult); 295} 296 297// Get the valid immediate range for the specified NEON type code. 298static unsigned RFT(unsigned t, bool shift = false) { 299 NeonTypeFlags Type(t); 300 int IsQuad = Type.isQuad(); 301 switch (Type.getEltType()) { 302 case NeonTypeFlags::Int8: 303 case NeonTypeFlags::Poly8: 304 return shift ? 7 : (8 << IsQuad) - 1; 305 case NeonTypeFlags::Int16: 306 case NeonTypeFlags::Poly16: 307 return shift ? 15 : (4 << IsQuad) - 1; 308 case NeonTypeFlags::Int32: 309 return shift ? 31 : (2 << IsQuad) - 1; 310 case NeonTypeFlags::Int64: 311 return shift ? 63 : (1 << IsQuad) - 1; 312 case NeonTypeFlags::Float16: 313 assert(!shift && "cannot shift float types!"); 314 return (4 << IsQuad) - 1; 315 case NeonTypeFlags::Float32: 316 assert(!shift && "cannot shift float types!"); 317 return (2 << IsQuad) - 1; 318 } 319 llvm_unreachable("Invalid NeonTypeFlag!"); 320} 321 322/// getNeonEltType - Return the QualType corresponding to the elements of 323/// the vector type specified by the NeonTypeFlags. This is used to check 324/// the pointer arguments for Neon load/store intrinsics. 325static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 326 switch (Flags.getEltType()) { 327 case NeonTypeFlags::Int8: 328 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 329 case NeonTypeFlags::Int16: 330 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 331 case NeonTypeFlags::Int32: 332 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 333 case NeonTypeFlags::Int64: 334 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 335 case NeonTypeFlags::Poly8: 336 return Context.SignedCharTy; 337 case NeonTypeFlags::Poly16: 338 return Context.ShortTy; 339 case NeonTypeFlags::Float16: 340 return Context.UnsignedShortTy; 341 case NeonTypeFlags::Float32: 342 return Context.FloatTy; 343 } 344 llvm_unreachable("Invalid NeonTypeFlag!"); 345} 346 347bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 348 llvm::APSInt Result; 349 350 unsigned mask = 0; 351 unsigned TV = 0; 352 int PtrArgNum = -1; 353 bool HasConstPtr = false; 354 switch (BuiltinID) { 355#define GET_NEON_OVERLOAD_CHECK 356#include "clang/Basic/arm_neon.inc" 357#undef GET_NEON_OVERLOAD_CHECK 358 } 359 360 // For NEON intrinsics which are overloaded on vector element type, validate 361 // the immediate which specifies which variant to emit. 362 unsigned ImmArg = TheCall->getNumArgs()-1; 363 if (mask) { 364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 365 return true; 366 367 TV = Result.getLimitedValue(64); 368 if ((TV > 63) || (mask & (1 << TV)) == 0) 369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 370 << TheCall->getArg(ImmArg)->getSourceRange(); 371 } 372 373 if (PtrArgNum >= 0) { 374 // Check that pointer arguments have the specified type. 375 Expr *Arg = TheCall->getArg(PtrArgNum); 376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 377 Arg = ICE->getSubExpr(); 378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 379 QualType RHSTy = RHS.get()->getType(); 380 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 381 if (HasConstPtr) 382 EltTy = EltTy.withConst(); 383 QualType LHSTy = Context.getPointerType(EltTy); 384 AssignConvertType ConvTy; 385 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 386 if (RHS.isInvalid()) 387 return true; 388 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 389 RHS.get(), AA_Assigning)) 390 return true; 391 } 392 393 // For NEON intrinsics which take an immediate value as part of the 394 // instruction, range check them here. 395 unsigned i = 0, l = 0, u = 0; 396 switch (BuiltinID) { 397 default: return false; 398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 400 case ARM::BI__builtin_arm_vcvtr_f: 401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 402#define GET_NEON_IMMEDIATE_CHECK 403#include "clang/Basic/arm_neon.inc" 404#undef GET_NEON_IMMEDIATE_CHECK 405 }; 406 407 // Check that the immediate argument is actually a constant. 408 if (SemaBuiltinConstantArg(TheCall, i, Result)) 409 return true; 410 411 // Range check against the upper/lower values for this isntruction. 412 unsigned Val = Result.getZExtValue(); 413 if (Val < l || Val > (u + l)) 414 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 415 << l << u+l << TheCall->getArg(i)->getSourceRange(); 416 417 // FIXME: VFP Intrinsics should error if VFP not present. 418 return false; 419} 420 421/// CheckFunctionCall - Check a direct function call for various correctness 422/// and safety properties not strictly enforced by the C type system. 423bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 424 // Get the IdentifierInfo* for the called function. 425 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 426 427 // None of the checks below are needed for functions that don't have 428 // simple names (e.g., C++ conversion functions). 429 if (!FnInfo) 430 return false; 431 432 // FIXME: This mechanism should be abstracted to be less fragile and 433 // more efficient. For example, just map function ids to custom 434 // handlers. 435 436 // Printf and scanf checking. 437 for (specific_attr_iterator<FormatAttr> 438 i = FDecl->specific_attr_begin<FormatAttr>(), 439 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 440 CheckFormatArguments(*i, TheCall); 441 } 442 443 for (specific_attr_iterator<NonNullAttr> 444 i = FDecl->specific_attr_begin<NonNullAttr>(), 445 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 446 CheckNonNullArguments(*i, TheCall->getArgs(), 447 TheCall->getCallee()->getLocStart()); 448 } 449 450 unsigned CMId = FDecl->getMemoryFunctionKind(); 451 if (CMId == 0) 452 return false; 453 454 // Handle memory setting and copying functions. 455 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 456 CheckStrlcpycatArguments(TheCall, FnInfo); 457 else if (CMId == Builtin::BIstrncat) 458 CheckStrncatArguments(TheCall, FnInfo); 459 else 460 CheckMemaccessArguments(TheCall, CMId, FnInfo); 461 462 return false; 463} 464 465bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 466 Expr **Args, unsigned NumArgs) { 467 for (specific_attr_iterator<FormatAttr> 468 i = Method->specific_attr_begin<FormatAttr>(), 469 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) { 470 471 CheckFormatArguments(*i, Args, NumArgs, false, lbrac, 472 Method->getSourceRange()); 473 } 474 475 // diagnose nonnull arguments. 476 for (specific_attr_iterator<NonNullAttr> 477 i = Method->specific_attr_begin<NonNullAttr>(), 478 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) { 479 CheckNonNullArguments(*i, Args, lbrac); 480 } 481 482 return false; 483} 484 485bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 486 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 487 if (!V) 488 return false; 489 490 QualType Ty = V->getType(); 491 if (!Ty->isBlockPointerType()) 492 return false; 493 494 // format string checking. 495 for (specific_attr_iterator<FormatAttr> 496 i = NDecl->specific_attr_begin<FormatAttr>(), 497 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 498 CheckFormatArguments(*i, TheCall); 499 } 500 501 return false; 502} 503 504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 505 AtomicExpr::AtomicOp Op) { 506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 508 509 // All these operations take one of the following forms: 510 enum { 511 // C __c11_atomic_init(A *, C) 512 Init, 513 // C __c11_atomic_load(A *, int) 514 Load, 515 // void __atomic_load(A *, CP, int) 516 Copy, 517 // C __c11_atomic_add(A *, M, int) 518 Arithmetic, 519 // C __atomic_exchange_n(A *, CP, int) 520 Xchg, 521 // void __atomic_exchange(A *, C *, CP, int) 522 GNUXchg, 523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 524 C11CmpXchg, 525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 526 GNUCmpXchg 527 } Form = Init; 528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 530 // where: 531 // C is an appropriate type, 532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 535 // the int parameters are for orderings. 536 537 assert(AtomicExpr::AO__c11_atomic_init == 0 && 538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 539 && "need to update code for modified C11 atomics"); 540 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 541 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 542 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 543 Op == AtomicExpr::AO__atomic_store_n || 544 Op == AtomicExpr::AO__atomic_exchange_n || 545 Op == AtomicExpr::AO__atomic_compare_exchange_n; 546 bool IsAddSub = false; 547 548 switch (Op) { 549 case AtomicExpr::AO__c11_atomic_init: 550 Form = Init; 551 break; 552 553 case AtomicExpr::AO__c11_atomic_load: 554 case AtomicExpr::AO__atomic_load_n: 555 Form = Load; 556 break; 557 558 case AtomicExpr::AO__c11_atomic_store: 559 case AtomicExpr::AO__atomic_load: 560 case AtomicExpr::AO__atomic_store: 561 case AtomicExpr::AO__atomic_store_n: 562 Form = Copy; 563 break; 564 565 case AtomicExpr::AO__c11_atomic_fetch_add: 566 case AtomicExpr::AO__c11_atomic_fetch_sub: 567 case AtomicExpr::AO__atomic_fetch_add: 568 case AtomicExpr::AO__atomic_fetch_sub: 569 case AtomicExpr::AO__atomic_add_fetch: 570 case AtomicExpr::AO__atomic_sub_fetch: 571 IsAddSub = true; 572 // Fall through. 573 case AtomicExpr::AO__c11_atomic_fetch_and: 574 case AtomicExpr::AO__c11_atomic_fetch_or: 575 case AtomicExpr::AO__c11_atomic_fetch_xor: 576 case AtomicExpr::AO__atomic_fetch_and: 577 case AtomicExpr::AO__atomic_fetch_or: 578 case AtomicExpr::AO__atomic_fetch_xor: 579 case AtomicExpr::AO__atomic_fetch_nand: 580 case AtomicExpr::AO__atomic_and_fetch: 581 case AtomicExpr::AO__atomic_or_fetch: 582 case AtomicExpr::AO__atomic_xor_fetch: 583 case AtomicExpr::AO__atomic_nand_fetch: 584 Form = Arithmetic; 585 break; 586 587 case AtomicExpr::AO__c11_atomic_exchange: 588 case AtomicExpr::AO__atomic_exchange_n: 589 Form = Xchg; 590 break; 591 592 case AtomicExpr::AO__atomic_exchange: 593 Form = GNUXchg; 594 break; 595 596 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 597 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 598 Form = C11CmpXchg; 599 break; 600 601 case AtomicExpr::AO__atomic_compare_exchange: 602 case AtomicExpr::AO__atomic_compare_exchange_n: 603 Form = GNUCmpXchg; 604 break; 605 } 606 607 // Check we have the right number of arguments. 608 if (TheCall->getNumArgs() < NumArgs[Form]) { 609 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 610 << 0 << NumArgs[Form] << TheCall->getNumArgs() 611 << TheCall->getCallee()->getSourceRange(); 612 return ExprError(); 613 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 614 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 615 diag::err_typecheck_call_too_many_args) 616 << 0 << NumArgs[Form] << TheCall->getNumArgs() 617 << TheCall->getCallee()->getSourceRange(); 618 return ExprError(); 619 } 620 621 // Inspect the first argument of the atomic operation. 622 Expr *Ptr = TheCall->getArg(0); 623 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 624 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 625 if (!pointerType) { 626 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 627 << Ptr->getType() << Ptr->getSourceRange(); 628 return ExprError(); 629 } 630 631 // For a __c11 builtin, this should be a pointer to an _Atomic type. 632 QualType AtomTy = pointerType->getPointeeType(); // 'A' 633 QualType ValType = AtomTy; // 'C' 634 if (IsC11) { 635 if (!AtomTy->isAtomicType()) { 636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 637 << Ptr->getType() << Ptr->getSourceRange(); 638 return ExprError(); 639 } 640 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 641 } 642 643 // For an arithmetic operation, the implied arithmetic must be well-formed. 644 if (Form == Arithmetic) { 645 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 646 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 648 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 649 return ExprError(); 650 } 651 if (!IsAddSub && !ValType->isIntegerType()) { 652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 653 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 654 return ExprError(); 655 } 656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 657 // For __atomic_*_n operations, the value type must be a scalar integral or 658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 659 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 660 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 661 return ExprError(); 662 } 663 664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) { 665 // For GNU atomics, require a trivially-copyable type. This is not part of 666 // the GNU atomics specification, but we enforce it for sanity. 667 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 668 << Ptr->getType() << Ptr->getSourceRange(); 669 return ExprError(); 670 } 671 672 // FIXME: For any builtin other than a load, the ValType must not be 673 // const-qualified. 674 675 switch (ValType.getObjCLifetime()) { 676 case Qualifiers::OCL_None: 677 case Qualifiers::OCL_ExplicitNone: 678 // okay 679 break; 680 681 case Qualifiers::OCL_Weak: 682 case Qualifiers::OCL_Strong: 683 case Qualifiers::OCL_Autoreleasing: 684 // FIXME: Can this happen? By this point, ValType should be known 685 // to be trivially copyable. 686 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 687 << ValType << Ptr->getSourceRange(); 688 return ExprError(); 689 } 690 691 QualType ResultType = ValType; 692 if (Form == Copy || Form == GNUXchg || Form == Init) 693 ResultType = Context.VoidTy; 694 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 695 ResultType = Context.BoolTy; 696 697 // The type of a parameter passed 'by value'. In the GNU atomics, such 698 // arguments are actually passed as pointers. 699 QualType ByValType = ValType; // 'CP' 700 if (!IsC11 && !IsN) 701 ByValType = Ptr->getType(); 702 703 // The first argument --- the pointer --- has a fixed type; we 704 // deduce the types of the rest of the arguments accordingly. Walk 705 // the remaining arguments, converting them to the deduced value type. 706 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 707 QualType Ty; 708 if (i < NumVals[Form] + 1) { 709 switch (i) { 710 case 1: 711 // The second argument is the non-atomic operand. For arithmetic, this 712 // is always passed by value, and for a compare_exchange it is always 713 // passed by address. For the rest, GNU uses by-address and C11 uses 714 // by-value. 715 assert(Form != Load); 716 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 717 Ty = ValType; 718 else if (Form == Copy || Form == Xchg) 719 Ty = ByValType; 720 else if (Form == Arithmetic) 721 Ty = Context.getPointerDiffType(); 722 else 723 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 724 break; 725 case 2: 726 // The third argument to compare_exchange / GNU exchange is a 727 // (pointer to a) desired value. 728 Ty = ByValType; 729 break; 730 case 3: 731 // The fourth argument to GNU compare_exchange is a 'weak' flag. 732 Ty = Context.BoolTy; 733 break; 734 } 735 } else { 736 // The order(s) are always converted to int. 737 Ty = Context.IntTy; 738 } 739 740 InitializedEntity Entity = 741 InitializedEntity::InitializeParameter(Context, Ty, false); 742 ExprResult Arg = TheCall->getArg(i); 743 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 744 if (Arg.isInvalid()) 745 return true; 746 TheCall->setArg(i, Arg.get()); 747 } 748 749 // Permute the arguments into a 'consistent' order. 750 SmallVector<Expr*, 5> SubExprs; 751 SubExprs.push_back(Ptr); 752 switch (Form) { 753 case Init: 754 // Note, AtomicExpr::getVal1() has a special case for this atomic. 755 SubExprs.push_back(TheCall->getArg(1)); // Val1 756 break; 757 case Load: 758 SubExprs.push_back(TheCall->getArg(1)); // Order 759 break; 760 case Copy: 761 case Arithmetic: 762 case Xchg: 763 SubExprs.push_back(TheCall->getArg(2)); // Order 764 SubExprs.push_back(TheCall->getArg(1)); // Val1 765 break; 766 case GNUXchg: 767 // Note, AtomicExpr::getVal2() has a special case for this atomic. 768 SubExprs.push_back(TheCall->getArg(3)); // Order 769 SubExprs.push_back(TheCall->getArg(1)); // Val1 770 SubExprs.push_back(TheCall->getArg(2)); // Val2 771 break; 772 case C11CmpXchg: 773 SubExprs.push_back(TheCall->getArg(3)); // Order 774 SubExprs.push_back(TheCall->getArg(1)); // Val1 775 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 776 SubExprs.push_back(TheCall->getArg(2)); // Val2 777 break; 778 case GNUCmpXchg: 779 SubExprs.push_back(TheCall->getArg(4)); // Order 780 SubExprs.push_back(TheCall->getArg(1)); // Val1 781 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 782 SubExprs.push_back(TheCall->getArg(2)); // Val2 783 SubExprs.push_back(TheCall->getArg(3)); // Weak 784 break; 785 } 786 787 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 788 SubExprs.data(), SubExprs.size(), 789 ResultType, Op, 790 TheCall->getRParenLoc())); 791} 792 793 794/// checkBuiltinArgument - Given a call to a builtin function, perform 795/// normal type-checking on the given argument, updating the call in 796/// place. This is useful when a builtin function requires custom 797/// type-checking for some of its arguments but not necessarily all of 798/// them. 799/// 800/// Returns true on error. 801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 802 FunctionDecl *Fn = E->getDirectCallee(); 803 assert(Fn && "builtin call without direct callee!"); 804 805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 806 InitializedEntity Entity = 807 InitializedEntity::InitializeParameter(S.Context, Param); 808 809 ExprResult Arg = E->getArg(0); 810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 811 if (Arg.isInvalid()) 812 return true; 813 814 E->setArg(ArgIndex, Arg.take()); 815 return false; 816} 817 818/// SemaBuiltinAtomicOverloaded - We have a call to a function like 819/// __sync_fetch_and_add, which is an overloaded function based on the pointer 820/// type of its first argument. The main ActOnCallExpr routines have already 821/// promoted the types of arguments because all of these calls are prototyped as 822/// void(...). 823/// 824/// This function goes through and does final semantic checking for these 825/// builtins, 826ExprResult 827Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 828 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 831 832 // Ensure that we have at least one argument to do type inference from. 833 if (TheCall->getNumArgs() < 1) { 834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 835 << 0 << 1 << TheCall->getNumArgs() 836 << TheCall->getCallee()->getSourceRange(); 837 return ExprError(); 838 } 839 840 // Inspect the first argument of the atomic builtin. This should always be 841 // a pointer type, whose element is an integral scalar or pointer type. 842 // Because it is a pointer type, we don't have to worry about any implicit 843 // casts here. 844 // FIXME: We don't allow floating point scalars as input. 845 Expr *FirstArg = TheCall->getArg(0); 846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 847 if (FirstArgResult.isInvalid()) 848 return ExprError(); 849 FirstArg = FirstArgResult.take(); 850 TheCall->setArg(0, FirstArg); 851 852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 853 if (!pointerType) { 854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 855 << FirstArg->getType() << FirstArg->getSourceRange(); 856 return ExprError(); 857 } 858 859 QualType ValType = pointerType->getPointeeType(); 860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 861 !ValType->isBlockPointerType()) { 862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 863 << FirstArg->getType() << FirstArg->getSourceRange(); 864 return ExprError(); 865 } 866 867 switch (ValType.getObjCLifetime()) { 868 case Qualifiers::OCL_None: 869 case Qualifiers::OCL_ExplicitNone: 870 // okay 871 break; 872 873 case Qualifiers::OCL_Weak: 874 case Qualifiers::OCL_Strong: 875 case Qualifiers::OCL_Autoreleasing: 876 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 877 << ValType << FirstArg->getSourceRange(); 878 return ExprError(); 879 } 880 881 // Strip any qualifiers off ValType. 882 ValType = ValType.getUnqualifiedType(); 883 884 // The majority of builtins return a value, but a few have special return 885 // types, so allow them to override appropriately below. 886 QualType ResultType = ValType; 887 888 // We need to figure out which concrete builtin this maps onto. For example, 889 // __sync_fetch_and_add with a 2 byte object turns into 890 // __sync_fetch_and_add_2. 891#define BUILTIN_ROW(x) \ 892 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 893 Builtin::BI##x##_8, Builtin::BI##x##_16 } 894 895 static const unsigned BuiltinIndices[][5] = { 896 BUILTIN_ROW(__sync_fetch_and_add), 897 BUILTIN_ROW(__sync_fetch_and_sub), 898 BUILTIN_ROW(__sync_fetch_and_or), 899 BUILTIN_ROW(__sync_fetch_and_and), 900 BUILTIN_ROW(__sync_fetch_and_xor), 901 902 BUILTIN_ROW(__sync_add_and_fetch), 903 BUILTIN_ROW(__sync_sub_and_fetch), 904 BUILTIN_ROW(__sync_and_and_fetch), 905 BUILTIN_ROW(__sync_or_and_fetch), 906 BUILTIN_ROW(__sync_xor_and_fetch), 907 908 BUILTIN_ROW(__sync_val_compare_and_swap), 909 BUILTIN_ROW(__sync_bool_compare_and_swap), 910 BUILTIN_ROW(__sync_lock_test_and_set), 911 BUILTIN_ROW(__sync_lock_release), 912 BUILTIN_ROW(__sync_swap) 913 }; 914#undef BUILTIN_ROW 915 916 // Determine the index of the size. 917 unsigned SizeIndex; 918 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 919 case 1: SizeIndex = 0; break; 920 case 2: SizeIndex = 1; break; 921 case 4: SizeIndex = 2; break; 922 case 8: SizeIndex = 3; break; 923 case 16: SizeIndex = 4; break; 924 default: 925 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 926 << FirstArg->getType() << FirstArg->getSourceRange(); 927 return ExprError(); 928 } 929 930 // Each of these builtins has one pointer argument, followed by some number of 931 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 932 // that we ignore. Find out which row of BuiltinIndices to read from as well 933 // as the number of fixed args. 934 unsigned BuiltinID = FDecl->getBuiltinID(); 935 unsigned BuiltinIndex, NumFixed = 1; 936 switch (BuiltinID) { 937 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 938 case Builtin::BI__sync_fetch_and_add: 939 case Builtin::BI__sync_fetch_and_add_1: 940 case Builtin::BI__sync_fetch_and_add_2: 941 case Builtin::BI__sync_fetch_and_add_4: 942 case Builtin::BI__sync_fetch_and_add_8: 943 case Builtin::BI__sync_fetch_and_add_16: 944 BuiltinIndex = 0; 945 break; 946 947 case Builtin::BI__sync_fetch_and_sub: 948 case Builtin::BI__sync_fetch_and_sub_1: 949 case Builtin::BI__sync_fetch_and_sub_2: 950 case Builtin::BI__sync_fetch_and_sub_4: 951 case Builtin::BI__sync_fetch_and_sub_8: 952 case Builtin::BI__sync_fetch_and_sub_16: 953 BuiltinIndex = 1; 954 break; 955 956 case Builtin::BI__sync_fetch_and_or: 957 case Builtin::BI__sync_fetch_and_or_1: 958 case Builtin::BI__sync_fetch_and_or_2: 959 case Builtin::BI__sync_fetch_and_or_4: 960 case Builtin::BI__sync_fetch_and_or_8: 961 case Builtin::BI__sync_fetch_and_or_16: 962 BuiltinIndex = 2; 963 break; 964 965 case Builtin::BI__sync_fetch_and_and: 966 case Builtin::BI__sync_fetch_and_and_1: 967 case Builtin::BI__sync_fetch_and_and_2: 968 case Builtin::BI__sync_fetch_and_and_4: 969 case Builtin::BI__sync_fetch_and_and_8: 970 case Builtin::BI__sync_fetch_and_and_16: 971 BuiltinIndex = 3; 972 break; 973 974 case Builtin::BI__sync_fetch_and_xor: 975 case Builtin::BI__sync_fetch_and_xor_1: 976 case Builtin::BI__sync_fetch_and_xor_2: 977 case Builtin::BI__sync_fetch_and_xor_4: 978 case Builtin::BI__sync_fetch_and_xor_8: 979 case Builtin::BI__sync_fetch_and_xor_16: 980 BuiltinIndex = 4; 981 break; 982 983 case Builtin::BI__sync_add_and_fetch: 984 case Builtin::BI__sync_add_and_fetch_1: 985 case Builtin::BI__sync_add_and_fetch_2: 986 case Builtin::BI__sync_add_and_fetch_4: 987 case Builtin::BI__sync_add_and_fetch_8: 988 case Builtin::BI__sync_add_and_fetch_16: 989 BuiltinIndex = 5; 990 break; 991 992 case Builtin::BI__sync_sub_and_fetch: 993 case Builtin::BI__sync_sub_and_fetch_1: 994 case Builtin::BI__sync_sub_and_fetch_2: 995 case Builtin::BI__sync_sub_and_fetch_4: 996 case Builtin::BI__sync_sub_and_fetch_8: 997 case Builtin::BI__sync_sub_and_fetch_16: 998 BuiltinIndex = 6; 999 break; 1000 1001 case Builtin::BI__sync_and_and_fetch: 1002 case Builtin::BI__sync_and_and_fetch_1: 1003 case Builtin::BI__sync_and_and_fetch_2: 1004 case Builtin::BI__sync_and_and_fetch_4: 1005 case Builtin::BI__sync_and_and_fetch_8: 1006 case Builtin::BI__sync_and_and_fetch_16: 1007 BuiltinIndex = 7; 1008 break; 1009 1010 case Builtin::BI__sync_or_and_fetch: 1011 case Builtin::BI__sync_or_and_fetch_1: 1012 case Builtin::BI__sync_or_and_fetch_2: 1013 case Builtin::BI__sync_or_and_fetch_4: 1014 case Builtin::BI__sync_or_and_fetch_8: 1015 case Builtin::BI__sync_or_and_fetch_16: 1016 BuiltinIndex = 8; 1017 break; 1018 1019 case Builtin::BI__sync_xor_and_fetch: 1020 case Builtin::BI__sync_xor_and_fetch_1: 1021 case Builtin::BI__sync_xor_and_fetch_2: 1022 case Builtin::BI__sync_xor_and_fetch_4: 1023 case Builtin::BI__sync_xor_and_fetch_8: 1024 case Builtin::BI__sync_xor_and_fetch_16: 1025 BuiltinIndex = 9; 1026 break; 1027 1028 case Builtin::BI__sync_val_compare_and_swap: 1029 case Builtin::BI__sync_val_compare_and_swap_1: 1030 case Builtin::BI__sync_val_compare_and_swap_2: 1031 case Builtin::BI__sync_val_compare_and_swap_4: 1032 case Builtin::BI__sync_val_compare_and_swap_8: 1033 case Builtin::BI__sync_val_compare_and_swap_16: 1034 BuiltinIndex = 10; 1035 NumFixed = 2; 1036 break; 1037 1038 case Builtin::BI__sync_bool_compare_and_swap: 1039 case Builtin::BI__sync_bool_compare_and_swap_1: 1040 case Builtin::BI__sync_bool_compare_and_swap_2: 1041 case Builtin::BI__sync_bool_compare_and_swap_4: 1042 case Builtin::BI__sync_bool_compare_and_swap_8: 1043 case Builtin::BI__sync_bool_compare_and_swap_16: 1044 BuiltinIndex = 11; 1045 NumFixed = 2; 1046 ResultType = Context.BoolTy; 1047 break; 1048 1049 case Builtin::BI__sync_lock_test_and_set: 1050 case Builtin::BI__sync_lock_test_and_set_1: 1051 case Builtin::BI__sync_lock_test_and_set_2: 1052 case Builtin::BI__sync_lock_test_and_set_4: 1053 case Builtin::BI__sync_lock_test_and_set_8: 1054 case Builtin::BI__sync_lock_test_and_set_16: 1055 BuiltinIndex = 12; 1056 break; 1057 1058 case Builtin::BI__sync_lock_release: 1059 case Builtin::BI__sync_lock_release_1: 1060 case Builtin::BI__sync_lock_release_2: 1061 case Builtin::BI__sync_lock_release_4: 1062 case Builtin::BI__sync_lock_release_8: 1063 case Builtin::BI__sync_lock_release_16: 1064 BuiltinIndex = 13; 1065 NumFixed = 0; 1066 ResultType = Context.VoidTy; 1067 break; 1068 1069 case Builtin::BI__sync_swap: 1070 case Builtin::BI__sync_swap_1: 1071 case Builtin::BI__sync_swap_2: 1072 case Builtin::BI__sync_swap_4: 1073 case Builtin::BI__sync_swap_8: 1074 case Builtin::BI__sync_swap_16: 1075 BuiltinIndex = 14; 1076 break; 1077 } 1078 1079 // Now that we know how many fixed arguments we expect, first check that we 1080 // have at least that many. 1081 if (TheCall->getNumArgs() < 1+NumFixed) { 1082 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1083 << 0 << 1+NumFixed << TheCall->getNumArgs() 1084 << TheCall->getCallee()->getSourceRange(); 1085 return ExprError(); 1086 } 1087 1088 // Get the decl for the concrete builtin from this, we can tell what the 1089 // concrete integer type we should convert to is. 1090 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1091 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1092 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 1093 FunctionDecl *NewBuiltinDecl = 1094 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 1095 TUScope, false, DRE->getLocStart())); 1096 1097 // The first argument --- the pointer --- has a fixed type; we 1098 // deduce the types of the rest of the arguments accordingly. Walk 1099 // the remaining arguments, converting them to the deduced value type. 1100 for (unsigned i = 0; i != NumFixed; ++i) { 1101 ExprResult Arg = TheCall->getArg(i+1); 1102 1103 // GCC does an implicit conversion to the pointer or integer ValType. This 1104 // can fail in some cases (1i -> int**), check for this error case now. 1105 // Initialize the argument. 1106 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1107 ValType, /*consume*/ false); 1108 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1109 if (Arg.isInvalid()) 1110 return ExprError(); 1111 1112 // Okay, we have something that *can* be converted to the right type. Check 1113 // to see if there is a potentially weird extension going on here. This can 1114 // happen when you do an atomic operation on something like an char* and 1115 // pass in 42. The 42 gets converted to char. This is even more strange 1116 // for things like 45.123 -> char, etc. 1117 // FIXME: Do this check. 1118 TheCall->setArg(i+1, Arg.take()); 1119 } 1120 1121 ASTContext& Context = this->getASTContext(); 1122 1123 // Create a new DeclRefExpr to refer to the new decl. 1124 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1125 Context, 1126 DRE->getQualifierLoc(), 1127 SourceLocation(), 1128 NewBuiltinDecl, 1129 /*enclosing*/ false, 1130 DRE->getLocation(), 1131 NewBuiltinDecl->getType(), 1132 DRE->getValueKind()); 1133 1134 // Set the callee in the CallExpr. 1135 // FIXME: This leaks the original parens and implicit casts. 1136 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1137 if (PromotedCall.isInvalid()) 1138 return ExprError(); 1139 TheCall->setCallee(PromotedCall.take()); 1140 1141 // Change the result type of the call to match the original value type. This 1142 // is arbitrary, but the codegen for these builtins ins design to handle it 1143 // gracefully. 1144 TheCall->setType(ResultType); 1145 1146 return move(TheCallResult); 1147} 1148 1149/// CheckObjCString - Checks that the argument to the builtin 1150/// CFString constructor is correct 1151/// Note: It might also make sense to do the UTF-16 conversion here (would 1152/// simplify the backend). 1153bool Sema::CheckObjCString(Expr *Arg) { 1154 Arg = Arg->IgnoreParenCasts(); 1155 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1156 1157 if (!Literal || !Literal->isAscii()) { 1158 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1159 << Arg->getSourceRange(); 1160 return true; 1161 } 1162 1163 if (Literal->containsNonAsciiOrNull()) { 1164 StringRef String = Literal->getString(); 1165 unsigned NumBytes = String.size(); 1166 SmallVector<UTF16, 128> ToBuf(NumBytes); 1167 const UTF8 *FromPtr = (UTF8 *)String.data(); 1168 UTF16 *ToPtr = &ToBuf[0]; 1169 1170 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1171 &ToPtr, ToPtr + NumBytes, 1172 strictConversion); 1173 // Check for conversion failure. 1174 if (Result != conversionOK) 1175 Diag(Arg->getLocStart(), 1176 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1177 } 1178 return false; 1179} 1180 1181/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1182/// Emit an error and return true on failure, return false on success. 1183bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1184 Expr *Fn = TheCall->getCallee(); 1185 if (TheCall->getNumArgs() > 2) { 1186 Diag(TheCall->getArg(2)->getLocStart(), 1187 diag::err_typecheck_call_too_many_args) 1188 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1189 << Fn->getSourceRange() 1190 << SourceRange(TheCall->getArg(2)->getLocStart(), 1191 (*(TheCall->arg_end()-1))->getLocEnd()); 1192 return true; 1193 } 1194 1195 if (TheCall->getNumArgs() < 2) { 1196 return Diag(TheCall->getLocEnd(), 1197 diag::err_typecheck_call_too_few_args_at_least) 1198 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1199 } 1200 1201 // Type-check the first argument normally. 1202 if (checkBuiltinArgument(*this, TheCall, 0)) 1203 return true; 1204 1205 // Determine whether the current function is variadic or not. 1206 BlockScopeInfo *CurBlock = getCurBlock(); 1207 bool isVariadic; 1208 if (CurBlock) 1209 isVariadic = CurBlock->TheDecl->isVariadic(); 1210 else if (FunctionDecl *FD = getCurFunctionDecl()) 1211 isVariadic = FD->isVariadic(); 1212 else 1213 isVariadic = getCurMethodDecl()->isVariadic(); 1214 1215 if (!isVariadic) { 1216 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1217 return true; 1218 } 1219 1220 // Verify that the second argument to the builtin is the last argument of the 1221 // current function or method. 1222 bool SecondArgIsLastNamedArgument = false; 1223 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1224 1225 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1226 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1227 // FIXME: This isn't correct for methods (results in bogus warning). 1228 // Get the last formal in the current function. 1229 const ParmVarDecl *LastArg; 1230 if (CurBlock) 1231 LastArg = *(CurBlock->TheDecl->param_end()-1); 1232 else if (FunctionDecl *FD = getCurFunctionDecl()) 1233 LastArg = *(FD->param_end()-1); 1234 else 1235 LastArg = *(getCurMethodDecl()->param_end()-1); 1236 SecondArgIsLastNamedArgument = PV == LastArg; 1237 } 1238 } 1239 1240 if (!SecondArgIsLastNamedArgument) 1241 Diag(TheCall->getArg(1)->getLocStart(), 1242 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1243 return false; 1244} 1245 1246/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1247/// friends. This is declared to take (...), so we have to check everything. 1248bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1249 if (TheCall->getNumArgs() < 2) 1250 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1251 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1252 if (TheCall->getNumArgs() > 2) 1253 return Diag(TheCall->getArg(2)->getLocStart(), 1254 diag::err_typecheck_call_too_many_args) 1255 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1256 << SourceRange(TheCall->getArg(2)->getLocStart(), 1257 (*(TheCall->arg_end()-1))->getLocEnd()); 1258 1259 ExprResult OrigArg0 = TheCall->getArg(0); 1260 ExprResult OrigArg1 = TheCall->getArg(1); 1261 1262 // Do standard promotions between the two arguments, returning their common 1263 // type. 1264 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1265 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1266 return true; 1267 1268 // Make sure any conversions are pushed back into the call; this is 1269 // type safe since unordered compare builtins are declared as "_Bool 1270 // foo(...)". 1271 TheCall->setArg(0, OrigArg0.get()); 1272 TheCall->setArg(1, OrigArg1.get()); 1273 1274 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1275 return false; 1276 1277 // If the common type isn't a real floating type, then the arguments were 1278 // invalid for this operation. 1279 if (!Res->isRealFloatingType()) 1280 return Diag(OrigArg0.get()->getLocStart(), 1281 diag::err_typecheck_call_invalid_ordered_compare) 1282 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1283 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1284 1285 return false; 1286} 1287 1288/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1289/// __builtin_isnan and friends. This is declared to take (...), so we have 1290/// to check everything. We expect the last argument to be a floating point 1291/// value. 1292bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1293 if (TheCall->getNumArgs() < NumArgs) 1294 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1295 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1296 if (TheCall->getNumArgs() > NumArgs) 1297 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1298 diag::err_typecheck_call_too_many_args) 1299 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1300 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1301 (*(TheCall->arg_end()-1))->getLocEnd()); 1302 1303 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1304 1305 if (OrigArg->isTypeDependent()) 1306 return false; 1307 1308 // This operation requires a non-_Complex floating-point number. 1309 if (!OrigArg->getType()->isRealFloatingType()) 1310 return Diag(OrigArg->getLocStart(), 1311 diag::err_typecheck_call_invalid_unary_fp) 1312 << OrigArg->getType() << OrigArg->getSourceRange(); 1313 1314 // If this is an implicit conversion from float -> double, remove it. 1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1316 Expr *CastArg = Cast->getSubExpr(); 1317 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1318 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1319 "promotion from float to double is the only expected cast here"); 1320 Cast->setSubExpr(0); 1321 TheCall->setArg(NumArgs-1, CastArg); 1322 } 1323 } 1324 1325 return false; 1326} 1327 1328/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1329// This is declared to take (...), so we have to check everything. 1330ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1331 if (TheCall->getNumArgs() < 2) 1332 return ExprError(Diag(TheCall->getLocEnd(), 1333 diag::err_typecheck_call_too_few_args_at_least) 1334 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1335 << TheCall->getSourceRange()); 1336 1337 // Determine which of the following types of shufflevector we're checking: 1338 // 1) unary, vector mask: (lhs, mask) 1339 // 2) binary, vector mask: (lhs, rhs, mask) 1340 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1341 QualType resType = TheCall->getArg(0)->getType(); 1342 unsigned numElements = 0; 1343 1344 if (!TheCall->getArg(0)->isTypeDependent() && 1345 !TheCall->getArg(1)->isTypeDependent()) { 1346 QualType LHSType = TheCall->getArg(0)->getType(); 1347 QualType RHSType = TheCall->getArg(1)->getType(); 1348 1349 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1350 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1351 << SourceRange(TheCall->getArg(0)->getLocStart(), 1352 TheCall->getArg(1)->getLocEnd()); 1353 return ExprError(); 1354 } 1355 1356 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1357 unsigned numResElements = TheCall->getNumArgs() - 2; 1358 1359 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1360 // with mask. If so, verify that RHS is an integer vector type with the 1361 // same number of elts as lhs. 1362 if (TheCall->getNumArgs() == 2) { 1363 if (!RHSType->hasIntegerRepresentation() || 1364 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1365 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1366 << SourceRange(TheCall->getArg(1)->getLocStart(), 1367 TheCall->getArg(1)->getLocEnd()); 1368 numResElements = numElements; 1369 } 1370 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1371 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1372 << SourceRange(TheCall->getArg(0)->getLocStart(), 1373 TheCall->getArg(1)->getLocEnd()); 1374 return ExprError(); 1375 } else if (numElements != numResElements) { 1376 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1377 resType = Context.getVectorType(eltType, numResElements, 1378 VectorType::GenericVector); 1379 } 1380 } 1381 1382 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1383 if (TheCall->getArg(i)->isTypeDependent() || 1384 TheCall->getArg(i)->isValueDependent()) 1385 continue; 1386 1387 llvm::APSInt Result(32); 1388 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1389 return ExprError(Diag(TheCall->getLocStart(), 1390 diag::err_shufflevector_nonconstant_argument) 1391 << TheCall->getArg(i)->getSourceRange()); 1392 1393 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1394 return ExprError(Diag(TheCall->getLocStart(), 1395 diag::err_shufflevector_argument_too_large) 1396 << TheCall->getArg(i)->getSourceRange()); 1397 } 1398 1399 SmallVector<Expr*, 32> exprs; 1400 1401 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1402 exprs.push_back(TheCall->getArg(i)); 1403 TheCall->setArg(i, 0); 1404 } 1405 1406 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 1407 exprs.size(), resType, 1408 TheCall->getCallee()->getLocStart(), 1409 TheCall->getRParenLoc())); 1410} 1411 1412/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1413// This is declared to take (const void*, ...) and can take two 1414// optional constant int args. 1415bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1416 unsigned NumArgs = TheCall->getNumArgs(); 1417 1418 if (NumArgs > 3) 1419 return Diag(TheCall->getLocEnd(), 1420 diag::err_typecheck_call_too_many_args_at_most) 1421 << 0 /*function call*/ << 3 << NumArgs 1422 << TheCall->getSourceRange(); 1423 1424 // Argument 0 is checked for us and the remaining arguments must be 1425 // constant integers. 1426 for (unsigned i = 1; i != NumArgs; ++i) { 1427 Expr *Arg = TheCall->getArg(i); 1428 1429 llvm::APSInt Result; 1430 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1431 return true; 1432 1433 // FIXME: gcc issues a warning and rewrites these to 0. These 1434 // seems especially odd for the third argument since the default 1435 // is 3. 1436 if (i == 1) { 1437 if (Result.getLimitedValue() > 1) 1438 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1439 << "0" << "1" << Arg->getSourceRange(); 1440 } else { 1441 if (Result.getLimitedValue() > 3) 1442 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1443 << "0" << "3" << Arg->getSourceRange(); 1444 } 1445 } 1446 1447 return false; 1448} 1449 1450/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1451/// TheCall is a constant expression. 1452bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1453 llvm::APSInt &Result) { 1454 Expr *Arg = TheCall->getArg(ArgNum); 1455 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1456 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1457 1458 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1459 1460 if (!Arg->isIntegerConstantExpr(Result, Context)) 1461 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1462 << FDecl->getDeclName() << Arg->getSourceRange(); 1463 1464 return false; 1465} 1466 1467/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1468/// int type). This simply type checks that type is one of the defined 1469/// constants (0-3). 1470// For compatibility check 0-3, llvm only handles 0 and 2. 1471bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1472 llvm::APSInt Result; 1473 1474 // Check constant-ness first. 1475 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1476 return true; 1477 1478 Expr *Arg = TheCall->getArg(1); 1479 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1480 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1481 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1482 } 1483 1484 return false; 1485} 1486 1487/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1488/// This checks that val is a constant 1. 1489bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1490 Expr *Arg = TheCall->getArg(1); 1491 llvm::APSInt Result; 1492 1493 // TODO: This is less than ideal. Overload this to take a value. 1494 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1495 return true; 1496 1497 if (Result != 1) 1498 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1499 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1500 1501 return false; 1502} 1503 1504// Handle i > 1 ? "x" : "y", recursively. 1505bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args, 1506 unsigned NumArgs, bool HasVAListArg, 1507 unsigned format_idx, unsigned firstDataArg, 1508 FormatStringType Type, bool inFunctionCall) { 1509 tryAgain: 1510 if (E->isTypeDependent() || E->isValueDependent()) 1511 return false; 1512 1513 E = E->IgnoreParenCasts(); 1514 1515 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 1516 // Technically -Wformat-nonliteral does not warn about this case. 1517 // The behavior of printf and friends in this case is implementation 1518 // dependent. Ideally if the format string cannot be null then 1519 // it should have a 'nonnull' attribute in the function prototype. 1520 return true; 1521 1522 switch (E->getStmtClass()) { 1523 case Stmt::BinaryConditionalOperatorClass: 1524 case Stmt::ConditionalOperatorClass: { 1525 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1526 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg, 1527 format_idx, firstDataArg, Type, 1528 inFunctionCall) 1529 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg, 1530 format_idx, firstDataArg, Type, 1531 inFunctionCall); 1532 } 1533 1534 case Stmt::ImplicitCastExprClass: { 1535 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1536 goto tryAgain; 1537 } 1538 1539 case Stmt::OpaqueValueExprClass: 1540 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1541 E = src; 1542 goto tryAgain; 1543 } 1544 return false; 1545 1546 case Stmt::PredefinedExprClass: 1547 // While __func__, etc., are technically not string literals, they 1548 // cannot contain format specifiers and thus are not a security 1549 // liability. 1550 return true; 1551 1552 case Stmt::DeclRefExprClass: { 1553 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1554 1555 // As an exception, do not flag errors for variables binding to 1556 // const string literals. 1557 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1558 bool isConstant = false; 1559 QualType T = DR->getType(); 1560 1561 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1562 isConstant = AT->getElementType().isConstant(Context); 1563 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1564 isConstant = T.isConstant(Context) && 1565 PT->getPointeeType().isConstant(Context); 1566 } else if (T->isObjCObjectPointerType()) { 1567 // In ObjC, there is usually no "const ObjectPointer" type, 1568 // so don't check if the pointee type is constant. 1569 isConstant = T.isConstant(Context); 1570 } 1571 1572 if (isConstant) { 1573 if (const Expr *Init = VD->getAnyInitializer()) { 1574 // Look through initializers like const char c[] = { "foo" } 1575 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 1576 if (InitList->isStringLiteralInit()) 1577 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 1578 } 1579 return SemaCheckStringLiteral(Init, Args, NumArgs, 1580 HasVAListArg, format_idx, firstDataArg, 1581 Type, /*inFunctionCall*/false); 1582 } 1583 } 1584 1585 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1586 // special check to see if the format string is a function parameter 1587 // of the function calling the printf function. If the function 1588 // has an attribute indicating it is a printf-like function, then we 1589 // should suppress warnings concerning non-literals being used in a call 1590 // to a vprintf function. For example: 1591 // 1592 // void 1593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1594 // va_list ap; 1595 // va_start(ap, fmt); 1596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1597 // ... 1598 // 1599 if (HasVAListArg) { 1600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 1601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 1602 int PVIndex = PV->getFunctionScopeIndex() + 1; 1603 for (specific_attr_iterator<FormatAttr> 1604 i = ND->specific_attr_begin<FormatAttr>(), 1605 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 1606 FormatAttr *PVFormat = *i; 1607 // adjust for implicit parameter 1608 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1609 if (MD->isInstance()) 1610 ++PVIndex; 1611 // We also check if the formats are compatible. 1612 // We can't pass a 'scanf' string to a 'printf' function. 1613 if (PVIndex == PVFormat->getFormatIdx() && 1614 Type == GetFormatStringType(PVFormat)) 1615 return true; 1616 } 1617 } 1618 } 1619 } 1620 } 1621 1622 return false; 1623 } 1624 1625 case Stmt::CallExprClass: 1626 case Stmt::CXXMemberCallExprClass: { 1627 const CallExpr *CE = cast<CallExpr>(E); 1628 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 1629 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 1630 unsigned ArgIndex = FA->getFormatIdx(); 1631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1632 if (MD->isInstance()) 1633 --ArgIndex; 1634 const Expr *Arg = CE->getArg(ArgIndex - 1); 1635 1636 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg, 1637 format_idx, firstDataArg, Type, 1638 inFunctionCall); 1639 } 1640 } 1641 1642 return false; 1643 } 1644 case Stmt::ObjCStringLiteralClass: 1645 case Stmt::StringLiteralClass: { 1646 const StringLiteral *StrE = NULL; 1647 1648 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1649 StrE = ObjCFExpr->getString(); 1650 else 1651 StrE = cast<StringLiteral>(E); 1652 1653 if (StrE) { 1654 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1655 firstDataArg, Type, inFunctionCall); 1656 return true; 1657 } 1658 1659 return false; 1660 } 1661 1662 default: 1663 return false; 1664 } 1665} 1666 1667void 1668Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1669 const Expr * const *ExprArgs, 1670 SourceLocation CallSiteLoc) { 1671 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1672 e = NonNull->args_end(); 1673 i != e; ++i) { 1674 const Expr *ArgExpr = ExprArgs[*i]; 1675 if (ArgExpr->isNullPointerConstant(Context, 1676 Expr::NPC_ValueDependentIsNotNull)) 1677 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1678 } 1679} 1680 1681Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 1682 return llvm::StringSwitch<FormatStringType>(Format->getType()) 1683 .Case("scanf", FST_Scanf) 1684 .Cases("printf", "printf0", FST_Printf) 1685 .Cases("NSString", "CFString", FST_NSString) 1686 .Case("strftime", FST_Strftime) 1687 .Case("strfmon", FST_Strfmon) 1688 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 1689 .Default(FST_Unknown); 1690} 1691 1692/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1693/// functions) for correct use of format strings. 1694void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) { 1695 bool IsCXXMember = false; 1696 // The way the format attribute works in GCC, the implicit this argument 1697 // of member functions is counted. However, it doesn't appear in our own 1698 // lists, so decrement format_idx in that case. 1699 IsCXXMember = isa<CXXMemberCallExpr>(TheCall); 1700 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(), 1701 IsCXXMember, TheCall->getRParenLoc(), 1702 TheCall->getCallee()->getSourceRange()); 1703} 1704 1705void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1706 unsigned NumArgs, bool IsCXXMember, 1707 SourceLocation Loc, SourceRange Range) { 1708 bool HasVAListArg = Format->getFirstArg() == 0; 1709 unsigned format_idx = Format->getFormatIdx() - 1; 1710 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1; 1711 if (IsCXXMember) { 1712 if (format_idx == 0) 1713 return; 1714 --format_idx; 1715 if(firstDataArg != 0) 1716 --firstDataArg; 1717 } 1718 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx, 1719 firstDataArg, GetFormatStringType(Format), Loc, Range); 1720} 1721 1722void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs, 1723 bool HasVAListArg, unsigned format_idx, 1724 unsigned firstDataArg, FormatStringType Type, 1725 SourceLocation Loc, SourceRange Range) { 1726 // CHECK: printf/scanf-like function is called with no format string. 1727 if (format_idx >= NumArgs) { 1728 Diag(Loc, diag::warn_missing_format_string) << Range; 1729 return; 1730 } 1731 1732 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1733 1734 // CHECK: format string is not a string literal. 1735 // 1736 // Dynamically generated format strings are difficult to 1737 // automatically vet at compile time. Requiring that format strings 1738 // are string literals: (1) permits the checking of format strings by 1739 // the compiler and thereby (2) can practically remove the source of 1740 // many format string exploits. 1741 1742 // Format string can be either ObjC string (e.g. @"%d") or 1743 // C string (e.g. "%d") 1744 // ObjC string uses the same format specifiers as C string, so we can use 1745 // the same format string checking logic for both ObjC and C strings. 1746 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1747 format_idx, firstDataArg, Type)) 1748 return; // Literal format string found, check done! 1749 1750 // Strftime is particular as it always uses a single 'time' argument, 1751 // so it is safe to pass a non-literal string. 1752 if (Type == FST_Strftime) 1753 return; 1754 1755 // Do not emit diag when the string param is a macro expansion and the 1756 // format is either NSString or CFString. This is a hack to prevent 1757 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 1758 // which are usually used in place of NS and CF string literals. 1759 if (Type == FST_NSString && 1760 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 1761 return; 1762 1763 // If there are no arguments specified, warn with -Wformat-security, otherwise 1764 // warn only with -Wformat-nonliteral. 1765 if (NumArgs == format_idx+1) 1766 Diag(Args[format_idx]->getLocStart(), 1767 diag::warn_format_nonliteral_noargs) 1768 << OrigFormatExpr->getSourceRange(); 1769 else 1770 Diag(Args[format_idx]->getLocStart(), 1771 diag::warn_format_nonliteral) 1772 << OrigFormatExpr->getSourceRange(); 1773} 1774 1775namespace { 1776class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1777protected: 1778 Sema &S; 1779 const StringLiteral *FExpr; 1780 const Expr *OrigFormatExpr; 1781 const unsigned FirstDataArg; 1782 const unsigned NumDataArgs; 1783 const bool IsObjCLiteral; 1784 const char *Beg; // Start of format string. 1785 const bool HasVAListArg; 1786 const Expr * const *Args; 1787 const unsigned NumArgs; 1788 unsigned FormatIdx; 1789 llvm::BitVector CoveredArgs; 1790 bool usesPositionalArgs; 1791 bool atFirstArg; 1792 bool inFunctionCall; 1793public: 1794 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1795 const Expr *origFormatExpr, unsigned firstDataArg, 1796 unsigned numDataArgs, bool isObjCLiteral, 1797 const char *beg, bool hasVAListArg, 1798 Expr **args, unsigned numArgs, 1799 unsigned formatIdx, bool inFunctionCall) 1800 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1801 FirstDataArg(firstDataArg), 1802 NumDataArgs(numDataArgs), 1803 IsObjCLiteral(isObjCLiteral), Beg(beg), 1804 HasVAListArg(hasVAListArg), 1805 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1806 usesPositionalArgs(false), atFirstArg(true), 1807 inFunctionCall(inFunctionCall) { 1808 CoveredArgs.resize(numDataArgs); 1809 CoveredArgs.reset(); 1810 } 1811 1812 void DoneProcessing(); 1813 1814 void HandleIncompleteSpecifier(const char *startSpecifier, 1815 unsigned specifierLen); 1816 1817 void HandleNonStandardLengthModifier( 1818 const analyze_format_string::LengthModifier &LM, 1819 const char *startSpecifier, unsigned specifierLen); 1820 1821 void HandleNonStandardConversionSpecifier( 1822 const analyze_format_string::ConversionSpecifier &CS, 1823 const char *startSpecifier, unsigned specifierLen); 1824 1825 void HandleNonStandardConversionSpecification( 1826 const analyze_format_string::LengthModifier &LM, 1827 const analyze_format_string::ConversionSpecifier &CS, 1828 const char *startSpecifier, unsigned specifierLen); 1829 1830 virtual void HandlePosition(const char *startPos, unsigned posLen); 1831 1832 virtual void HandleInvalidPosition(const char *startSpecifier, 1833 unsigned specifierLen, 1834 analyze_format_string::PositionContext p); 1835 1836 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1837 1838 void HandleNullChar(const char *nullCharacter); 1839 1840 template <typename Range> 1841 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1842 const Expr *ArgumentExpr, 1843 PartialDiagnostic PDiag, 1844 SourceLocation StringLoc, 1845 bool IsStringLocation, Range StringRange, 1846 FixItHint Fixit = FixItHint()); 1847 1848protected: 1849 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1850 const char *startSpec, 1851 unsigned specifierLen, 1852 const char *csStart, unsigned csLen); 1853 1854 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1855 const char *startSpec, 1856 unsigned specifierLen); 1857 1858 SourceRange getFormatStringRange(); 1859 CharSourceRange getSpecifierRange(const char *startSpecifier, 1860 unsigned specifierLen); 1861 SourceLocation getLocationOfByte(const char *x); 1862 1863 const Expr *getDataArg(unsigned i) const; 1864 1865 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1866 const analyze_format_string::ConversionSpecifier &CS, 1867 const char *startSpecifier, unsigned specifierLen, 1868 unsigned argIndex); 1869 1870 template <typename Range> 1871 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1872 bool IsStringLocation, Range StringRange, 1873 FixItHint Fixit = FixItHint()); 1874 1875 void CheckPositionalAndNonpositionalArgs( 1876 const analyze_format_string::FormatSpecifier *FS); 1877}; 1878} 1879 1880SourceRange CheckFormatHandler::getFormatStringRange() { 1881 return OrigFormatExpr->getSourceRange(); 1882} 1883 1884CharSourceRange CheckFormatHandler:: 1885getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1886 SourceLocation Start = getLocationOfByte(startSpecifier); 1887 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1888 1889 // Advance the end SourceLocation by one due to half-open ranges. 1890 End = End.getLocWithOffset(1); 1891 1892 return CharSourceRange::getCharRange(Start, End); 1893} 1894 1895SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1896 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1897} 1898 1899void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1900 unsigned specifierLen){ 1901 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1902 getLocationOfByte(startSpecifier), 1903 /*IsStringLocation*/true, 1904 getSpecifierRange(startSpecifier, specifierLen)); 1905} 1906 1907void CheckFormatHandler::HandleNonStandardLengthModifier( 1908 const analyze_format_string::LengthModifier &LM, 1909 const char *startSpecifier, unsigned specifierLen) { 1910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString() 1911 << 0, 1912 getLocationOfByte(LM.getStart()), 1913 /*IsStringLocation*/true, 1914 getSpecifierRange(startSpecifier, specifierLen)); 1915} 1916 1917void CheckFormatHandler::HandleNonStandardConversionSpecifier( 1918 const analyze_format_string::ConversionSpecifier &CS, 1919 const char *startSpecifier, unsigned specifierLen) { 1920 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() 1921 << 1, 1922 getLocationOfByte(CS.getStart()), 1923 /*IsStringLocation*/true, 1924 getSpecifierRange(startSpecifier, specifierLen)); 1925} 1926 1927void CheckFormatHandler::HandleNonStandardConversionSpecification( 1928 const analyze_format_string::LengthModifier &LM, 1929 const analyze_format_string::ConversionSpecifier &CS, 1930 const char *startSpecifier, unsigned specifierLen) { 1931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec) 1932 << LM.toString() << CS.toString(), 1933 getLocationOfByte(LM.getStart()), 1934 /*IsStringLocation*/true, 1935 getSpecifierRange(startSpecifier, specifierLen)); 1936} 1937 1938void CheckFormatHandler::HandlePosition(const char *startPos, 1939 unsigned posLen) { 1940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 1941 getLocationOfByte(startPos), 1942 /*IsStringLocation*/true, 1943 getSpecifierRange(startPos, posLen)); 1944} 1945 1946void 1947CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1948 analyze_format_string::PositionContext p) { 1949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1950 << (unsigned) p, 1951 getLocationOfByte(startPos), /*IsStringLocation*/true, 1952 getSpecifierRange(startPos, posLen)); 1953} 1954 1955void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1956 unsigned posLen) { 1957 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1958 getLocationOfByte(startPos), 1959 /*IsStringLocation*/true, 1960 getSpecifierRange(startPos, posLen)); 1961} 1962 1963void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1964 if (!IsObjCLiteral) { 1965 // The presence of a null character is likely an error. 1966 EmitFormatDiagnostic( 1967 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1968 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1969 getFormatStringRange()); 1970 } 1971} 1972 1973const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1974 return Args[FirstDataArg + i]; 1975} 1976 1977void CheckFormatHandler::DoneProcessing() { 1978 // Does the number of data arguments exceed the number of 1979 // format conversions in the format string? 1980 if (!HasVAListArg) { 1981 // Find any arguments that weren't covered. 1982 CoveredArgs.flip(); 1983 signed notCoveredArg = CoveredArgs.find_first(); 1984 if (notCoveredArg >= 0) { 1985 assert((unsigned)notCoveredArg < NumDataArgs); 1986 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart(); 1987 if (!S.getSourceManager().isInSystemMacro(Loc)) { 1988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1989 Loc, 1990 /*IsStringLocation*/false, getFormatStringRange()); 1991 } 1992 } 1993 } 1994} 1995 1996bool 1997CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1998 SourceLocation Loc, 1999 const char *startSpec, 2000 unsigned specifierLen, 2001 const char *csStart, 2002 unsigned csLen) { 2003 2004 bool keepGoing = true; 2005 if (argIndex < NumDataArgs) { 2006 // Consider the argument coverered, even though the specifier doesn't 2007 // make sense. 2008 CoveredArgs.set(argIndex); 2009 } 2010 else { 2011 // If argIndex exceeds the number of data arguments we 2012 // don't issue a warning because that is just a cascade of warnings (and 2013 // they may have intended '%%' anyway). We don't want to continue processing 2014 // the format string after this point, however, as we will like just get 2015 // gibberish when trying to match arguments. 2016 keepGoing = false; 2017 } 2018 2019 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2020 << StringRef(csStart, csLen), 2021 Loc, /*IsStringLocation*/true, 2022 getSpecifierRange(startSpec, specifierLen)); 2023 2024 return keepGoing; 2025} 2026 2027void 2028CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2029 const char *startSpec, 2030 unsigned specifierLen) { 2031 EmitFormatDiagnostic( 2032 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2033 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2034} 2035 2036bool 2037CheckFormatHandler::CheckNumArgs( 2038 const analyze_format_string::FormatSpecifier &FS, 2039 const analyze_format_string::ConversionSpecifier &CS, 2040 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2041 2042 if (argIndex >= NumDataArgs) { 2043 PartialDiagnostic PDiag = FS.usesPositionalArg() 2044 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2045 << (argIndex+1) << NumDataArgs) 2046 : S.PDiag(diag::warn_printf_insufficient_data_args); 2047 EmitFormatDiagnostic( 2048 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2049 getSpecifierRange(startSpecifier, specifierLen)); 2050 return false; 2051 } 2052 return true; 2053} 2054 2055template<typename Range> 2056void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2057 SourceLocation Loc, 2058 bool IsStringLocation, 2059 Range StringRange, 2060 FixItHint FixIt) { 2061 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2062 Loc, IsStringLocation, StringRange, FixIt); 2063} 2064 2065/// \brief If the format string is not within the funcion call, emit a note 2066/// so that the function call and string are in diagnostic messages. 2067/// 2068/// \param inFunctionCall if true, the format string is within the function 2069/// call and only one diagnostic message will be produced. Otherwise, an 2070/// extra note will be emitted pointing to location of the format string. 2071/// 2072/// \param ArgumentExpr the expression that is passed as the format string 2073/// argument in the function call. Used for getting locations when two 2074/// diagnostics are emitted. 2075/// 2076/// \param PDiag the callee should already have provided any strings for the 2077/// diagnostic message. This function only adds locations and fixits 2078/// to diagnostics. 2079/// 2080/// \param Loc primary location for diagnostic. If two diagnostics are 2081/// required, one will be at Loc and a new SourceLocation will be created for 2082/// the other one. 2083/// 2084/// \param IsStringLocation if true, Loc points to the format string should be 2085/// used for the note. Otherwise, Loc points to the argument list and will 2086/// be used with PDiag. 2087/// 2088/// \param StringRange some or all of the string to highlight. This is 2089/// templated so it can accept either a CharSourceRange or a SourceRange. 2090/// 2091/// \param Fixit optional fix it hint for the format string. 2092template<typename Range> 2093void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2094 const Expr *ArgumentExpr, 2095 PartialDiagnostic PDiag, 2096 SourceLocation Loc, 2097 bool IsStringLocation, 2098 Range StringRange, 2099 FixItHint FixIt) { 2100 if (InFunctionCall) 2101 S.Diag(Loc, PDiag) << StringRange << FixIt; 2102 else { 2103 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2104 << ArgumentExpr->getSourceRange(); 2105 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2106 diag::note_format_string_defined) 2107 << StringRange << FixIt; 2108 } 2109} 2110 2111//===--- CHECK: Printf format string checking ------------------------------===// 2112 2113namespace { 2114class CheckPrintfHandler : public CheckFormatHandler { 2115public: 2116 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2117 const Expr *origFormatExpr, unsigned firstDataArg, 2118 unsigned numDataArgs, bool isObjCLiteral, 2119 const char *beg, bool hasVAListArg, 2120 Expr **Args, unsigned NumArgs, 2121 unsigned formatIdx, bool inFunctionCall) 2122 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2123 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2124 Args, NumArgs, formatIdx, inFunctionCall) {} 2125 2126 2127 bool HandleInvalidPrintfConversionSpecifier( 2128 const analyze_printf::PrintfSpecifier &FS, 2129 const char *startSpecifier, 2130 unsigned specifierLen); 2131 2132 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2133 const char *startSpecifier, 2134 unsigned specifierLen); 2135 2136 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2137 const char *startSpecifier, unsigned specifierLen); 2138 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2139 const analyze_printf::OptionalAmount &Amt, 2140 unsigned type, 2141 const char *startSpecifier, unsigned specifierLen); 2142 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2143 const analyze_printf::OptionalFlag &flag, 2144 const char *startSpecifier, unsigned specifierLen); 2145 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2146 const analyze_printf::OptionalFlag &ignoredFlag, 2147 const analyze_printf::OptionalFlag &flag, 2148 const char *startSpecifier, unsigned specifierLen); 2149}; 2150} 2151 2152bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2153 const analyze_printf::PrintfSpecifier &FS, 2154 const char *startSpecifier, 2155 unsigned specifierLen) { 2156 const analyze_printf::PrintfConversionSpecifier &CS = 2157 FS.getConversionSpecifier(); 2158 2159 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2160 getLocationOfByte(CS.getStart()), 2161 startSpecifier, specifierLen, 2162 CS.getStart(), CS.getLength()); 2163} 2164 2165bool CheckPrintfHandler::HandleAmount( 2166 const analyze_format_string::OptionalAmount &Amt, 2167 unsigned k, const char *startSpecifier, 2168 unsigned specifierLen) { 2169 2170 if (Amt.hasDataArgument()) { 2171 if (!HasVAListArg) { 2172 unsigned argIndex = Amt.getArgIndex(); 2173 if (argIndex >= NumDataArgs) { 2174 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2175 << k, 2176 getLocationOfByte(Amt.getStart()), 2177 /*IsStringLocation*/true, 2178 getSpecifierRange(startSpecifier, specifierLen)); 2179 // Don't do any more checking. We will just emit 2180 // spurious errors. 2181 return false; 2182 } 2183 2184 // Type check the data argument. It should be an 'int'. 2185 // Although not in conformance with C99, we also allow the argument to be 2186 // an 'unsigned int' as that is a reasonably safe case. GCC also 2187 // doesn't emit a warning for that case. 2188 CoveredArgs.set(argIndex); 2189 const Expr *Arg = getDataArg(argIndex); 2190 QualType T = Arg->getType(); 2191 2192 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 2193 assert(ATR.isValid()); 2194 2195 if (!ATR.matchesType(S.Context, T)) { 2196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2197 << k << ATR.getRepresentativeTypeName(S.Context) 2198 << T << Arg->getSourceRange(), 2199 getLocationOfByte(Amt.getStart()), 2200 /*IsStringLocation*/true, 2201 getSpecifierRange(startSpecifier, specifierLen)); 2202 // Don't do any more checking. We will just emit 2203 // spurious errors. 2204 return false; 2205 } 2206 } 2207 } 2208 return true; 2209} 2210 2211void CheckPrintfHandler::HandleInvalidAmount( 2212 const analyze_printf::PrintfSpecifier &FS, 2213 const analyze_printf::OptionalAmount &Amt, 2214 unsigned type, 2215 const char *startSpecifier, 2216 unsigned specifierLen) { 2217 const analyze_printf::PrintfConversionSpecifier &CS = 2218 FS.getConversionSpecifier(); 2219 2220 FixItHint fixit = 2221 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2222 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2223 Amt.getConstantLength())) 2224 : FixItHint(); 2225 2226 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2227 << type << CS.toString(), 2228 getLocationOfByte(Amt.getStart()), 2229 /*IsStringLocation*/true, 2230 getSpecifierRange(startSpecifier, specifierLen), 2231 fixit); 2232} 2233 2234void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2235 const analyze_printf::OptionalFlag &flag, 2236 const char *startSpecifier, 2237 unsigned specifierLen) { 2238 // Warn about pointless flag with a fixit removal. 2239 const analyze_printf::PrintfConversionSpecifier &CS = 2240 FS.getConversionSpecifier(); 2241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2242 << flag.toString() << CS.toString(), 2243 getLocationOfByte(flag.getPosition()), 2244 /*IsStringLocation*/true, 2245 getSpecifierRange(startSpecifier, specifierLen), 2246 FixItHint::CreateRemoval( 2247 getSpecifierRange(flag.getPosition(), 1))); 2248} 2249 2250void CheckPrintfHandler::HandleIgnoredFlag( 2251 const analyze_printf::PrintfSpecifier &FS, 2252 const analyze_printf::OptionalFlag &ignoredFlag, 2253 const analyze_printf::OptionalFlag &flag, 2254 const char *startSpecifier, 2255 unsigned specifierLen) { 2256 // Warn about ignored flag with a fixit removal. 2257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2258 << ignoredFlag.toString() << flag.toString(), 2259 getLocationOfByte(ignoredFlag.getPosition()), 2260 /*IsStringLocation*/true, 2261 getSpecifierRange(startSpecifier, specifierLen), 2262 FixItHint::CreateRemoval( 2263 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2264} 2265 2266bool 2267CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2268 &FS, 2269 const char *startSpecifier, 2270 unsigned specifierLen) { 2271 2272 using namespace analyze_format_string; 2273 using namespace analyze_printf; 2274 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2275 2276 if (FS.consumesDataArgument()) { 2277 if (atFirstArg) { 2278 atFirstArg = false; 2279 usesPositionalArgs = FS.usesPositionalArg(); 2280 } 2281 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2282 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2283 startSpecifier, specifierLen); 2284 return false; 2285 } 2286 } 2287 2288 // First check if the field width, precision, and conversion specifier 2289 // have matching data arguments. 2290 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2291 startSpecifier, specifierLen)) { 2292 return false; 2293 } 2294 2295 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2296 startSpecifier, specifierLen)) { 2297 return false; 2298 } 2299 2300 if (!CS.consumesDataArgument()) { 2301 // FIXME: Technically specifying a precision or field width here 2302 // makes no sense. Worth issuing a warning at some point. 2303 return true; 2304 } 2305 2306 // Consume the argument. 2307 unsigned argIndex = FS.getArgIndex(); 2308 if (argIndex < NumDataArgs) { 2309 // The check to see if the argIndex is valid will come later. 2310 // We set the bit here because we may exit early from this 2311 // function if we encounter some other error. 2312 CoveredArgs.set(argIndex); 2313 } 2314 2315 // Check for using an Objective-C specific conversion specifier 2316 // in a non-ObjC literal. 2317 if (!IsObjCLiteral && CS.isObjCArg()) { 2318 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2319 specifierLen); 2320 } 2321 2322 // Check for invalid use of field width 2323 if (!FS.hasValidFieldWidth()) { 2324 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2325 startSpecifier, specifierLen); 2326 } 2327 2328 // Check for invalid use of precision 2329 if (!FS.hasValidPrecision()) { 2330 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2331 startSpecifier, specifierLen); 2332 } 2333 2334 // Check each flag does not conflict with any other component. 2335 if (!FS.hasValidThousandsGroupingPrefix()) 2336 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2337 if (!FS.hasValidLeadingZeros()) 2338 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2339 if (!FS.hasValidPlusPrefix()) 2340 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2341 if (!FS.hasValidSpacePrefix()) 2342 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2343 if (!FS.hasValidAlternativeForm()) 2344 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2345 if (!FS.hasValidLeftJustified()) 2346 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2347 2348 // Check that flags are not ignored by another flag 2349 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2350 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2351 startSpecifier, specifierLen); 2352 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2353 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2354 startSpecifier, specifierLen); 2355 2356 // Check the length modifier is valid with the given conversion specifier. 2357 const LengthModifier &LM = FS.getLengthModifier(); 2358 if (!FS.hasValidLengthModifier()) 2359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2360 << LM.toString() << CS.toString(), 2361 getLocationOfByte(LM.getStart()), 2362 /*IsStringLocation*/true, 2363 getSpecifierRange(startSpecifier, specifierLen), 2364 FixItHint::CreateRemoval( 2365 getSpecifierRange(LM.getStart(), 2366 LM.getLength()))); 2367 if (!FS.hasStandardLengthModifier()) 2368 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2369 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2370 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2371 if (!FS.hasStandardLengthConversionCombination()) 2372 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2373 specifierLen); 2374 2375 // Are we using '%n'? 2376 if (CS.getKind() == ConversionSpecifier::nArg) { 2377 // Issue a warning about this being a possible security issue. 2378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2379 getLocationOfByte(CS.getStart()), 2380 /*IsStringLocation*/true, 2381 getSpecifierRange(startSpecifier, specifierLen)); 2382 // Continue checking the other format specifiers. 2383 return true; 2384 } 2385 2386 // The remaining checks depend on the data arguments. 2387 if (HasVAListArg) 2388 return true; 2389 2390 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2391 return false; 2392 2393 // Now type check the data expression that matches the 2394 // format specifier. 2395 const Expr *Ex = getDataArg(argIndex); 2396 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context, 2397 IsObjCLiteral); 2398 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2399 // Check if we didn't match because of an implicit cast from a 'char' 2400 // or 'short' to an 'int'. This is done because printf is a varargs 2401 // function. 2402 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 2403 if (ICE->getType() == S.Context.IntTy || 2404 ICE->getType() == S.Context.UnsignedIntTy) { 2405 // All further checking is done on the subexpression. 2406 Ex = ICE->getSubExpr(); 2407 if (ATR.matchesType(S.Context, Ex->getType())) 2408 return true; 2409 } 2410 2411 // We may be able to offer a FixItHint if it is a supported type. 2412 PrintfSpecifier fixedFS = FS; 2413 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2414 S.Context, IsObjCLiteral); 2415 2416 if (success) { 2417 // Get the fix string from the fixed format specifier 2418 SmallString<128> buf; 2419 llvm::raw_svector_ostream os(buf); 2420 fixedFS.toString(os); 2421 2422 EmitFormatDiagnostic( 2423 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2424 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2425 << Ex->getSourceRange(), 2426 Ex->getLocStart(), 2427 /*IsStringLocation*/false, 2428 getSpecifierRange(startSpecifier, specifierLen), 2429 FixItHint::CreateReplacement( 2430 getSpecifierRange(startSpecifier, specifierLen), 2431 os.str())); 2432 } 2433 else { 2434 EmitFormatDiagnostic( 2435 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2436 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2437 << getSpecifierRange(startSpecifier, specifierLen) 2438 << Ex->getSourceRange(), 2439 Ex->getLocStart(), 2440 /*IsStringLocation*/false, 2441 getSpecifierRange(startSpecifier, specifierLen)); 2442 } 2443 } 2444 2445 return true; 2446} 2447 2448//===--- CHECK: Scanf format string checking ------------------------------===// 2449 2450namespace { 2451class CheckScanfHandler : public CheckFormatHandler { 2452public: 2453 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2454 const Expr *origFormatExpr, unsigned firstDataArg, 2455 unsigned numDataArgs, bool isObjCLiteral, 2456 const char *beg, bool hasVAListArg, 2457 Expr **Args, unsigned NumArgs, 2458 unsigned formatIdx, bool inFunctionCall) 2459 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2460 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2461 Args, NumArgs, formatIdx, inFunctionCall) {} 2462 2463 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2464 const char *startSpecifier, 2465 unsigned specifierLen); 2466 2467 bool HandleInvalidScanfConversionSpecifier( 2468 const analyze_scanf::ScanfSpecifier &FS, 2469 const char *startSpecifier, 2470 unsigned specifierLen); 2471 2472 void HandleIncompleteScanList(const char *start, const char *end); 2473}; 2474} 2475 2476void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2477 const char *end) { 2478 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2479 getLocationOfByte(end), /*IsStringLocation*/true, 2480 getSpecifierRange(start, end - start)); 2481} 2482 2483bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2484 const analyze_scanf::ScanfSpecifier &FS, 2485 const char *startSpecifier, 2486 unsigned specifierLen) { 2487 2488 const analyze_scanf::ScanfConversionSpecifier &CS = 2489 FS.getConversionSpecifier(); 2490 2491 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2492 getLocationOfByte(CS.getStart()), 2493 startSpecifier, specifierLen, 2494 CS.getStart(), CS.getLength()); 2495} 2496 2497bool CheckScanfHandler::HandleScanfSpecifier( 2498 const analyze_scanf::ScanfSpecifier &FS, 2499 const char *startSpecifier, 2500 unsigned specifierLen) { 2501 2502 using namespace analyze_scanf; 2503 using namespace analyze_format_string; 2504 2505 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2506 2507 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2508 // be used to decide if we are using positional arguments consistently. 2509 if (FS.consumesDataArgument()) { 2510 if (atFirstArg) { 2511 atFirstArg = false; 2512 usesPositionalArgs = FS.usesPositionalArg(); 2513 } 2514 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2515 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2516 startSpecifier, specifierLen); 2517 return false; 2518 } 2519 } 2520 2521 // Check if the field with is non-zero. 2522 const OptionalAmount &Amt = FS.getFieldWidth(); 2523 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2524 if (Amt.getConstantAmount() == 0) { 2525 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2526 Amt.getConstantLength()); 2527 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2528 getLocationOfByte(Amt.getStart()), 2529 /*IsStringLocation*/true, R, 2530 FixItHint::CreateRemoval(R)); 2531 } 2532 } 2533 2534 if (!FS.consumesDataArgument()) { 2535 // FIXME: Technically specifying a precision or field width here 2536 // makes no sense. Worth issuing a warning at some point. 2537 return true; 2538 } 2539 2540 // Consume the argument. 2541 unsigned argIndex = FS.getArgIndex(); 2542 if (argIndex < NumDataArgs) { 2543 // The check to see if the argIndex is valid will come later. 2544 // We set the bit here because we may exit early from this 2545 // function if we encounter some other error. 2546 CoveredArgs.set(argIndex); 2547 } 2548 2549 // Check the length modifier is valid with the given conversion specifier. 2550 const LengthModifier &LM = FS.getLengthModifier(); 2551 if (!FS.hasValidLengthModifier()) { 2552 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength()); 2553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2554 << LM.toString() << CS.toString() 2555 << getSpecifierRange(startSpecifier, specifierLen), 2556 getLocationOfByte(LM.getStart()), 2557 /*IsStringLocation*/true, R, 2558 FixItHint::CreateRemoval(R)); 2559 } 2560 2561 if (!FS.hasStandardLengthModifier()) 2562 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen); 2563 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2564 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2565 if (!FS.hasStandardLengthConversionCombination()) 2566 HandleNonStandardConversionSpecification(LM, CS, startSpecifier, 2567 specifierLen); 2568 2569 // The remaining checks depend on the data arguments. 2570 if (HasVAListArg) 2571 return true; 2572 2573 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2574 return false; 2575 2576 // Check that the argument type matches the format specifier. 2577 const Expr *Ex = getDataArg(argIndex); 2578 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context); 2579 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2580 ScanfSpecifier fixedFS = FS; 2581 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2582 S.Context); 2583 2584 if (success) { 2585 // Get the fix string from the fixed format specifier. 2586 SmallString<128> buf; 2587 llvm::raw_svector_ostream os(buf); 2588 fixedFS.toString(os); 2589 2590 EmitFormatDiagnostic( 2591 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2592 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2593 << Ex->getSourceRange(), 2594 Ex->getLocStart(), 2595 /*IsStringLocation*/false, 2596 getSpecifierRange(startSpecifier, specifierLen), 2597 FixItHint::CreateReplacement( 2598 getSpecifierRange(startSpecifier, specifierLen), 2599 os.str())); 2600 } else { 2601 EmitFormatDiagnostic( 2602 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2603 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2604 << Ex->getSourceRange(), 2605 Ex->getLocStart(), 2606 /*IsStringLocation*/false, 2607 getSpecifierRange(startSpecifier, specifierLen)); 2608 } 2609 } 2610 2611 return true; 2612} 2613 2614void Sema::CheckFormatString(const StringLiteral *FExpr, 2615 const Expr *OrigFormatExpr, 2616 Expr **Args, unsigned NumArgs, 2617 bool HasVAListArg, unsigned format_idx, 2618 unsigned firstDataArg, FormatStringType Type, 2619 bool inFunctionCall) { 2620 2621 // CHECK: is the format string a wide literal? 2622 if (!FExpr->isAscii()) { 2623 CheckFormatHandler::EmitFormatDiagnostic( 2624 *this, inFunctionCall, Args[format_idx], 2625 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2626 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2627 return; 2628 } 2629 2630 // Str - The format string. NOTE: this is NOT null-terminated! 2631 StringRef StrRef = FExpr->getString(); 2632 const char *Str = StrRef.data(); 2633 unsigned StrLen = StrRef.size(); 2634 const unsigned numDataArgs = NumArgs - firstDataArg; 2635 2636 // CHECK: empty format string? 2637 if (StrLen == 0 && numDataArgs > 0) { 2638 CheckFormatHandler::EmitFormatDiagnostic( 2639 *this, inFunctionCall, Args[format_idx], 2640 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2641 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2642 return; 2643 } 2644 2645 if (Type == FST_Printf || Type == FST_NSString) { 2646 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2647 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2648 Str, HasVAListArg, Args, NumArgs, format_idx, 2649 inFunctionCall); 2650 2651 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2652 getLangOpts())) 2653 H.DoneProcessing(); 2654 } else if (Type == FST_Scanf) { 2655 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2656 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2657 Str, HasVAListArg, Args, NumArgs, format_idx, 2658 inFunctionCall); 2659 2660 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2661 getLangOpts())) 2662 H.DoneProcessing(); 2663 } // TODO: handle other formats 2664} 2665 2666//===--- CHECK: Standard memory functions ---------------------------------===// 2667 2668/// \brief Determine whether the given type is a dynamic class type (e.g., 2669/// whether it has a vtable). 2670static bool isDynamicClassType(QualType T) { 2671 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2672 if (CXXRecordDecl *Definition = Record->getDefinition()) 2673 if (Definition->isDynamicClass()) 2674 return true; 2675 2676 return false; 2677} 2678 2679/// \brief If E is a sizeof expression, returns its argument expression, 2680/// otherwise returns NULL. 2681static const Expr *getSizeOfExprArg(const Expr* E) { 2682 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2683 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2684 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2685 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2686 2687 return 0; 2688} 2689 2690/// \brief If E is a sizeof expression, returns its argument type. 2691static QualType getSizeOfArgType(const Expr* E) { 2692 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2693 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2694 if (SizeOf->getKind() == clang::UETT_SizeOf) 2695 return SizeOf->getTypeOfArgument(); 2696 2697 return QualType(); 2698} 2699 2700/// \brief Check for dangerous or invalid arguments to memset(). 2701/// 2702/// This issues warnings on known problematic, dangerous or unspecified 2703/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2704/// function calls. 2705/// 2706/// \param Call The call expression to diagnose. 2707void Sema::CheckMemaccessArguments(const CallExpr *Call, 2708 unsigned BId, 2709 IdentifierInfo *FnName) { 2710 assert(BId != 0); 2711 2712 // It is possible to have a non-standard definition of memset. Validate 2713 // we have enough arguments, and if not, abort further checking. 2714 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2715 if (Call->getNumArgs() < ExpectedNumArgs) 2716 return; 2717 2718 unsigned LastArg = (BId == Builtin::BImemset || 2719 BId == Builtin::BIstrndup ? 1 : 2); 2720 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2721 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2722 2723 // We have special checking when the length is a sizeof expression. 2724 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2725 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2726 llvm::FoldingSetNodeID SizeOfArgID; 2727 2728 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2729 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2730 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2731 2732 QualType DestTy = Dest->getType(); 2733 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2734 QualType PointeeTy = DestPtrTy->getPointeeType(); 2735 2736 // Never warn about void type pointers. This can be used to suppress 2737 // false positives. 2738 if (PointeeTy->isVoidType()) 2739 continue; 2740 2741 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2742 // actually comparing the expressions for equality. Because computing the 2743 // expression IDs can be expensive, we only do this if the diagnostic is 2744 // enabled. 2745 if (SizeOfArg && 2746 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2747 SizeOfArg->getExprLoc())) { 2748 // We only compute IDs for expressions if the warning is enabled, and 2749 // cache the sizeof arg's ID. 2750 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2751 SizeOfArg->Profile(SizeOfArgID, Context, true); 2752 llvm::FoldingSetNodeID DestID; 2753 Dest->Profile(DestID, Context, true); 2754 if (DestID == SizeOfArgID) { 2755 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2756 // over sizeof(src) as well. 2757 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2758 FixItHint Fixit = FixItHint(); // Default hint. 2759 StringRef ReadableName = FnName->getName(); 2760 2761 if (isa<DeclRefExpr>(SizeOfArg)) 2762 Fixit = FixItHint::CreateInsertion(SizeOfArg->getLocStart(), "*"); 2763 2764 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2765 if (UnaryOp->getOpcode() == UO_AddrOf) { 2766 Fixit = FixItHint::CreateRemoval( 2767 CharSourceRange::getTokenRange(SizeOfArg->getLocStart(), 2768 SizeOfArg->getLocStart())); 2769 ActionIdx = 1; // If its an address-of operator, just remove it. 2770 } 2771 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2772 ActionIdx = 2; // If the pointee's size is sizeof(char), 2773 // suggest an explicit length. 2774 unsigned DestSrcSelect = 2775 (BId == Builtin::BIstrndup ? 1 : ArgIdx); 2776 2777 // If the function is defined as a builtin macro, do not show macro 2778 // expansion. 2779 SourceLocation SL = SizeOfArg->getExprLoc(); 2780 SourceRange DSR = Dest->getSourceRange(); 2781 SourceRange SSR = SizeOfArg->getSourceRange(); 2782 SourceManager &SM = PP.getSourceManager(); 2783 2784 if (SM.isMacroArgExpansion(SL)) { 2785 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 2786 SL = SM.getSpellingLoc(SL); 2787 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 2788 SM.getSpellingLoc(DSR.getEnd())); 2789 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 2790 SM.getSpellingLoc(SSR.getEnd())); 2791 } 2792 2793 DiagRuntimeBehavior(SL, Dest, 2794 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 2795 << ReadableName 2796 << DestSrcSelect 2797 << ActionIdx 2798 << DSR 2799 << SSR 2800 << Fixit); 2801 break; 2802 } 2803 } 2804 2805 // Also check for cases where the sizeof argument is the exact same 2806 // type as the memory argument, and where it points to a user-defined 2807 // record type. 2808 if (SizeOfArgTy != QualType()) { 2809 if (PointeeTy->isRecordType() && 2810 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 2811 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 2812 PDiag(diag::warn_sizeof_pointer_type_memaccess) 2813 << FnName << SizeOfArgTy << ArgIdx 2814 << PointeeTy << Dest->getSourceRange() 2815 << LenExpr->getSourceRange()); 2816 break; 2817 } 2818 } 2819 2820 // Always complain about dynamic classes. 2821 if (isDynamicClassType(PointeeTy)) { 2822 2823 unsigned OperationType = 0; 2824 // "overwritten" if we're warning about the destination for any call 2825 // but memcmp; otherwise a verb appropriate to the call. 2826 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 2827 if (BId == Builtin::BImemcpy) 2828 OperationType = 1; 2829 else if(BId == Builtin::BImemmove) 2830 OperationType = 2; 2831 else if (BId == Builtin::BImemcmp) 2832 OperationType = 3; 2833 } 2834 2835 DiagRuntimeBehavior( 2836 Dest->getExprLoc(), Dest, 2837 PDiag(diag::warn_dyn_class_memaccess) 2838 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 2839 << FnName << PointeeTy 2840 << OperationType 2841 << Call->getCallee()->getSourceRange()); 2842 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 2843 BId != Builtin::BImemset) 2844 DiagRuntimeBehavior( 2845 Dest->getExprLoc(), Dest, 2846 PDiag(diag::warn_arc_object_memaccess) 2847 << ArgIdx << FnName << PointeeTy 2848 << Call->getCallee()->getSourceRange()); 2849 else 2850 continue; 2851 2852 DiagRuntimeBehavior( 2853 Dest->getExprLoc(), Dest, 2854 PDiag(diag::note_bad_memaccess_silence) 2855 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2856 break; 2857 } 2858 } 2859} 2860 2861// A little helper routine: ignore addition and subtraction of integer literals. 2862// This intentionally does not ignore all integer constant expressions because 2863// we don't want to remove sizeof(). 2864static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2865 Ex = Ex->IgnoreParenCasts(); 2866 2867 for (;;) { 2868 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2869 if (!BO || !BO->isAdditiveOp()) 2870 break; 2871 2872 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2873 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2874 2875 if (isa<IntegerLiteral>(RHS)) 2876 Ex = LHS; 2877 else if (isa<IntegerLiteral>(LHS)) 2878 Ex = RHS; 2879 else 2880 break; 2881 } 2882 2883 return Ex; 2884} 2885 2886// Warn if the user has made the 'size' argument to strlcpy or strlcat 2887// be the size of the source, instead of the destination. 2888void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2889 IdentifierInfo *FnName) { 2890 2891 // Don't crash if the user has the wrong number of arguments 2892 if (Call->getNumArgs() != 3) 2893 return; 2894 2895 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2896 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2897 const Expr *CompareWithSrc = NULL; 2898 2899 // Look for 'strlcpy(dst, x, sizeof(x))' 2900 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2901 CompareWithSrc = Ex; 2902 else { 2903 // Look for 'strlcpy(dst, x, strlen(x))' 2904 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2905 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2906 && SizeCall->getNumArgs() == 1) 2907 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2908 } 2909 } 2910 2911 if (!CompareWithSrc) 2912 return; 2913 2914 // Determine if the argument to sizeof/strlen is equal to the source 2915 // argument. In principle there's all kinds of things you could do 2916 // here, for instance creating an == expression and evaluating it with 2917 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2918 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2919 if (!SrcArgDRE) 2920 return; 2921 2922 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2923 if (!CompareWithSrcDRE || 2924 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2925 return; 2926 2927 const Expr *OriginalSizeArg = Call->getArg(2); 2928 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2929 << OriginalSizeArg->getSourceRange() << FnName; 2930 2931 // Output a FIXIT hint if the destination is an array (rather than a 2932 // pointer to an array). This could be enhanced to handle some 2933 // pointers if we know the actual size, like if DstArg is 'array+2' 2934 // we could say 'sizeof(array)-2'. 2935 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2936 QualType DstArgTy = DstArg->getType(); 2937 2938 // Only handle constant-sized or VLAs, but not flexible members. 2939 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2940 // Only issue the FIXIT for arrays of size > 1. 2941 if (CAT->getSize().getSExtValue() <= 1) 2942 return; 2943 } else if (!DstArgTy->isVariableArrayType()) { 2944 return; 2945 } 2946 2947 SmallString<128> sizeString; 2948 llvm::raw_svector_ostream OS(sizeString); 2949 OS << "sizeof("; 2950 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2951 OS << ")"; 2952 2953 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2954 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2955 OS.str()); 2956} 2957 2958/// Check if two expressions refer to the same declaration. 2959static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 2960 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 2961 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 2962 return D1->getDecl() == D2->getDecl(); 2963 return false; 2964} 2965 2966static const Expr *getStrlenExprArg(const Expr *E) { 2967 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 2968 const FunctionDecl *FD = CE->getDirectCallee(); 2969 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 2970 return 0; 2971 return CE->getArg(0)->IgnoreParenCasts(); 2972 } 2973 return 0; 2974} 2975 2976// Warn on anti-patterns as the 'size' argument to strncat. 2977// The correct size argument should look like following: 2978// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 2979void Sema::CheckStrncatArguments(const CallExpr *CE, 2980 IdentifierInfo *FnName) { 2981 // Don't crash if the user has the wrong number of arguments. 2982 if (CE->getNumArgs() < 3) 2983 return; 2984 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 2985 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 2986 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 2987 2988 // Identify common expressions, which are wrongly used as the size argument 2989 // to strncat and may lead to buffer overflows. 2990 unsigned PatternType = 0; 2991 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 2992 // - sizeof(dst) 2993 if (referToTheSameDecl(SizeOfArg, DstArg)) 2994 PatternType = 1; 2995 // - sizeof(src) 2996 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 2997 PatternType = 2; 2998 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 2999 if (BE->getOpcode() == BO_Sub) { 3000 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3001 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3002 // - sizeof(dst) - strlen(dst) 3003 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3004 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3005 PatternType = 1; 3006 // - sizeof(src) - (anything) 3007 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3008 PatternType = 2; 3009 } 3010 } 3011 3012 if (PatternType == 0) 3013 return; 3014 3015 // Generate the diagnostic. 3016 SourceLocation SL = LenArg->getLocStart(); 3017 SourceRange SR = LenArg->getSourceRange(); 3018 SourceManager &SM = PP.getSourceManager(); 3019 3020 // If the function is defined as a builtin macro, do not show macro expansion. 3021 if (SM.isMacroArgExpansion(SL)) { 3022 SL = SM.getSpellingLoc(SL); 3023 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3024 SM.getSpellingLoc(SR.getEnd())); 3025 } 3026 3027 if (PatternType == 1) 3028 Diag(SL, diag::warn_strncat_large_size) << SR; 3029 else 3030 Diag(SL, diag::warn_strncat_src_size) << SR; 3031 3032 // Output a FIXIT hint if the destination is an array (rather than a 3033 // pointer to an array). This could be enhanced to handle some 3034 // pointers if we know the actual size, like if DstArg is 'array+2' 3035 // we could say 'sizeof(array)-2'. 3036 QualType DstArgTy = DstArg->getType(); 3037 3038 // Only handle constant-sized or VLAs, but not flexible members. 3039 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 3040 // Only issue the FIXIT for arrays of size > 1. 3041 if (CAT->getSize().getSExtValue() <= 1) 3042 return; 3043 } else if (!DstArgTy->isVariableArrayType()) { 3044 return; 3045 } 3046 3047 SmallString<128> sizeString; 3048 llvm::raw_svector_ostream OS(sizeString); 3049 OS << "sizeof("; 3050 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3051 OS << ") - "; 3052 OS << "strlen("; 3053 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 3054 OS << ") - 1"; 3055 3056 Diag(SL, diag::note_strncat_wrong_size) 3057 << FixItHint::CreateReplacement(SR, OS.str()); 3058} 3059 3060//===--- CHECK: Return Address of Stack Variable --------------------------===// 3061 3062static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3063 Decl *ParentDecl); 3064static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3065 Decl *ParentDecl); 3066 3067/// CheckReturnStackAddr - Check if a return statement returns the address 3068/// of a stack variable. 3069void 3070Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3071 SourceLocation ReturnLoc) { 3072 3073 Expr *stackE = 0; 3074 SmallVector<DeclRefExpr *, 8> refVars; 3075 3076 // Perform checking for returned stack addresses, local blocks, 3077 // label addresses or references to temporaries. 3078 if (lhsType->isPointerType() || 3079 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3080 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3081 } else if (lhsType->isReferenceType()) { 3082 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3083 } 3084 3085 if (stackE == 0) 3086 return; // Nothing suspicious was found. 3087 3088 SourceLocation diagLoc; 3089 SourceRange diagRange; 3090 if (refVars.empty()) { 3091 diagLoc = stackE->getLocStart(); 3092 diagRange = stackE->getSourceRange(); 3093 } else { 3094 // We followed through a reference variable. 'stackE' contains the 3095 // problematic expression but we will warn at the return statement pointing 3096 // at the reference variable. We will later display the "trail" of 3097 // reference variables using notes. 3098 diagLoc = refVars[0]->getLocStart(); 3099 diagRange = refVars[0]->getSourceRange(); 3100 } 3101 3102 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3103 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3104 : diag::warn_ret_stack_addr) 3105 << DR->getDecl()->getDeclName() << diagRange; 3106 } else if (isa<BlockExpr>(stackE)) { // local block. 3107 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3108 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3109 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3110 } else { // local temporary. 3111 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3112 : diag::warn_ret_local_temp_addr) 3113 << diagRange; 3114 } 3115 3116 // Display the "trail" of reference variables that we followed until we 3117 // found the problematic expression using notes. 3118 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3119 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3120 // If this var binds to another reference var, show the range of the next 3121 // var, otherwise the var binds to the problematic expression, in which case 3122 // show the range of the expression. 3123 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3124 : stackE->getSourceRange(); 3125 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3126 << VD->getDeclName() << range; 3127 } 3128} 3129 3130/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3131/// check if the expression in a return statement evaluates to an address 3132/// to a location on the stack, a local block, an address of a label, or a 3133/// reference to local temporary. The recursion is used to traverse the 3134/// AST of the return expression, with recursion backtracking when we 3135/// encounter a subexpression that (1) clearly does not lead to one of the 3136/// above problematic expressions (2) is something we cannot determine leads to 3137/// a problematic expression based on such local checking. 3138/// 3139/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3140/// the expression that they point to. Such variables are added to the 3141/// 'refVars' vector so that we know what the reference variable "trail" was. 3142/// 3143/// EvalAddr processes expressions that are pointers that are used as 3144/// references (and not L-values). EvalVal handles all other values. 3145/// At the base case of the recursion is a check for the above problematic 3146/// expressions. 3147/// 3148/// This implementation handles: 3149/// 3150/// * pointer-to-pointer casts 3151/// * implicit conversions from array references to pointers 3152/// * taking the address of fields 3153/// * arbitrary interplay between "&" and "*" operators 3154/// * pointer arithmetic from an address of a stack variable 3155/// * taking the address of an array element where the array is on the stack 3156static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3157 Decl *ParentDecl) { 3158 if (E->isTypeDependent()) 3159 return NULL; 3160 3161 // We should only be called for evaluating pointer expressions. 3162 assert((E->getType()->isAnyPointerType() || 3163 E->getType()->isBlockPointerType() || 3164 E->getType()->isObjCQualifiedIdType()) && 3165 "EvalAddr only works on pointers"); 3166 3167 E = E->IgnoreParens(); 3168 3169 // Our "symbolic interpreter" is just a dispatch off the currently 3170 // viewed AST node. We then recursively traverse the AST by calling 3171 // EvalAddr and EvalVal appropriately. 3172 switch (E->getStmtClass()) { 3173 case Stmt::DeclRefExprClass: { 3174 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3175 3176 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 3177 // If this is a reference variable, follow through to the expression that 3178 // it points to. 3179 if (V->hasLocalStorage() && 3180 V->getType()->isReferenceType() && V->hasInit()) { 3181 // Add the reference variable to the "trail". 3182 refVars.push_back(DR); 3183 return EvalAddr(V->getInit(), refVars, ParentDecl); 3184 } 3185 3186 return NULL; 3187 } 3188 3189 case Stmt::UnaryOperatorClass: { 3190 // The only unary operator that make sense to handle here 3191 // is AddrOf. All others don't make sense as pointers. 3192 UnaryOperator *U = cast<UnaryOperator>(E); 3193 3194 if (U->getOpcode() == UO_AddrOf) 3195 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 3196 else 3197 return NULL; 3198 } 3199 3200 case Stmt::BinaryOperatorClass: { 3201 // Handle pointer arithmetic. All other binary operators are not valid 3202 // in this context. 3203 BinaryOperator *B = cast<BinaryOperator>(E); 3204 BinaryOperatorKind op = B->getOpcode(); 3205 3206 if (op != BO_Add && op != BO_Sub) 3207 return NULL; 3208 3209 Expr *Base = B->getLHS(); 3210 3211 // Determine which argument is the real pointer base. It could be 3212 // the RHS argument instead of the LHS. 3213 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 3214 3215 assert (Base->getType()->isPointerType()); 3216 return EvalAddr(Base, refVars, ParentDecl); 3217 } 3218 3219 // For conditional operators we need to see if either the LHS or RHS are 3220 // valid DeclRefExpr*s. If one of them is valid, we return it. 3221 case Stmt::ConditionalOperatorClass: { 3222 ConditionalOperator *C = cast<ConditionalOperator>(E); 3223 3224 // Handle the GNU extension for missing LHS. 3225 if (Expr *lhsExpr = C->getLHS()) { 3226 // In C++, we can have a throw-expression, which has 'void' type. 3227 if (!lhsExpr->getType()->isVoidType()) 3228 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 3229 return LHS; 3230 } 3231 3232 // In C++, we can have a throw-expression, which has 'void' type. 3233 if (C->getRHS()->getType()->isVoidType()) 3234 return NULL; 3235 3236 return EvalAddr(C->getRHS(), refVars, ParentDecl); 3237 } 3238 3239 case Stmt::BlockExprClass: 3240 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 3241 return E; // local block. 3242 return NULL; 3243 3244 case Stmt::AddrLabelExprClass: 3245 return E; // address of label. 3246 3247 case Stmt::ExprWithCleanupsClass: 3248 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 3249 ParentDecl); 3250 3251 // For casts, we need to handle conversions from arrays to 3252 // pointer values, and pointer-to-pointer conversions. 3253 case Stmt::ImplicitCastExprClass: 3254 case Stmt::CStyleCastExprClass: 3255 case Stmt::CXXFunctionalCastExprClass: 3256 case Stmt::ObjCBridgedCastExprClass: 3257 case Stmt::CXXStaticCastExprClass: 3258 case Stmt::CXXDynamicCastExprClass: 3259 case Stmt::CXXConstCastExprClass: 3260 case Stmt::CXXReinterpretCastExprClass: { 3261 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 3262 switch (cast<CastExpr>(E)->getCastKind()) { 3263 case CK_BitCast: 3264 case CK_LValueToRValue: 3265 case CK_NoOp: 3266 case CK_BaseToDerived: 3267 case CK_DerivedToBase: 3268 case CK_UncheckedDerivedToBase: 3269 case CK_Dynamic: 3270 case CK_CPointerToObjCPointerCast: 3271 case CK_BlockPointerToObjCPointerCast: 3272 case CK_AnyPointerToBlockPointerCast: 3273 return EvalAddr(SubExpr, refVars, ParentDecl); 3274 3275 case CK_ArrayToPointerDecay: 3276 return EvalVal(SubExpr, refVars, ParentDecl); 3277 3278 default: 3279 return 0; 3280 } 3281 } 3282 3283 case Stmt::MaterializeTemporaryExprClass: 3284 if (Expr *Result = EvalAddr( 3285 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3286 refVars, ParentDecl)) 3287 return Result; 3288 3289 return E; 3290 3291 // Everything else: we simply don't reason about them. 3292 default: 3293 return NULL; 3294 } 3295} 3296 3297 3298/// EvalVal - This function is complements EvalAddr in the mutual recursion. 3299/// See the comments for EvalAddr for more details. 3300static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3301 Decl *ParentDecl) { 3302do { 3303 // We should only be called for evaluating non-pointer expressions, or 3304 // expressions with a pointer type that are not used as references but instead 3305 // are l-values (e.g., DeclRefExpr with a pointer type). 3306 3307 // Our "symbolic interpreter" is just a dispatch off the currently 3308 // viewed AST node. We then recursively traverse the AST by calling 3309 // EvalAddr and EvalVal appropriately. 3310 3311 E = E->IgnoreParens(); 3312 switch (E->getStmtClass()) { 3313 case Stmt::ImplicitCastExprClass: { 3314 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 3315 if (IE->getValueKind() == VK_LValue) { 3316 E = IE->getSubExpr(); 3317 continue; 3318 } 3319 return NULL; 3320 } 3321 3322 case Stmt::ExprWithCleanupsClass: 3323 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 3324 3325 case Stmt::DeclRefExprClass: { 3326 // When we hit a DeclRefExpr we are looking at code that refers to a 3327 // variable's name. If it's not a reference variable we check if it has 3328 // local storage within the function, and if so, return the expression. 3329 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3330 3331 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 3332 // Check if it refers to itself, e.g. "int& i = i;". 3333 if (V == ParentDecl) 3334 return DR; 3335 3336 if (V->hasLocalStorage()) { 3337 if (!V->getType()->isReferenceType()) 3338 return DR; 3339 3340 // Reference variable, follow through to the expression that 3341 // it points to. 3342 if (V->hasInit()) { 3343 // Add the reference variable to the "trail". 3344 refVars.push_back(DR); 3345 return EvalVal(V->getInit(), refVars, V); 3346 } 3347 } 3348 } 3349 3350 return NULL; 3351 } 3352 3353 case Stmt::UnaryOperatorClass: { 3354 // The only unary operator that make sense to handle here 3355 // is Deref. All others don't resolve to a "name." This includes 3356 // handling all sorts of rvalues passed to a unary operator. 3357 UnaryOperator *U = cast<UnaryOperator>(E); 3358 3359 if (U->getOpcode() == UO_Deref) 3360 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 3361 3362 return NULL; 3363 } 3364 3365 case Stmt::ArraySubscriptExprClass: { 3366 // Array subscripts are potential references to data on the stack. We 3367 // retrieve the DeclRefExpr* for the array variable if it indeed 3368 // has local storage. 3369 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 3370 } 3371 3372 case Stmt::ConditionalOperatorClass: { 3373 // For conditional operators we need to see if either the LHS or RHS are 3374 // non-NULL Expr's. If one is non-NULL, we return it. 3375 ConditionalOperator *C = cast<ConditionalOperator>(E); 3376 3377 // Handle the GNU extension for missing LHS. 3378 if (Expr *lhsExpr = C->getLHS()) 3379 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 3380 return LHS; 3381 3382 return EvalVal(C->getRHS(), refVars, ParentDecl); 3383 } 3384 3385 // Accesses to members are potential references to data on the stack. 3386 case Stmt::MemberExprClass: { 3387 MemberExpr *M = cast<MemberExpr>(E); 3388 3389 // Check for indirect access. We only want direct field accesses. 3390 if (M->isArrow()) 3391 return NULL; 3392 3393 // Check whether the member type is itself a reference, in which case 3394 // we're not going to refer to the member, but to what the member refers to. 3395 if (M->getMemberDecl()->getType()->isReferenceType()) 3396 return NULL; 3397 3398 return EvalVal(M->getBase(), refVars, ParentDecl); 3399 } 3400 3401 case Stmt::MaterializeTemporaryExprClass: 3402 if (Expr *Result = EvalVal( 3403 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3404 refVars, ParentDecl)) 3405 return Result; 3406 3407 return E; 3408 3409 default: 3410 // Check that we don't return or take the address of a reference to a 3411 // temporary. This is only useful in C++. 3412 if (!E->isTypeDependent() && E->isRValue()) 3413 return E; 3414 3415 // Everything else: we simply don't reason about them. 3416 return NULL; 3417 } 3418} while (true); 3419} 3420 3421//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3422 3423/// Check for comparisons of floating point operands using != and ==. 3424/// Issue a warning if these are no self-comparisons, as they are not likely 3425/// to do what the programmer intended. 3426void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3427 bool EmitWarning = true; 3428 3429 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3430 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3431 3432 // Special case: check for x == x (which is OK). 3433 // Do not emit warnings for such cases. 3434 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3435 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3436 if (DRL->getDecl() == DRR->getDecl()) 3437 EmitWarning = false; 3438 3439 3440 // Special case: check for comparisons against literals that can be exactly 3441 // represented by APFloat. In such cases, do not emit a warning. This 3442 // is a heuristic: often comparison against such literals are used to 3443 // detect if a value in a variable has not changed. This clearly can 3444 // lead to false negatives. 3445 if (EmitWarning) { 3446 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3447 if (FLL->isExact()) 3448 EmitWarning = false; 3449 } else 3450 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3451 if (FLR->isExact()) 3452 EmitWarning = false; 3453 } 3454 } 3455 3456 // Check for comparisons with builtin types. 3457 if (EmitWarning) 3458 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3459 if (CL->isBuiltinCall()) 3460 EmitWarning = false; 3461 3462 if (EmitWarning) 3463 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3464 if (CR->isBuiltinCall()) 3465 EmitWarning = false; 3466 3467 // Emit the diagnostic. 3468 if (EmitWarning) 3469 Diag(Loc, diag::warn_floatingpoint_eq) 3470 << LHS->getSourceRange() << RHS->getSourceRange(); 3471} 3472 3473//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3474//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3475 3476namespace { 3477 3478/// Structure recording the 'active' range of an integer-valued 3479/// expression. 3480struct IntRange { 3481 /// The number of bits active in the int. 3482 unsigned Width; 3483 3484 /// True if the int is known not to have negative values. 3485 bool NonNegative; 3486 3487 IntRange(unsigned Width, bool NonNegative) 3488 : Width(Width), NonNegative(NonNegative) 3489 {} 3490 3491 /// Returns the range of the bool type. 3492 static IntRange forBoolType() { 3493 return IntRange(1, true); 3494 } 3495 3496 /// Returns the range of an opaque value of the given integral type. 3497 static IntRange forValueOfType(ASTContext &C, QualType T) { 3498 return forValueOfCanonicalType(C, 3499 T->getCanonicalTypeInternal().getTypePtr()); 3500 } 3501 3502 /// Returns the range of an opaque value of a canonical integral type. 3503 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3504 assert(T->isCanonicalUnqualified()); 3505 3506 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3507 T = VT->getElementType().getTypePtr(); 3508 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3509 T = CT->getElementType().getTypePtr(); 3510 3511 // For enum types, use the known bit width of the enumerators. 3512 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3513 EnumDecl *Enum = ET->getDecl(); 3514 if (!Enum->isCompleteDefinition()) 3515 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3516 3517 unsigned NumPositive = Enum->getNumPositiveBits(); 3518 unsigned NumNegative = Enum->getNumNegativeBits(); 3519 3520 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3521 } 3522 3523 const BuiltinType *BT = cast<BuiltinType>(T); 3524 assert(BT->isInteger()); 3525 3526 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3527 } 3528 3529 /// Returns the "target" range of a canonical integral type, i.e. 3530 /// the range of values expressible in the type. 3531 /// 3532 /// This matches forValueOfCanonicalType except that enums have the 3533 /// full range of their type, not the range of their enumerators. 3534 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3535 assert(T->isCanonicalUnqualified()); 3536 3537 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3538 T = VT->getElementType().getTypePtr(); 3539 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3540 T = CT->getElementType().getTypePtr(); 3541 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3542 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3543 3544 const BuiltinType *BT = cast<BuiltinType>(T); 3545 assert(BT->isInteger()); 3546 3547 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3548 } 3549 3550 /// Returns the supremum of two ranges: i.e. their conservative merge. 3551 static IntRange join(IntRange L, IntRange R) { 3552 return IntRange(std::max(L.Width, R.Width), 3553 L.NonNegative && R.NonNegative); 3554 } 3555 3556 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3557 static IntRange meet(IntRange L, IntRange R) { 3558 return IntRange(std::min(L.Width, R.Width), 3559 L.NonNegative || R.NonNegative); 3560 } 3561}; 3562 3563static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 3564 unsigned MaxWidth) { 3565 if (value.isSigned() && value.isNegative()) 3566 return IntRange(value.getMinSignedBits(), false); 3567 3568 if (value.getBitWidth() > MaxWidth) 3569 value = value.trunc(MaxWidth); 3570 3571 // isNonNegative() just checks the sign bit without considering 3572 // signedness. 3573 return IntRange(value.getActiveBits(), true); 3574} 3575 3576static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3577 unsigned MaxWidth) { 3578 if (result.isInt()) 3579 return GetValueRange(C, result.getInt(), MaxWidth); 3580 3581 if (result.isVector()) { 3582 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3583 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3584 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3585 R = IntRange::join(R, El); 3586 } 3587 return R; 3588 } 3589 3590 if (result.isComplexInt()) { 3591 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3592 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3593 return IntRange::join(R, I); 3594 } 3595 3596 // This can happen with lossless casts to intptr_t of "based" lvalues. 3597 // Assume it might use arbitrary bits. 3598 // FIXME: The only reason we need to pass the type in here is to get 3599 // the sign right on this one case. It would be nice if APValue 3600 // preserved this. 3601 assert(result.isLValue() || result.isAddrLabelDiff()); 3602 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3603} 3604 3605/// Pseudo-evaluate the given integer expression, estimating the 3606/// range of values it might take. 3607/// 3608/// \param MaxWidth - the width to which the value will be truncated 3609static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3610 E = E->IgnoreParens(); 3611 3612 // Try a full evaluation first. 3613 Expr::EvalResult result; 3614 if (E->EvaluateAsRValue(result, C)) 3615 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3616 3617 // I think we only want to look through implicit casts here; if the 3618 // user has an explicit widening cast, we should treat the value as 3619 // being of the new, wider type. 3620 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3621 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3622 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3623 3624 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3625 3626 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3627 3628 // Assume that non-integer casts can span the full range of the type. 3629 if (!isIntegerCast) 3630 return OutputTypeRange; 3631 3632 IntRange SubRange 3633 = GetExprRange(C, CE->getSubExpr(), 3634 std::min(MaxWidth, OutputTypeRange.Width)); 3635 3636 // Bail out if the subexpr's range is as wide as the cast type. 3637 if (SubRange.Width >= OutputTypeRange.Width) 3638 return OutputTypeRange; 3639 3640 // Otherwise, we take the smaller width, and we're non-negative if 3641 // either the output type or the subexpr is. 3642 return IntRange(SubRange.Width, 3643 SubRange.NonNegative || OutputTypeRange.NonNegative); 3644 } 3645 3646 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3647 // If we can fold the condition, just take that operand. 3648 bool CondResult; 3649 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3650 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3651 : CO->getFalseExpr(), 3652 MaxWidth); 3653 3654 // Otherwise, conservatively merge. 3655 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3656 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3657 return IntRange::join(L, R); 3658 } 3659 3660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3661 switch (BO->getOpcode()) { 3662 3663 // Boolean-valued operations are single-bit and positive. 3664 case BO_LAnd: 3665 case BO_LOr: 3666 case BO_LT: 3667 case BO_GT: 3668 case BO_LE: 3669 case BO_GE: 3670 case BO_EQ: 3671 case BO_NE: 3672 return IntRange::forBoolType(); 3673 3674 // The type of the assignments is the type of the LHS, so the RHS 3675 // is not necessarily the same type. 3676 case BO_MulAssign: 3677 case BO_DivAssign: 3678 case BO_RemAssign: 3679 case BO_AddAssign: 3680 case BO_SubAssign: 3681 case BO_XorAssign: 3682 case BO_OrAssign: 3683 // TODO: bitfields? 3684 return IntRange::forValueOfType(C, E->getType()); 3685 3686 // Simple assignments just pass through the RHS, which will have 3687 // been coerced to the LHS type. 3688 case BO_Assign: 3689 // TODO: bitfields? 3690 return GetExprRange(C, BO->getRHS(), MaxWidth); 3691 3692 // Operations with opaque sources are black-listed. 3693 case BO_PtrMemD: 3694 case BO_PtrMemI: 3695 return IntRange::forValueOfType(C, E->getType()); 3696 3697 // Bitwise-and uses the *infinum* of the two source ranges. 3698 case BO_And: 3699 case BO_AndAssign: 3700 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3701 GetExprRange(C, BO->getRHS(), MaxWidth)); 3702 3703 // Left shift gets black-listed based on a judgement call. 3704 case BO_Shl: 3705 // ...except that we want to treat '1 << (blah)' as logically 3706 // positive. It's an important idiom. 3707 if (IntegerLiteral *I 3708 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3709 if (I->getValue() == 1) { 3710 IntRange R = IntRange::forValueOfType(C, E->getType()); 3711 return IntRange(R.Width, /*NonNegative*/ true); 3712 } 3713 } 3714 // fallthrough 3715 3716 case BO_ShlAssign: 3717 return IntRange::forValueOfType(C, E->getType()); 3718 3719 // Right shift by a constant can narrow its left argument. 3720 case BO_Shr: 3721 case BO_ShrAssign: { 3722 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3723 3724 // If the shift amount is a positive constant, drop the width by 3725 // that much. 3726 llvm::APSInt shift; 3727 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3728 shift.isNonNegative()) { 3729 unsigned zext = shift.getZExtValue(); 3730 if (zext >= L.Width) 3731 L.Width = (L.NonNegative ? 0 : 1); 3732 else 3733 L.Width -= zext; 3734 } 3735 3736 return L; 3737 } 3738 3739 // Comma acts as its right operand. 3740 case BO_Comma: 3741 return GetExprRange(C, BO->getRHS(), MaxWidth); 3742 3743 // Black-list pointer subtractions. 3744 case BO_Sub: 3745 if (BO->getLHS()->getType()->isPointerType()) 3746 return IntRange::forValueOfType(C, E->getType()); 3747 break; 3748 3749 // The width of a division result is mostly determined by the size 3750 // of the LHS. 3751 case BO_Div: { 3752 // Don't 'pre-truncate' the operands. 3753 unsigned opWidth = C.getIntWidth(E->getType()); 3754 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3755 3756 // If the divisor is constant, use that. 3757 llvm::APSInt divisor; 3758 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3759 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3760 if (log2 >= L.Width) 3761 L.Width = (L.NonNegative ? 0 : 1); 3762 else 3763 L.Width = std::min(L.Width - log2, MaxWidth); 3764 return L; 3765 } 3766 3767 // Otherwise, just use the LHS's width. 3768 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3769 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3770 } 3771 3772 // The result of a remainder can't be larger than the result of 3773 // either side. 3774 case BO_Rem: { 3775 // Don't 'pre-truncate' the operands. 3776 unsigned opWidth = C.getIntWidth(E->getType()); 3777 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3778 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3779 3780 IntRange meet = IntRange::meet(L, R); 3781 meet.Width = std::min(meet.Width, MaxWidth); 3782 return meet; 3783 } 3784 3785 // The default behavior is okay for these. 3786 case BO_Mul: 3787 case BO_Add: 3788 case BO_Xor: 3789 case BO_Or: 3790 break; 3791 } 3792 3793 // The default case is to treat the operation as if it were closed 3794 // on the narrowest type that encompasses both operands. 3795 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3796 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3797 return IntRange::join(L, R); 3798 } 3799 3800 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3801 switch (UO->getOpcode()) { 3802 // Boolean-valued operations are white-listed. 3803 case UO_LNot: 3804 return IntRange::forBoolType(); 3805 3806 // Operations with opaque sources are black-listed. 3807 case UO_Deref: 3808 case UO_AddrOf: // should be impossible 3809 return IntRange::forValueOfType(C, E->getType()); 3810 3811 default: 3812 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3813 } 3814 } 3815 3816 if (dyn_cast<OffsetOfExpr>(E)) { 3817 IntRange::forValueOfType(C, E->getType()); 3818 } 3819 3820 if (FieldDecl *BitField = E->getBitField()) 3821 return IntRange(BitField->getBitWidthValue(C), 3822 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3823 3824 return IntRange::forValueOfType(C, E->getType()); 3825} 3826 3827static IntRange GetExprRange(ASTContext &C, Expr *E) { 3828 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3829} 3830 3831/// Checks whether the given value, which currently has the given 3832/// source semantics, has the same value when coerced through the 3833/// target semantics. 3834static bool IsSameFloatAfterCast(const llvm::APFloat &value, 3835 const llvm::fltSemantics &Src, 3836 const llvm::fltSemantics &Tgt) { 3837 llvm::APFloat truncated = value; 3838 3839 bool ignored; 3840 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3841 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3842 3843 return truncated.bitwiseIsEqual(value); 3844} 3845 3846/// Checks whether the given value, which currently has the given 3847/// source semantics, has the same value when coerced through the 3848/// target semantics. 3849/// 3850/// The value might be a vector of floats (or a complex number). 3851static bool IsSameFloatAfterCast(const APValue &value, 3852 const llvm::fltSemantics &Src, 3853 const llvm::fltSemantics &Tgt) { 3854 if (value.isFloat()) 3855 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3856 3857 if (value.isVector()) { 3858 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3859 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3860 return false; 3861 return true; 3862 } 3863 3864 assert(value.isComplexFloat()); 3865 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3866 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3867} 3868 3869static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3870 3871static bool IsZero(Sema &S, Expr *E) { 3872 // Suppress cases where we are comparing against an enum constant. 3873 if (const DeclRefExpr *DR = 3874 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3875 if (isa<EnumConstantDecl>(DR->getDecl())) 3876 return false; 3877 3878 // Suppress cases where the '0' value is expanded from a macro. 3879 if (E->getLocStart().isMacroID()) 3880 return false; 3881 3882 llvm::APSInt Value; 3883 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3884} 3885 3886static bool HasEnumType(Expr *E) { 3887 // Strip off implicit integral promotions. 3888 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3889 if (ICE->getCastKind() != CK_IntegralCast && 3890 ICE->getCastKind() != CK_NoOp) 3891 break; 3892 E = ICE->getSubExpr(); 3893 } 3894 3895 return E->getType()->isEnumeralType(); 3896} 3897 3898static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3899 BinaryOperatorKind op = E->getOpcode(); 3900 if (E->isValueDependent()) 3901 return; 3902 3903 if (op == BO_LT && IsZero(S, E->getRHS())) { 3904 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3905 << "< 0" << "false" << HasEnumType(E->getLHS()) 3906 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3907 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3908 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3909 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3910 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3911 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3912 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3913 << "0 >" << "false" << HasEnumType(E->getRHS()) 3914 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3915 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3916 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3917 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3918 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3919 } 3920} 3921 3922/// Analyze the operands of the given comparison. Implements the 3923/// fallback case from AnalyzeComparison. 3924static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3925 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3926 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3927} 3928 3929/// \brief Implements -Wsign-compare. 3930/// 3931/// \param E the binary operator to check for warnings 3932static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3933 // The type the comparison is being performed in. 3934 QualType T = E->getLHS()->getType(); 3935 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3936 && "comparison with mismatched types"); 3937 3938 // We don't do anything special if this isn't an unsigned integral 3939 // comparison: we're only interested in integral comparisons, and 3940 // signed comparisons only happen in cases we don't care to warn about. 3941 // 3942 // We also don't care about value-dependent expressions or expressions 3943 // whose result is a constant. 3944 if (!T->hasUnsignedIntegerRepresentation() 3945 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3946 return AnalyzeImpConvsInComparison(S, E); 3947 3948 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3949 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3950 3951 // Check to see if one of the (unmodified) operands is of different 3952 // signedness. 3953 Expr *signedOperand, *unsignedOperand; 3954 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3955 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3956 "unsigned comparison between two signed integer expressions?"); 3957 signedOperand = LHS; 3958 unsignedOperand = RHS; 3959 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3960 signedOperand = RHS; 3961 unsignedOperand = LHS; 3962 } else { 3963 CheckTrivialUnsignedComparison(S, E); 3964 return AnalyzeImpConvsInComparison(S, E); 3965 } 3966 3967 // Otherwise, calculate the effective range of the signed operand. 3968 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3969 3970 // Go ahead and analyze implicit conversions in the operands. Note 3971 // that we skip the implicit conversions on both sides. 3972 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3973 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3974 3975 // If the signed range is non-negative, -Wsign-compare won't fire, 3976 // but we should still check for comparisons which are always true 3977 // or false. 3978 if (signedRange.NonNegative) 3979 return CheckTrivialUnsignedComparison(S, E); 3980 3981 // For (in)equality comparisons, if the unsigned operand is a 3982 // constant which cannot collide with a overflowed signed operand, 3983 // then reinterpreting the signed operand as unsigned will not 3984 // change the result of the comparison. 3985 if (E->isEqualityOp()) { 3986 unsigned comparisonWidth = S.Context.getIntWidth(T); 3987 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3988 3989 // We should never be unable to prove that the unsigned operand is 3990 // non-negative. 3991 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3992 3993 if (unsignedRange.Width < comparisonWidth) 3994 return; 3995 } 3996 3997 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 3998 S.PDiag(diag::warn_mixed_sign_comparison) 3999 << LHS->getType() << RHS->getType() 4000 << LHS->getSourceRange() << RHS->getSourceRange()); 4001} 4002 4003/// Analyzes an attempt to assign the given value to a bitfield. 4004/// 4005/// Returns true if there was something fishy about the attempt. 4006static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 4007 SourceLocation InitLoc) { 4008 assert(Bitfield->isBitField()); 4009 if (Bitfield->isInvalidDecl()) 4010 return false; 4011 4012 // White-list bool bitfields. 4013 if (Bitfield->getType()->isBooleanType()) 4014 return false; 4015 4016 // Ignore value- or type-dependent expressions. 4017 if (Bitfield->getBitWidth()->isValueDependent() || 4018 Bitfield->getBitWidth()->isTypeDependent() || 4019 Init->isValueDependent() || 4020 Init->isTypeDependent()) 4021 return false; 4022 4023 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 4024 4025 llvm::APSInt Value; 4026 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 4027 return false; 4028 4029 unsigned OriginalWidth = Value.getBitWidth(); 4030 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 4031 4032 if (OriginalWidth <= FieldWidth) 4033 return false; 4034 4035 // Compute the value which the bitfield will contain. 4036 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 4037 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 4038 4039 // Check whether the stored value is equal to the original value. 4040 TruncatedValue = TruncatedValue.extend(OriginalWidth); 4041 if (Value == TruncatedValue) 4042 return false; 4043 4044 // Special-case bitfields of width 1: booleans are naturally 0/1, and 4045 // therefore don't strictly fit into a signed bitfield of width 1. 4046 if (FieldWidth == 1 && Value == 1) 4047 return false; 4048 4049 std::string PrettyValue = Value.toString(10); 4050 std::string PrettyTrunc = TruncatedValue.toString(10); 4051 4052 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 4053 << PrettyValue << PrettyTrunc << OriginalInit->getType() 4054 << Init->getSourceRange(); 4055 4056 return true; 4057} 4058 4059/// Analyze the given simple or compound assignment for warning-worthy 4060/// operations. 4061static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 4062 // Just recurse on the LHS. 4063 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4064 4065 // We want to recurse on the RHS as normal unless we're assigning to 4066 // a bitfield. 4067 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 4068 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 4069 E->getOperatorLoc())) { 4070 // Recurse, ignoring any implicit conversions on the RHS. 4071 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 4072 E->getOperatorLoc()); 4073 } 4074 } 4075 4076 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4077} 4078 4079/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4080static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 4081 SourceLocation CContext, unsigned diag, 4082 bool pruneControlFlow = false) { 4083 if (pruneControlFlow) { 4084 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4085 S.PDiag(diag) 4086 << SourceType << T << E->getSourceRange() 4087 << SourceRange(CContext)); 4088 return; 4089 } 4090 S.Diag(E->getExprLoc(), diag) 4091 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 4092} 4093 4094/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4095static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 4096 SourceLocation CContext, unsigned diag, 4097 bool pruneControlFlow = false) { 4098 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 4099} 4100 4101/// Diagnose an implicit cast from a literal expression. Does not warn when the 4102/// cast wouldn't lose information. 4103void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 4104 SourceLocation CContext) { 4105 // Try to convert the literal exactly to an integer. If we can, don't warn. 4106 bool isExact = false; 4107 const llvm::APFloat &Value = FL->getValue(); 4108 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 4109 T->hasUnsignedIntegerRepresentation()); 4110 if (Value.convertToInteger(IntegerValue, 4111 llvm::APFloat::rmTowardZero, &isExact) 4112 == llvm::APFloat::opOK && isExact) 4113 return; 4114 4115 SmallString<16> PrettySourceValue; 4116 Value.toString(PrettySourceValue); 4117 SmallString<16> PrettyTargetValue; 4118 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 4119 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 4120 else 4121 IntegerValue.toString(PrettyTargetValue); 4122 4123 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 4124 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 4125 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 4126} 4127 4128std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 4129 if (!Range.Width) return "0"; 4130 4131 llvm::APSInt ValueInRange = Value; 4132 ValueInRange.setIsSigned(!Range.NonNegative); 4133 ValueInRange = ValueInRange.trunc(Range.Width); 4134 return ValueInRange.toString(10); 4135} 4136 4137void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 4138 SourceLocation CC, bool *ICContext = 0) { 4139 if (E->isTypeDependent() || E->isValueDependent()) return; 4140 4141 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 4142 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 4143 if (Source == Target) return; 4144 if (Target->isDependentType()) return; 4145 4146 // If the conversion context location is invalid don't complain. We also 4147 // don't want to emit a warning if the issue occurs from the expansion of 4148 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 4149 // delay this check as long as possible. Once we detect we are in that 4150 // scenario, we just return. 4151 if (CC.isInvalid()) 4152 return; 4153 4154 // Diagnose implicit casts to bool. 4155 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 4156 if (isa<StringLiteral>(E)) 4157 // Warn on string literal to bool. Checks for string literals in logical 4158 // expressions, for instances, assert(0 && "error here"), is prevented 4159 // by a check in AnalyzeImplicitConversions(). 4160 return DiagnoseImpCast(S, E, T, CC, 4161 diag::warn_impcast_string_literal_to_bool); 4162 if (Source->isFunctionType()) { 4163 // Warn on function to bool. Checks free functions and static member 4164 // functions. Weakly imported functions are excluded from the check, 4165 // since it's common to test their value to check whether the linker 4166 // found a definition for them. 4167 ValueDecl *D = 0; 4168 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 4169 D = R->getDecl(); 4170 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 4171 D = M->getMemberDecl(); 4172 } 4173 4174 if (D && !D->isWeak()) { 4175 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 4176 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 4177 << F << E->getSourceRange() << SourceRange(CC); 4178 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 4179 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 4180 QualType ReturnType; 4181 UnresolvedSet<4> NonTemplateOverloads; 4182 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 4183 if (!ReturnType.isNull() 4184 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 4185 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 4186 << FixItHint::CreateInsertion( 4187 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 4188 return; 4189 } 4190 } 4191 } 4192 } 4193 4194 // Strip vector types. 4195 if (isa<VectorType>(Source)) { 4196 if (!isa<VectorType>(Target)) { 4197 if (S.SourceMgr.isInSystemMacro(CC)) 4198 return; 4199 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 4200 } 4201 4202 // If the vector cast is cast between two vectors of the same size, it is 4203 // a bitcast, not a conversion. 4204 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 4205 return; 4206 4207 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 4208 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 4209 } 4210 4211 // Strip complex types. 4212 if (isa<ComplexType>(Source)) { 4213 if (!isa<ComplexType>(Target)) { 4214 if (S.SourceMgr.isInSystemMacro(CC)) 4215 return; 4216 4217 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 4218 } 4219 4220 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 4221 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 4222 } 4223 4224 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 4225 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 4226 4227 // If the source is floating point... 4228 if (SourceBT && SourceBT->isFloatingPoint()) { 4229 // ...and the target is floating point... 4230 if (TargetBT && TargetBT->isFloatingPoint()) { 4231 // ...then warn if we're dropping FP rank. 4232 4233 // Builtin FP kinds are ordered by increasing FP rank. 4234 if (SourceBT->getKind() > TargetBT->getKind()) { 4235 // Don't warn about float constants that are precisely 4236 // representable in the target type. 4237 Expr::EvalResult result; 4238 if (E->EvaluateAsRValue(result, S.Context)) { 4239 // Value might be a float, a float vector, or a float complex. 4240 if (IsSameFloatAfterCast(result.Val, 4241 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 4242 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 4243 return; 4244 } 4245 4246 if (S.SourceMgr.isInSystemMacro(CC)) 4247 return; 4248 4249 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 4250 } 4251 return; 4252 } 4253 4254 // If the target is integral, always warn. 4255 if (TargetBT && TargetBT->isInteger()) { 4256 if (S.SourceMgr.isInSystemMacro(CC)) 4257 return; 4258 4259 Expr *InnerE = E->IgnoreParenImpCasts(); 4260 // We also want to warn on, e.g., "int i = -1.234" 4261 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 4262 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 4263 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 4264 4265 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 4266 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 4267 } else { 4268 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 4269 } 4270 } 4271 4272 return; 4273 } 4274 4275 if (!Source->isIntegerType() || !Target->isIntegerType()) 4276 return; 4277 4278 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 4279 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 4280 SourceLocation Loc = E->getSourceRange().getBegin(); 4281 if (Loc.isMacroID()) 4282 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 4283 if (!Loc.isMacroID() || CC.isMacroID()) 4284 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 4285 << T << clang::SourceRange(CC) 4286 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T)); 4287 return; 4288 } 4289 4290 // TODO: remove this early return once the false positives for constant->bool 4291 // in templates, macros, etc, are reduced or removed. 4292 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 4293 return; 4294 4295 IntRange SourceRange = GetExprRange(S.Context, E); 4296 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 4297 4298 if (SourceRange.Width > TargetRange.Width) { 4299 // If the source is a constant, use a default-on diagnostic. 4300 // TODO: this should happen for bitfield stores, too. 4301 llvm::APSInt Value(32); 4302 if (E->isIntegerConstantExpr(Value, S.Context)) { 4303 if (S.SourceMgr.isInSystemMacro(CC)) 4304 return; 4305 4306 std::string PrettySourceValue = Value.toString(10); 4307 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 4308 4309 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4310 S.PDiag(diag::warn_impcast_integer_precision_constant) 4311 << PrettySourceValue << PrettyTargetValue 4312 << E->getType() << T << E->getSourceRange() 4313 << clang::SourceRange(CC)); 4314 return; 4315 } 4316 4317 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 4318 if (S.SourceMgr.isInSystemMacro(CC)) 4319 return; 4320 4321 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 4322 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 4323 /* pruneControlFlow */ true); 4324 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 4325 } 4326 4327 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 4328 (!TargetRange.NonNegative && SourceRange.NonNegative && 4329 SourceRange.Width == TargetRange.Width)) { 4330 4331 if (S.SourceMgr.isInSystemMacro(CC)) 4332 return; 4333 4334 unsigned DiagID = diag::warn_impcast_integer_sign; 4335 4336 // Traditionally, gcc has warned about this under -Wsign-compare. 4337 // We also want to warn about it in -Wconversion. 4338 // So if -Wconversion is off, use a completely identical diagnostic 4339 // in the sign-compare group. 4340 // The conditional-checking code will 4341 if (ICContext) { 4342 DiagID = diag::warn_impcast_integer_sign_conditional; 4343 *ICContext = true; 4344 } 4345 4346 return DiagnoseImpCast(S, E, T, CC, DiagID); 4347 } 4348 4349 // Diagnose conversions between different enumeration types. 4350 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 4351 // type, to give us better diagnostics. 4352 QualType SourceType = E->getType(); 4353 if (!S.getLangOpts().CPlusPlus) { 4354 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4355 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4356 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 4357 SourceType = S.Context.getTypeDeclType(Enum); 4358 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 4359 } 4360 } 4361 4362 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 4363 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 4364 if ((SourceEnum->getDecl()->getIdentifier() || 4365 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 4366 (TargetEnum->getDecl()->getIdentifier() || 4367 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 4368 SourceEnum != TargetEnum) { 4369 if (S.SourceMgr.isInSystemMacro(CC)) 4370 return; 4371 4372 return DiagnoseImpCast(S, E, SourceType, T, CC, 4373 diag::warn_impcast_different_enum_types); 4374 } 4375 4376 return; 4377} 4378 4379void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4380 SourceLocation CC, QualType T); 4381 4382void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 4383 SourceLocation CC, bool &ICContext) { 4384 E = E->IgnoreParenImpCasts(); 4385 4386 if (isa<ConditionalOperator>(E)) 4387 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 4388 4389 AnalyzeImplicitConversions(S, E, CC); 4390 if (E->getType() != T) 4391 return CheckImplicitConversion(S, E, T, CC, &ICContext); 4392 return; 4393} 4394 4395void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4396 SourceLocation CC, QualType T) { 4397 AnalyzeImplicitConversions(S, E->getCond(), CC); 4398 4399 bool Suspicious = false; 4400 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 4401 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 4402 4403 // If -Wconversion would have warned about either of the candidates 4404 // for a signedness conversion to the context type... 4405 if (!Suspicious) return; 4406 4407 // ...but it's currently ignored... 4408 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4409 CC)) 4410 return; 4411 4412 // ...then check whether it would have warned about either of the 4413 // candidates for a signedness conversion to the condition type. 4414 if (E->getType() == T) return; 4415 4416 Suspicious = false; 4417 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4418 E->getType(), CC, &Suspicious); 4419 if (!Suspicious) 4420 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4421 E->getType(), CC, &Suspicious); 4422} 4423 4424/// AnalyzeImplicitConversions - Find and report any interesting 4425/// implicit conversions in the given expression. There are a couple 4426/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4427void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4428 QualType T = OrigE->getType(); 4429 Expr *E = OrigE->IgnoreParenImpCasts(); 4430 4431 if (E->isTypeDependent() || E->isValueDependent()) 4432 return; 4433 4434 // For conditional operators, we analyze the arguments as if they 4435 // were being fed directly into the output. 4436 if (isa<ConditionalOperator>(E)) { 4437 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4438 CheckConditionalOperator(S, CO, CC, T); 4439 return; 4440 } 4441 4442 // Go ahead and check any implicit conversions we might have skipped. 4443 // The non-canonical typecheck is just an optimization; 4444 // CheckImplicitConversion will filter out dead implicit conversions. 4445 if (E->getType() != T) 4446 CheckImplicitConversion(S, E, T, CC); 4447 4448 // Now continue drilling into this expression. 4449 4450 // Skip past explicit casts. 4451 if (isa<ExplicitCastExpr>(E)) { 4452 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4453 return AnalyzeImplicitConversions(S, E, CC); 4454 } 4455 4456 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4457 // Do a somewhat different check with comparison operators. 4458 if (BO->isComparisonOp()) 4459 return AnalyzeComparison(S, BO); 4460 4461 // And with simple assignments. 4462 if (BO->getOpcode() == BO_Assign) 4463 return AnalyzeAssignment(S, BO); 4464 } 4465 4466 // These break the otherwise-useful invariant below. Fortunately, 4467 // we don't really need to recurse into them, because any internal 4468 // expressions should have been analyzed already when they were 4469 // built into statements. 4470 if (isa<StmtExpr>(E)) return; 4471 4472 // Don't descend into unevaluated contexts. 4473 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4474 4475 // Now just recurse over the expression's children. 4476 CC = E->getExprLoc(); 4477 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4478 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4479 for (Stmt::child_range I = E->children(); I; ++I) { 4480 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 4481 if (!ChildExpr) 4482 continue; 4483 4484 if (IsLogicalOperator && 4485 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4486 // Ignore checking string literals that are in logical operators. 4487 continue; 4488 AnalyzeImplicitConversions(S, ChildExpr, CC); 4489 } 4490} 4491 4492} // end anonymous namespace 4493 4494/// Diagnoses "dangerous" implicit conversions within the given 4495/// expression (which is a full expression). Implements -Wconversion 4496/// and -Wsign-compare. 4497/// 4498/// \param CC the "context" location of the implicit conversion, i.e. 4499/// the most location of the syntactic entity requiring the implicit 4500/// conversion 4501void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4502 // Don't diagnose in unevaluated contexts. 4503 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4504 return; 4505 4506 // Don't diagnose for value- or type-dependent expressions. 4507 if (E->isTypeDependent() || E->isValueDependent()) 4508 return; 4509 4510 // Check for array bounds violations in cases where the check isn't triggered 4511 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4512 // ArraySubscriptExpr is on the RHS of a variable initialization. 4513 CheckArrayAccess(E); 4514 4515 // This is not the right CC for (e.g.) a variable initialization. 4516 AnalyzeImplicitConversions(*this, E, CC); 4517} 4518 4519void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4520 FieldDecl *BitField, 4521 Expr *Init) { 4522 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4523} 4524 4525/// CheckParmsForFunctionDef - Check that the parameters of the given 4526/// function are appropriate for the definition of a function. This 4527/// takes care of any checks that cannot be performed on the 4528/// declaration itself, e.g., that the types of each of the function 4529/// parameters are complete. 4530bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4531 bool CheckParameterNames) { 4532 bool HasInvalidParm = false; 4533 for (; P != PEnd; ++P) { 4534 ParmVarDecl *Param = *P; 4535 4536 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4537 // function declarator that is part of a function definition of 4538 // that function shall not have incomplete type. 4539 // 4540 // This is also C++ [dcl.fct]p6. 4541 if (!Param->isInvalidDecl() && 4542 RequireCompleteType(Param->getLocation(), Param->getType(), 4543 diag::err_typecheck_decl_incomplete_type)) { 4544 Param->setInvalidDecl(); 4545 HasInvalidParm = true; 4546 } 4547 4548 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4549 // declaration of each parameter shall include an identifier. 4550 if (CheckParameterNames && 4551 Param->getIdentifier() == 0 && 4552 !Param->isImplicit() && 4553 !getLangOpts().CPlusPlus) 4554 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4555 4556 // C99 6.7.5.3p12: 4557 // If the function declarator is not part of a definition of that 4558 // function, parameters may have incomplete type and may use the [*] 4559 // notation in their sequences of declarator specifiers to specify 4560 // variable length array types. 4561 QualType PType = Param->getOriginalType(); 4562 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4563 if (AT->getSizeModifier() == ArrayType::Star) { 4564 // FIXME: This diagnosic should point the the '[*]' if source-location 4565 // information is added for it. 4566 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4567 } 4568 } 4569 } 4570 4571 return HasInvalidParm; 4572} 4573 4574/// CheckCastAlign - Implements -Wcast-align, which warns when a 4575/// pointer cast increases the alignment requirements. 4576void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4577 // This is actually a lot of work to potentially be doing on every 4578 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4579 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4580 TRange.getBegin()) 4581 == DiagnosticsEngine::Ignored) 4582 return; 4583 4584 // Ignore dependent types. 4585 if (T->isDependentType() || Op->getType()->isDependentType()) 4586 return; 4587 4588 // Require that the destination be a pointer type. 4589 const PointerType *DestPtr = T->getAs<PointerType>(); 4590 if (!DestPtr) return; 4591 4592 // If the destination has alignment 1, we're done. 4593 QualType DestPointee = DestPtr->getPointeeType(); 4594 if (DestPointee->isIncompleteType()) return; 4595 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4596 if (DestAlign.isOne()) return; 4597 4598 // Require that the source be a pointer type. 4599 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4600 if (!SrcPtr) return; 4601 QualType SrcPointee = SrcPtr->getPointeeType(); 4602 4603 // Whitelist casts from cv void*. We already implicitly 4604 // whitelisted casts to cv void*, since they have alignment 1. 4605 // Also whitelist casts involving incomplete types, which implicitly 4606 // includes 'void'. 4607 if (SrcPointee->isIncompleteType()) return; 4608 4609 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4610 if (SrcAlign >= DestAlign) return; 4611 4612 Diag(TRange.getBegin(), diag::warn_cast_align) 4613 << Op->getType() << T 4614 << static_cast<unsigned>(SrcAlign.getQuantity()) 4615 << static_cast<unsigned>(DestAlign.getQuantity()) 4616 << TRange << Op->getSourceRange(); 4617} 4618 4619static const Type* getElementType(const Expr *BaseExpr) { 4620 const Type* EltType = BaseExpr->getType().getTypePtr(); 4621 if (EltType->isAnyPointerType()) 4622 return EltType->getPointeeType().getTypePtr(); 4623 else if (EltType->isArrayType()) 4624 return EltType->getBaseElementTypeUnsafe(); 4625 return EltType; 4626} 4627 4628/// \brief Check whether this array fits the idiom of a size-one tail padded 4629/// array member of a struct. 4630/// 4631/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4632/// commonly used to emulate flexible arrays in C89 code. 4633static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4634 const NamedDecl *ND) { 4635 if (Size != 1 || !ND) return false; 4636 4637 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4638 if (!FD) return false; 4639 4640 // Don't consider sizes resulting from macro expansions or template argument 4641 // substitution to form C89 tail-padded arrays. 4642 4643 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 4644 while (TInfo) { 4645 TypeLoc TL = TInfo->getTypeLoc(); 4646 // Look through typedefs. 4647 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL); 4648 if (TTL) { 4649 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl(); 4650 TInfo = TDL->getTypeSourceInfo(); 4651 continue; 4652 } 4653 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL); 4654 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 4655 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4656 return false; 4657 break; 4658 } 4659 4660 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4661 if (!RD) return false; 4662 if (RD->isUnion()) return false; 4663 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4664 if (!CRD->isStandardLayout()) return false; 4665 } 4666 4667 // See if this is the last field decl in the record. 4668 const Decl *D = FD; 4669 while ((D = D->getNextDeclInContext())) 4670 if (isa<FieldDecl>(D)) 4671 return false; 4672 return true; 4673} 4674 4675void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4676 const ArraySubscriptExpr *ASE, 4677 bool AllowOnePastEnd, bool IndexNegated) { 4678 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 4679 if (IndexExpr->isValueDependent()) 4680 return; 4681 4682 const Type *EffectiveType = getElementType(BaseExpr); 4683 BaseExpr = BaseExpr->IgnoreParenCasts(); 4684 const ConstantArrayType *ArrayTy = 4685 Context.getAsConstantArrayType(BaseExpr->getType()); 4686 if (!ArrayTy) 4687 return; 4688 4689 llvm::APSInt index; 4690 if (!IndexExpr->EvaluateAsInt(index, Context)) 4691 return; 4692 if (IndexNegated) 4693 index = -index; 4694 4695 const NamedDecl *ND = NULL; 4696 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4697 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4698 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4699 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4700 4701 if (index.isUnsigned() || !index.isNegative()) { 4702 llvm::APInt size = ArrayTy->getSize(); 4703 if (!size.isStrictlyPositive()) 4704 return; 4705 4706 const Type* BaseType = getElementType(BaseExpr); 4707 if (BaseType != EffectiveType) { 4708 // Make sure we're comparing apples to apples when comparing index to size 4709 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4710 uint64_t array_typesize = Context.getTypeSize(BaseType); 4711 // Handle ptrarith_typesize being zero, such as when casting to void* 4712 if (!ptrarith_typesize) ptrarith_typesize = 1; 4713 if (ptrarith_typesize != array_typesize) { 4714 // There's a cast to a different size type involved 4715 uint64_t ratio = array_typesize / ptrarith_typesize; 4716 // TODO: Be smarter about handling cases where array_typesize is not a 4717 // multiple of ptrarith_typesize 4718 if (ptrarith_typesize * ratio == array_typesize) 4719 size *= llvm::APInt(size.getBitWidth(), ratio); 4720 } 4721 } 4722 4723 if (size.getBitWidth() > index.getBitWidth()) 4724 index = index.zext(size.getBitWidth()); 4725 else if (size.getBitWidth() < index.getBitWidth()) 4726 size = size.zext(index.getBitWidth()); 4727 4728 // For array subscripting the index must be less than size, but for pointer 4729 // arithmetic also allow the index (offset) to be equal to size since 4730 // computing the next address after the end of the array is legal and 4731 // commonly done e.g. in C++ iterators and range-based for loops. 4732 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 4733 return; 4734 4735 // Also don't warn for arrays of size 1 which are members of some 4736 // structure. These are often used to approximate flexible arrays in C89 4737 // code. 4738 if (IsTailPaddedMemberArray(*this, size, ND)) 4739 return; 4740 4741 // Suppress the warning if the subscript expression (as identified by the 4742 // ']' location) and the index expression are both from macro expansions 4743 // within a system header. 4744 if (ASE) { 4745 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4746 ASE->getRBracketLoc()); 4747 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4748 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4749 IndexExpr->getLocStart()); 4750 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4751 return; 4752 } 4753 } 4754 4755 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4756 if (ASE) 4757 DiagID = diag::warn_array_index_exceeds_bounds; 4758 4759 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4760 PDiag(DiagID) << index.toString(10, true) 4761 << size.toString(10, true) 4762 << (unsigned)size.getLimitedValue(~0U) 4763 << IndexExpr->getSourceRange()); 4764 } else { 4765 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4766 if (!ASE) { 4767 DiagID = diag::warn_ptr_arith_precedes_bounds; 4768 if (index.isNegative()) index = -index; 4769 } 4770 4771 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4772 PDiag(DiagID) << index.toString(10, true) 4773 << IndexExpr->getSourceRange()); 4774 } 4775 4776 if (!ND) { 4777 // Try harder to find a NamedDecl to point at in the note. 4778 while (const ArraySubscriptExpr *ASE = 4779 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 4780 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 4781 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4782 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4783 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4784 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4785 } 4786 4787 if (ND) 4788 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4789 PDiag(diag::note_array_index_out_of_bounds) 4790 << ND->getDeclName()); 4791} 4792 4793void Sema::CheckArrayAccess(const Expr *expr) { 4794 int AllowOnePastEnd = 0; 4795 while (expr) { 4796 expr = expr->IgnoreParenImpCasts(); 4797 switch (expr->getStmtClass()) { 4798 case Stmt::ArraySubscriptExprClass: { 4799 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4800 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 4801 AllowOnePastEnd > 0); 4802 return; 4803 } 4804 case Stmt::UnaryOperatorClass: { 4805 // Only unwrap the * and & unary operators 4806 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4807 expr = UO->getSubExpr(); 4808 switch (UO->getOpcode()) { 4809 case UO_AddrOf: 4810 AllowOnePastEnd++; 4811 break; 4812 case UO_Deref: 4813 AllowOnePastEnd--; 4814 break; 4815 default: 4816 return; 4817 } 4818 break; 4819 } 4820 case Stmt::ConditionalOperatorClass: { 4821 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4822 if (const Expr *lhs = cond->getLHS()) 4823 CheckArrayAccess(lhs); 4824 if (const Expr *rhs = cond->getRHS()) 4825 CheckArrayAccess(rhs); 4826 return; 4827 } 4828 default: 4829 return; 4830 } 4831 } 4832} 4833 4834//===--- CHECK: Objective-C retain cycles ----------------------------------// 4835 4836namespace { 4837 struct RetainCycleOwner { 4838 RetainCycleOwner() : Variable(0), Indirect(false) {} 4839 VarDecl *Variable; 4840 SourceRange Range; 4841 SourceLocation Loc; 4842 bool Indirect; 4843 4844 void setLocsFrom(Expr *e) { 4845 Loc = e->getExprLoc(); 4846 Range = e->getSourceRange(); 4847 } 4848 }; 4849} 4850 4851/// Consider whether capturing the given variable can possibly lead to 4852/// a retain cycle. 4853static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4854 // In ARC, it's captured strongly iff the variable has __strong 4855 // lifetime. In MRR, it's captured strongly if the variable is 4856 // __block and has an appropriate type. 4857 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4858 return false; 4859 4860 owner.Variable = var; 4861 owner.setLocsFrom(ref); 4862 return true; 4863} 4864 4865static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 4866 while (true) { 4867 e = e->IgnoreParens(); 4868 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4869 switch (cast->getCastKind()) { 4870 case CK_BitCast: 4871 case CK_LValueBitCast: 4872 case CK_LValueToRValue: 4873 case CK_ARCReclaimReturnedObject: 4874 e = cast->getSubExpr(); 4875 continue; 4876 4877 default: 4878 return false; 4879 } 4880 } 4881 4882 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4883 ObjCIvarDecl *ivar = ref->getDecl(); 4884 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4885 return false; 4886 4887 // Try to find a retain cycle in the base. 4888 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 4889 return false; 4890 4891 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4892 owner.Indirect = true; 4893 return true; 4894 } 4895 4896 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4897 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4898 if (!var) return false; 4899 return considerVariable(var, ref, owner); 4900 } 4901 4902 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4903 if (member->isArrow()) return false; 4904 4905 // Don't count this as an indirect ownership. 4906 e = member->getBase(); 4907 continue; 4908 } 4909 4910 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4911 // Only pay attention to pseudo-objects on property references. 4912 ObjCPropertyRefExpr *pre 4913 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4914 ->IgnoreParens()); 4915 if (!pre) return false; 4916 if (pre->isImplicitProperty()) return false; 4917 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4918 if (!property->isRetaining() && 4919 !(property->getPropertyIvarDecl() && 4920 property->getPropertyIvarDecl()->getType() 4921 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4922 return false; 4923 4924 owner.Indirect = true; 4925 if (pre->isSuperReceiver()) { 4926 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 4927 if (!owner.Variable) 4928 return false; 4929 owner.Loc = pre->getLocation(); 4930 owner.Range = pre->getSourceRange(); 4931 return true; 4932 } 4933 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4934 ->getSourceExpr()); 4935 continue; 4936 } 4937 4938 // Array ivars? 4939 4940 return false; 4941 } 4942} 4943 4944namespace { 4945 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4946 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4947 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4948 Variable(variable), Capturer(0) {} 4949 4950 VarDecl *Variable; 4951 Expr *Capturer; 4952 4953 void VisitDeclRefExpr(DeclRefExpr *ref) { 4954 if (ref->getDecl() == Variable && !Capturer) 4955 Capturer = ref; 4956 } 4957 4958 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4959 if (Capturer) return; 4960 Visit(ref->getBase()); 4961 if (Capturer && ref->isFreeIvar()) 4962 Capturer = ref; 4963 } 4964 4965 void VisitBlockExpr(BlockExpr *block) { 4966 // Look inside nested blocks 4967 if (block->getBlockDecl()->capturesVariable(Variable)) 4968 Visit(block->getBlockDecl()->getBody()); 4969 } 4970 }; 4971} 4972 4973/// Check whether the given argument is a block which captures a 4974/// variable. 4975static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4976 assert(owner.Variable && owner.Loc.isValid()); 4977 4978 e = e->IgnoreParenCasts(); 4979 BlockExpr *block = dyn_cast<BlockExpr>(e); 4980 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4981 return 0; 4982 4983 FindCaptureVisitor visitor(S.Context, owner.Variable); 4984 visitor.Visit(block->getBlockDecl()->getBody()); 4985 return visitor.Capturer; 4986} 4987 4988static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4989 RetainCycleOwner &owner) { 4990 assert(capturer); 4991 assert(owner.Variable && owner.Loc.isValid()); 4992 4993 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 4994 << owner.Variable << capturer->getSourceRange(); 4995 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 4996 << owner.Indirect << owner.Range; 4997} 4998 4999/// Check for a keyword selector that starts with the word 'add' or 5000/// 'set'. 5001static bool isSetterLikeSelector(Selector sel) { 5002 if (sel.isUnarySelector()) return false; 5003 5004 StringRef str = sel.getNameForSlot(0); 5005 while (!str.empty() && str.front() == '_') str = str.substr(1); 5006 if (str.startswith("set")) 5007 str = str.substr(3); 5008 else if (str.startswith("add")) { 5009 // Specially whitelist 'addOperationWithBlock:'. 5010 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 5011 return false; 5012 str = str.substr(3); 5013 } 5014 else 5015 return false; 5016 5017 if (str.empty()) return true; 5018 return !islower(str.front()); 5019} 5020 5021/// Check a message send to see if it's likely to cause a retain cycle. 5022void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 5023 // Only check instance methods whose selector looks like a setter. 5024 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 5025 return; 5026 5027 // Try to find a variable that the receiver is strongly owned by. 5028 RetainCycleOwner owner; 5029 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 5030 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 5031 return; 5032 } else { 5033 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 5034 owner.Variable = getCurMethodDecl()->getSelfDecl(); 5035 owner.Loc = msg->getSuperLoc(); 5036 owner.Range = msg->getSuperLoc(); 5037 } 5038 5039 // Check whether the receiver is captured by any of the arguments. 5040 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 5041 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 5042 return diagnoseRetainCycle(*this, capturer, owner); 5043} 5044 5045/// Check a property assign to see if it's likely to cause a retain cycle. 5046void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 5047 RetainCycleOwner owner; 5048 if (!findRetainCycleOwner(*this, receiver, owner)) 5049 return; 5050 5051 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 5052 diagnoseRetainCycle(*this, capturer, owner); 5053} 5054 5055bool Sema::checkUnsafeAssigns(SourceLocation Loc, 5056 QualType LHS, Expr *RHS) { 5057 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 5058 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 5059 return false; 5060 // strip off any implicit cast added to get to the one arc-specific 5061 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5062 if (cast->getCastKind() == CK_ARCConsumeObject) { 5063 Diag(Loc, diag::warn_arc_retained_assign) 5064 << (LT == Qualifiers::OCL_ExplicitNone) 5065 << RHS->getSourceRange(); 5066 return true; 5067 } 5068 RHS = cast->getSubExpr(); 5069 } 5070 return false; 5071} 5072 5073void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 5074 Expr *LHS, Expr *RHS) { 5075 QualType LHSType; 5076 // PropertyRef on LHS type need be directly obtained from 5077 // its declaration as it has a PsuedoType. 5078 ObjCPropertyRefExpr *PRE 5079 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 5080 if (PRE && !PRE->isImplicitProperty()) { 5081 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5082 if (PD) 5083 LHSType = PD->getType(); 5084 } 5085 5086 if (LHSType.isNull()) 5087 LHSType = LHS->getType(); 5088 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 5089 return; 5090 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 5091 // FIXME. Check for other life times. 5092 if (LT != Qualifiers::OCL_None) 5093 return; 5094 5095 if (PRE) { 5096 if (PRE->isImplicitProperty()) 5097 return; 5098 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5099 if (!PD) 5100 return; 5101 5102 unsigned Attributes = PD->getPropertyAttributes(); 5103 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 5104 // when 'assign' attribute was not explicitly specified 5105 // by user, ignore it and rely on property type itself 5106 // for lifetime info. 5107 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 5108 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 5109 LHSType->isObjCRetainableType()) 5110 return; 5111 5112 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5113 if (cast->getCastKind() == CK_ARCConsumeObject) { 5114 Diag(Loc, diag::warn_arc_retained_property_assign) 5115 << RHS->getSourceRange(); 5116 return; 5117 } 5118 RHS = cast->getSubExpr(); 5119 } 5120 } 5121 } 5122} 5123 5124//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 5125 5126namespace { 5127bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 5128 SourceLocation StmtLoc, 5129 const NullStmt *Body) { 5130 // Do not warn if the body is a macro that expands to nothing, e.g: 5131 // 5132 // #define CALL(x) 5133 // if (condition) 5134 // CALL(0); 5135 // 5136 if (Body->hasLeadingEmptyMacro()) 5137 return false; 5138 5139 // Get line numbers of statement and body. 5140 bool StmtLineInvalid; 5141 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 5142 &StmtLineInvalid); 5143 if (StmtLineInvalid) 5144 return false; 5145 5146 bool BodyLineInvalid; 5147 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 5148 &BodyLineInvalid); 5149 if (BodyLineInvalid) 5150 return false; 5151 5152 // Warn if null statement and body are on the same line. 5153 if (StmtLine != BodyLine) 5154 return false; 5155 5156 return true; 5157} 5158} // Unnamed namespace 5159 5160void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5161 const Stmt *Body, 5162 unsigned DiagID) { 5163 // Since this is a syntactic check, don't emit diagnostic for template 5164 // instantiations, this just adds noise. 5165 if (CurrentInstantiationScope) 5166 return; 5167 5168 // The body should be a null statement. 5169 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5170 if (!NBody) 5171 return; 5172 5173 // Do the usual checks. 5174 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5175 return; 5176 5177 Diag(NBody->getSemiLoc(), DiagID); 5178 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5179} 5180 5181void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 5182 const Stmt *PossibleBody) { 5183 assert(!CurrentInstantiationScope); // Ensured by caller 5184 5185 SourceLocation StmtLoc; 5186 const Stmt *Body; 5187 unsigned DiagID; 5188 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 5189 StmtLoc = FS->getRParenLoc(); 5190 Body = FS->getBody(); 5191 DiagID = diag::warn_empty_for_body; 5192 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 5193 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 5194 Body = WS->getBody(); 5195 DiagID = diag::warn_empty_while_body; 5196 } else 5197 return; // Neither `for' nor `while'. 5198 5199 // The body should be a null statement. 5200 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5201 if (!NBody) 5202 return; 5203 5204 // Skip expensive checks if diagnostic is disabled. 5205 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 5206 DiagnosticsEngine::Ignored) 5207 return; 5208 5209 // Do the usual checks. 5210 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5211 return; 5212 5213 // `for(...);' and `while(...);' are popular idioms, so in order to keep 5214 // noise level low, emit diagnostics only if for/while is followed by a 5215 // CompoundStmt, e.g.: 5216 // for (int i = 0; i < n; i++); 5217 // { 5218 // a(i); 5219 // } 5220 // or if for/while is followed by a statement with more indentation 5221 // than for/while itself: 5222 // for (int i = 0; i < n; i++); 5223 // a(i); 5224 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 5225 if (!ProbableTypo) { 5226 bool BodyColInvalid; 5227 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 5228 PossibleBody->getLocStart(), 5229 &BodyColInvalid); 5230 if (BodyColInvalid) 5231 return; 5232 5233 bool StmtColInvalid; 5234 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 5235 S->getLocStart(), 5236 &StmtColInvalid); 5237 if (StmtColInvalid) 5238 return; 5239 5240 if (BodyCol > StmtCol) 5241 ProbableTypo = true; 5242 } 5243 5244 if (ProbableTypo) { 5245 Diag(NBody->getSemiLoc(), DiagID); 5246 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5247 } 5248} 5249