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