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