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/SemaInternal.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExprObjC.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/Analysis/Analyses/FormatString.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/SmallBitVector.h" 37 #include "llvm/ADT/SmallString.h" 38 #include "llvm/Support/ConvertUTF.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <limits> 41 using namespace clang; 42 using namespace sema; 43 44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 45 unsigned ByteNo) const { 46 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 47 Context.getTargetInfo()); 48 } 49 50 /// Checks that a call expression's argument count is the desired number. 51 /// This is useful when doing custom type-checking. Returns true on error. 52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 53 unsigned argCount = call->getNumArgs(); 54 if (argCount == desiredArgCount) return false; 55 56 if (argCount < desiredArgCount) 57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 58 << 0 /*function call*/ << desiredArgCount << argCount 59 << call->getSourceRange(); 60 61 // Highlight all the excess arguments. 62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 63 call->getArg(argCount - 1)->getLocEnd()); 64 65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 66 << 0 /*function call*/ << desiredArgCount << argCount 67 << call->getArg(1)->getSourceRange(); 68 } 69 70 /// Check that the first argument to __builtin_annotation is an integer 71 /// and the second argument is a non-wide string literal. 72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 73 if (checkArgCount(S, TheCall, 2)) 74 return true; 75 76 // First argument should be an integer. 77 Expr *ValArg = TheCall->getArg(0); 78 QualType Ty = ValArg->getType(); 79 if (!Ty->isIntegerType()) { 80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 81 << ValArg->getSourceRange(); 82 return true; 83 } 84 85 // Second argument should be a constant string. 86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 88 if (!Literal || !Literal->isAscii()) { 89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 90 << StrArg->getSourceRange(); 91 return true; 92 } 93 94 TheCall->setType(Ty); 95 return false; 96 } 97 98 /// Check that the argument to __builtin_addressof is a glvalue, and set the 99 /// result type to the corresponding pointer type. 100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 101 if (checkArgCount(S, TheCall, 1)) 102 return true; 103 104 ExprResult Arg(TheCall->getArg(0)); 105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 106 if (ResultType.isNull()) 107 return true; 108 109 TheCall->setArg(0, Arg.get()); 110 TheCall->setType(ResultType); 111 return false; 112 } 113 114 ExprResult 115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 116 ExprResult TheCallResult(TheCall); 117 118 // Find out if any arguments are required to be integer constant expressions. 119 unsigned ICEArguments = 0; 120 ASTContext::GetBuiltinTypeError Error; 121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 122 if (Error != ASTContext::GE_None) 123 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 124 125 // If any arguments are required to be ICE's, check and diagnose. 126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 127 // Skip arguments not required to be ICE's. 128 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 129 130 llvm::APSInt Result; 131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 132 return true; 133 ICEArguments &= ~(1 << ArgNo); 134 } 135 136 switch (BuiltinID) { 137 case Builtin::BI__builtin___CFStringMakeConstantString: 138 assert(TheCall->getNumArgs() == 1 && 139 "Wrong # arguments to builtin CFStringMakeConstantString"); 140 if (CheckObjCString(TheCall->getArg(0))) 141 return ExprError(); 142 break; 143 case Builtin::BI__builtin_stdarg_start: 144 case Builtin::BI__builtin_va_start: 145 if (SemaBuiltinVAStart(TheCall)) 146 return ExprError(); 147 break; 148 case Builtin::BI__va_start: { 149 switch (Context.getTargetInfo().getTriple().getArch()) { 150 case llvm::Triple::arm: 151 case llvm::Triple::thumb: 152 if (SemaBuiltinVAStartARM(TheCall)) 153 return ExprError(); 154 break; 155 default: 156 if (SemaBuiltinVAStart(TheCall)) 157 return ExprError(); 158 break; 159 } 160 break; 161 } 162 case Builtin::BI__builtin_isgreater: 163 case Builtin::BI__builtin_isgreaterequal: 164 case Builtin::BI__builtin_isless: 165 case Builtin::BI__builtin_islessequal: 166 case Builtin::BI__builtin_islessgreater: 167 case Builtin::BI__builtin_isunordered: 168 if (SemaBuiltinUnorderedCompare(TheCall)) 169 return ExprError(); 170 break; 171 case Builtin::BI__builtin_fpclassify: 172 if (SemaBuiltinFPClassification(TheCall, 6)) 173 return ExprError(); 174 break; 175 case Builtin::BI__builtin_isfinite: 176 case Builtin::BI__builtin_isinf: 177 case Builtin::BI__builtin_isinf_sign: 178 case Builtin::BI__builtin_isnan: 179 case Builtin::BI__builtin_isnormal: 180 if (SemaBuiltinFPClassification(TheCall, 1)) 181 return ExprError(); 182 break; 183 case Builtin::BI__builtin_shufflevector: 184 return SemaBuiltinShuffleVector(TheCall); 185 // TheCall will be freed by the smart pointer here, but that's fine, since 186 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 187 case Builtin::BI__builtin_prefetch: 188 if (SemaBuiltinPrefetch(TheCall)) 189 return ExprError(); 190 break; 191 case Builtin::BI__assume: 192 if (SemaBuiltinAssume(TheCall)) 193 return ExprError(); 194 break; 195 case Builtin::BI__builtin_object_size: 196 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 197 return ExprError(); 198 break; 199 case Builtin::BI__builtin_longjmp: 200 if (SemaBuiltinLongjmp(TheCall)) 201 return ExprError(); 202 break; 203 204 case Builtin::BI__builtin_classify_type: 205 if (checkArgCount(*this, TheCall, 1)) return true; 206 TheCall->setType(Context.IntTy); 207 break; 208 case Builtin::BI__builtin_constant_p: 209 if (checkArgCount(*this, TheCall, 1)) return true; 210 TheCall->setType(Context.IntTy); 211 break; 212 case Builtin::BI__sync_fetch_and_add: 213 case Builtin::BI__sync_fetch_and_add_1: 214 case Builtin::BI__sync_fetch_and_add_2: 215 case Builtin::BI__sync_fetch_and_add_4: 216 case Builtin::BI__sync_fetch_and_add_8: 217 case Builtin::BI__sync_fetch_and_add_16: 218 case Builtin::BI__sync_fetch_and_sub: 219 case Builtin::BI__sync_fetch_and_sub_1: 220 case Builtin::BI__sync_fetch_and_sub_2: 221 case Builtin::BI__sync_fetch_and_sub_4: 222 case Builtin::BI__sync_fetch_and_sub_8: 223 case Builtin::BI__sync_fetch_and_sub_16: 224 case Builtin::BI__sync_fetch_and_or: 225 case Builtin::BI__sync_fetch_and_or_1: 226 case Builtin::BI__sync_fetch_and_or_2: 227 case Builtin::BI__sync_fetch_and_or_4: 228 case Builtin::BI__sync_fetch_and_or_8: 229 case Builtin::BI__sync_fetch_and_or_16: 230 case Builtin::BI__sync_fetch_and_and: 231 case Builtin::BI__sync_fetch_and_and_1: 232 case Builtin::BI__sync_fetch_and_and_2: 233 case Builtin::BI__sync_fetch_and_and_4: 234 case Builtin::BI__sync_fetch_and_and_8: 235 case Builtin::BI__sync_fetch_and_and_16: 236 case Builtin::BI__sync_fetch_and_xor: 237 case Builtin::BI__sync_fetch_and_xor_1: 238 case Builtin::BI__sync_fetch_and_xor_2: 239 case Builtin::BI__sync_fetch_and_xor_4: 240 case Builtin::BI__sync_fetch_and_xor_8: 241 case Builtin::BI__sync_fetch_and_xor_16: 242 case Builtin::BI__sync_add_and_fetch: 243 case Builtin::BI__sync_add_and_fetch_1: 244 case Builtin::BI__sync_add_and_fetch_2: 245 case Builtin::BI__sync_add_and_fetch_4: 246 case Builtin::BI__sync_add_and_fetch_8: 247 case Builtin::BI__sync_add_and_fetch_16: 248 case Builtin::BI__sync_sub_and_fetch: 249 case Builtin::BI__sync_sub_and_fetch_1: 250 case Builtin::BI__sync_sub_and_fetch_2: 251 case Builtin::BI__sync_sub_and_fetch_4: 252 case Builtin::BI__sync_sub_and_fetch_8: 253 case Builtin::BI__sync_sub_and_fetch_16: 254 case Builtin::BI__sync_and_and_fetch: 255 case Builtin::BI__sync_and_and_fetch_1: 256 case Builtin::BI__sync_and_and_fetch_2: 257 case Builtin::BI__sync_and_and_fetch_4: 258 case Builtin::BI__sync_and_and_fetch_8: 259 case Builtin::BI__sync_and_and_fetch_16: 260 case Builtin::BI__sync_or_and_fetch: 261 case Builtin::BI__sync_or_and_fetch_1: 262 case Builtin::BI__sync_or_and_fetch_2: 263 case Builtin::BI__sync_or_and_fetch_4: 264 case Builtin::BI__sync_or_and_fetch_8: 265 case Builtin::BI__sync_or_and_fetch_16: 266 case Builtin::BI__sync_xor_and_fetch: 267 case Builtin::BI__sync_xor_and_fetch_1: 268 case Builtin::BI__sync_xor_and_fetch_2: 269 case Builtin::BI__sync_xor_and_fetch_4: 270 case Builtin::BI__sync_xor_and_fetch_8: 271 case Builtin::BI__sync_xor_and_fetch_16: 272 case Builtin::BI__sync_val_compare_and_swap: 273 case Builtin::BI__sync_val_compare_and_swap_1: 274 case Builtin::BI__sync_val_compare_and_swap_2: 275 case Builtin::BI__sync_val_compare_and_swap_4: 276 case Builtin::BI__sync_val_compare_and_swap_8: 277 case Builtin::BI__sync_val_compare_and_swap_16: 278 case Builtin::BI__sync_bool_compare_and_swap: 279 case Builtin::BI__sync_bool_compare_and_swap_1: 280 case Builtin::BI__sync_bool_compare_and_swap_2: 281 case Builtin::BI__sync_bool_compare_and_swap_4: 282 case Builtin::BI__sync_bool_compare_and_swap_8: 283 case Builtin::BI__sync_bool_compare_and_swap_16: 284 case Builtin::BI__sync_lock_test_and_set: 285 case Builtin::BI__sync_lock_test_and_set_1: 286 case Builtin::BI__sync_lock_test_and_set_2: 287 case Builtin::BI__sync_lock_test_and_set_4: 288 case Builtin::BI__sync_lock_test_and_set_8: 289 case Builtin::BI__sync_lock_test_and_set_16: 290 case Builtin::BI__sync_lock_release: 291 case Builtin::BI__sync_lock_release_1: 292 case Builtin::BI__sync_lock_release_2: 293 case Builtin::BI__sync_lock_release_4: 294 case Builtin::BI__sync_lock_release_8: 295 case Builtin::BI__sync_lock_release_16: 296 case Builtin::BI__sync_swap: 297 case Builtin::BI__sync_swap_1: 298 case Builtin::BI__sync_swap_2: 299 case Builtin::BI__sync_swap_4: 300 case Builtin::BI__sync_swap_8: 301 case Builtin::BI__sync_swap_16: 302 return SemaBuiltinAtomicOverloaded(TheCallResult); 303 #define BUILTIN(ID, TYPE, ATTRS) 304 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 305 case Builtin::BI##ID: \ 306 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 307 #include "clang/Basic/Builtins.def" 308 case Builtin::BI__builtin_annotation: 309 if (SemaBuiltinAnnotation(*this, TheCall)) 310 return ExprError(); 311 break; 312 case Builtin::BI__builtin_addressof: 313 if (SemaBuiltinAddressof(*this, TheCall)) 314 return ExprError(); 315 break; 316 case Builtin::BI__builtin_operator_new: 317 case Builtin::BI__builtin_operator_delete: 318 if (!getLangOpts().CPlusPlus) { 319 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 320 << (BuiltinID == Builtin::BI__builtin_operator_new 321 ? "__builtin_operator_new" 322 : "__builtin_operator_delete") 323 << "C++"; 324 return ExprError(); 325 } 326 // CodeGen assumes it can find the global new and delete to call, 327 // so ensure that they are declared. 328 DeclareGlobalNewDelete(); 329 break; 330 } 331 332 // Since the target specific builtins for each arch overlap, only check those 333 // of the arch we are compiling for. 334 if (BuiltinID >= Builtin::FirstTSBuiltin) { 335 switch (Context.getTargetInfo().getTriple().getArch()) { 336 case llvm::Triple::arm: 337 case llvm::Triple::armeb: 338 case llvm::Triple::thumb: 339 case llvm::Triple::thumbeb: 340 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 341 return ExprError(); 342 break; 343 case llvm::Triple::aarch64: 344 case llvm::Triple::aarch64_be: 345 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 346 return ExprError(); 347 break; 348 case llvm::Triple::mips: 349 case llvm::Triple::mipsel: 350 case llvm::Triple::mips64: 351 case llvm::Triple::mips64el: 352 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 353 return ExprError(); 354 break; 355 case llvm::Triple::x86: 356 case llvm::Triple::x86_64: 357 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 358 return ExprError(); 359 break; 360 default: 361 break; 362 } 363 } 364 365 return TheCallResult; 366 } 367 368 // Get the valid immediate range for the specified NEON type code. 369 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 370 NeonTypeFlags Type(t); 371 int IsQuad = ForceQuad ? true : Type.isQuad(); 372 switch (Type.getEltType()) { 373 case NeonTypeFlags::Int8: 374 case NeonTypeFlags::Poly8: 375 return shift ? 7 : (8 << IsQuad) - 1; 376 case NeonTypeFlags::Int16: 377 case NeonTypeFlags::Poly16: 378 return shift ? 15 : (4 << IsQuad) - 1; 379 case NeonTypeFlags::Int32: 380 return shift ? 31 : (2 << IsQuad) - 1; 381 case NeonTypeFlags::Int64: 382 case NeonTypeFlags::Poly64: 383 return shift ? 63 : (1 << IsQuad) - 1; 384 case NeonTypeFlags::Poly128: 385 return shift ? 127 : (1 << IsQuad) - 1; 386 case NeonTypeFlags::Float16: 387 assert(!shift && "cannot shift float types!"); 388 return (4 << IsQuad) - 1; 389 case NeonTypeFlags::Float32: 390 assert(!shift && "cannot shift float types!"); 391 return (2 << IsQuad) - 1; 392 case NeonTypeFlags::Float64: 393 assert(!shift && "cannot shift float types!"); 394 return (1 << IsQuad) - 1; 395 } 396 llvm_unreachable("Invalid NeonTypeFlag!"); 397 } 398 399 /// getNeonEltType - Return the QualType corresponding to the elements of 400 /// the vector type specified by the NeonTypeFlags. This is used to check 401 /// the pointer arguments for Neon load/store intrinsics. 402 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 403 bool IsPolyUnsigned, bool IsInt64Long) { 404 switch (Flags.getEltType()) { 405 case NeonTypeFlags::Int8: 406 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 407 case NeonTypeFlags::Int16: 408 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 409 case NeonTypeFlags::Int32: 410 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 411 case NeonTypeFlags::Int64: 412 if (IsInt64Long) 413 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 414 else 415 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 416 : Context.LongLongTy; 417 case NeonTypeFlags::Poly8: 418 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 419 case NeonTypeFlags::Poly16: 420 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 421 case NeonTypeFlags::Poly64: 422 return Context.UnsignedLongTy; 423 case NeonTypeFlags::Poly128: 424 break; 425 case NeonTypeFlags::Float16: 426 return Context.HalfTy; 427 case NeonTypeFlags::Float32: 428 return Context.FloatTy; 429 case NeonTypeFlags::Float64: 430 return Context.DoubleTy; 431 } 432 llvm_unreachable("Invalid NeonTypeFlag!"); 433 } 434 435 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 436 llvm::APSInt Result; 437 uint64_t mask = 0; 438 unsigned TV = 0; 439 int PtrArgNum = -1; 440 bool HasConstPtr = false; 441 switch (BuiltinID) { 442 #define GET_NEON_OVERLOAD_CHECK 443 #include "clang/Basic/arm_neon.inc" 444 #undef GET_NEON_OVERLOAD_CHECK 445 } 446 447 // For NEON intrinsics which are overloaded on vector element type, validate 448 // the immediate which specifies which variant to emit. 449 unsigned ImmArg = TheCall->getNumArgs()-1; 450 if (mask) { 451 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 452 return true; 453 454 TV = Result.getLimitedValue(64); 455 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 456 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 457 << TheCall->getArg(ImmArg)->getSourceRange(); 458 } 459 460 if (PtrArgNum >= 0) { 461 // Check that pointer arguments have the specified type. 462 Expr *Arg = TheCall->getArg(PtrArgNum); 463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 464 Arg = ICE->getSubExpr(); 465 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 466 QualType RHSTy = RHS.get()->getType(); 467 468 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 469 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 470 bool IsInt64Long = 471 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 472 QualType EltTy = 473 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 474 if (HasConstPtr) 475 EltTy = EltTy.withConst(); 476 QualType LHSTy = Context.getPointerType(EltTy); 477 AssignConvertType ConvTy; 478 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 479 if (RHS.isInvalid()) 480 return true; 481 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 482 RHS.get(), AA_Assigning)) 483 return true; 484 } 485 486 // For NEON intrinsics which take an immediate value as part of the 487 // instruction, range check them here. 488 unsigned i = 0, l = 0, u = 0; 489 switch (BuiltinID) { 490 default: 491 return false; 492 #define GET_NEON_IMMEDIATE_CHECK 493 #include "clang/Basic/arm_neon.inc" 494 #undef GET_NEON_IMMEDIATE_CHECK 495 } 496 497 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 498 } 499 500 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 501 unsigned MaxWidth) { 502 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 503 BuiltinID == ARM::BI__builtin_arm_ldaex || 504 BuiltinID == ARM::BI__builtin_arm_strex || 505 BuiltinID == ARM::BI__builtin_arm_stlex || 506 BuiltinID == AArch64::BI__builtin_arm_ldrex || 507 BuiltinID == AArch64::BI__builtin_arm_ldaex || 508 BuiltinID == AArch64::BI__builtin_arm_strex || 509 BuiltinID == AArch64::BI__builtin_arm_stlex) && 510 "unexpected ARM builtin"); 511 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 512 BuiltinID == ARM::BI__builtin_arm_ldaex || 513 BuiltinID == AArch64::BI__builtin_arm_ldrex || 514 BuiltinID == AArch64::BI__builtin_arm_ldaex; 515 516 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 517 518 // Ensure that we have the proper number of arguments. 519 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 520 return true; 521 522 // Inspect the pointer argument of the atomic builtin. This should always be 523 // a pointer type, whose element is an integral scalar or pointer type. 524 // Because it is a pointer type, we don't have to worry about any implicit 525 // casts here. 526 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 527 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 528 if (PointerArgRes.isInvalid()) 529 return true; 530 PointerArg = PointerArgRes.get(); 531 532 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 533 if (!pointerType) { 534 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 535 << PointerArg->getType() << PointerArg->getSourceRange(); 536 return true; 537 } 538 539 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 540 // task is to insert the appropriate casts into the AST. First work out just 541 // what the appropriate type is. 542 QualType ValType = pointerType->getPointeeType(); 543 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 544 if (IsLdrex) 545 AddrType.addConst(); 546 547 // Issue a warning if the cast is dodgy. 548 CastKind CastNeeded = CK_NoOp; 549 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 550 CastNeeded = CK_BitCast; 551 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 552 << PointerArg->getType() 553 << Context.getPointerType(AddrType) 554 << AA_Passing << PointerArg->getSourceRange(); 555 } 556 557 // Finally, do the cast and replace the argument with the corrected version. 558 AddrType = Context.getPointerType(AddrType); 559 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 560 if (PointerArgRes.isInvalid()) 561 return true; 562 PointerArg = PointerArgRes.get(); 563 564 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 565 566 // In general, we allow ints, floats and pointers to be loaded and stored. 567 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 568 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 569 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 570 << PointerArg->getType() << PointerArg->getSourceRange(); 571 return true; 572 } 573 574 // But ARM doesn't have instructions to deal with 128-bit versions. 575 if (Context.getTypeSize(ValType) > MaxWidth) { 576 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 577 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 578 << PointerArg->getType() << PointerArg->getSourceRange(); 579 return true; 580 } 581 582 switch (ValType.getObjCLifetime()) { 583 case Qualifiers::OCL_None: 584 case Qualifiers::OCL_ExplicitNone: 585 // okay 586 break; 587 588 case Qualifiers::OCL_Weak: 589 case Qualifiers::OCL_Strong: 590 case Qualifiers::OCL_Autoreleasing: 591 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 592 << ValType << PointerArg->getSourceRange(); 593 return true; 594 } 595 596 597 if (IsLdrex) { 598 TheCall->setType(ValType); 599 return false; 600 } 601 602 // Initialize the argument to be stored. 603 ExprResult ValArg = TheCall->getArg(0); 604 InitializedEntity Entity = InitializedEntity::InitializeParameter( 605 Context, ValType, /*consume*/ false); 606 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 607 if (ValArg.isInvalid()) 608 return true; 609 TheCall->setArg(0, ValArg.get()); 610 611 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 612 // but the custom checker bypasses all default analysis. 613 TheCall->setType(Context.IntTy); 614 return false; 615 } 616 617 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 618 llvm::APSInt Result; 619 620 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 621 BuiltinID == ARM::BI__builtin_arm_ldaex || 622 BuiltinID == ARM::BI__builtin_arm_strex || 623 BuiltinID == ARM::BI__builtin_arm_stlex) { 624 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 625 } 626 627 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 628 return true; 629 630 // For intrinsics which take an immediate value as part of the instruction, 631 // range check them here. 632 unsigned i = 0, l = 0, u = 0; 633 switch (BuiltinID) { 634 default: return false; 635 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 636 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 637 case ARM::BI__builtin_arm_vcvtr_f: 638 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 639 case ARM::BI__builtin_arm_dmb: 640 case ARM::BI__builtin_arm_dsb: 641 case ARM::BI__builtin_arm_isb: l = 0; u = 15; break; 642 } 643 644 // FIXME: VFP Intrinsics should error if VFP not present. 645 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 646 } 647 648 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 649 CallExpr *TheCall) { 650 llvm::APSInt Result; 651 652 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 653 BuiltinID == AArch64::BI__builtin_arm_ldaex || 654 BuiltinID == AArch64::BI__builtin_arm_strex || 655 BuiltinID == AArch64::BI__builtin_arm_stlex) { 656 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 657 } 658 659 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 660 return true; 661 662 // For intrinsics which take an immediate value as part of the instruction, 663 // range check them here. 664 unsigned i = 0, l = 0, u = 0; 665 switch (BuiltinID) { 666 default: return false; 667 case AArch64::BI__builtin_arm_dmb: 668 case AArch64::BI__builtin_arm_dsb: 669 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 670 } 671 672 // FIXME: VFP Intrinsics should error if VFP not present. 673 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 674 } 675 676 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 677 unsigned i = 0, l = 0, u = 0; 678 switch (BuiltinID) { 679 default: return false; 680 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 681 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 682 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 683 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 684 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 685 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 686 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 687 } 688 689 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 690 } 691 692 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 693 switch (BuiltinID) { 694 case X86::BI_mm_prefetch: 695 // This is declared to take (const char*, int) 696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 697 } 698 return false; 699 } 700 701 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 702 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 703 /// Returns true when the format fits the function and the FormatStringInfo has 704 /// been populated. 705 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 706 FormatStringInfo *FSI) { 707 FSI->HasVAListArg = Format->getFirstArg() == 0; 708 FSI->FormatIdx = Format->getFormatIdx() - 1; 709 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 710 711 // The way the format attribute works in GCC, the implicit this argument 712 // of member functions is counted. However, it doesn't appear in our own 713 // lists, so decrement format_idx in that case. 714 if (IsCXXMember) { 715 if(FSI->FormatIdx == 0) 716 return false; 717 --FSI->FormatIdx; 718 if (FSI->FirstDataArg != 0) 719 --FSI->FirstDataArg; 720 } 721 return true; 722 } 723 724 /// Checks if a the given expression evaluates to null. 725 /// 726 /// \brief Returns true if the value evaluates to null. 727 static bool CheckNonNullExpr(Sema &S, 728 const Expr *Expr) { 729 // As a special case, transparent unions initialized with zero are 730 // considered null for the purposes of the nonnull attribute. 731 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 732 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 733 if (const CompoundLiteralExpr *CLE = 734 dyn_cast<CompoundLiteralExpr>(Expr)) 735 if (const InitListExpr *ILE = 736 dyn_cast<InitListExpr>(CLE->getInitializer())) 737 Expr = ILE->getInit(0); 738 } 739 740 bool Result; 741 return (!Expr->isValueDependent() && 742 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 743 !Result); 744 } 745 746 static void CheckNonNullArgument(Sema &S, 747 const Expr *ArgExpr, 748 SourceLocation CallSiteLoc) { 749 if (CheckNonNullExpr(S, ArgExpr)) 750 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 751 } 752 753 static void CheckNonNullArguments(Sema &S, 754 const NamedDecl *FDecl, 755 const Expr * const *ExprArgs, 756 SourceLocation CallSiteLoc) { 757 // Check the attributes attached to the method/function itself. 758 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 759 for (const auto &Val : NonNull->args()) 760 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc); 761 } 762 763 // Check the attributes on the parameters. 764 ArrayRef<ParmVarDecl*> parms; 765 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 766 parms = FD->parameters(); 767 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl)) 768 parms = MD->parameters(); 769 770 unsigned argIndex = 0; 771 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 772 I != E; ++I, ++argIndex) { 773 const ParmVarDecl *PVD = *I; 774 if (PVD->hasAttr<NonNullAttr>()) 775 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc); 776 } 777 } 778 779 /// Handles the checks for format strings, non-POD arguments to vararg 780 /// functions, and NULL arguments passed to non-NULL parameters. 781 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 782 unsigned NumParams, bool IsMemberFunction, 783 SourceLocation Loc, SourceRange Range, 784 VariadicCallType CallType) { 785 // FIXME: We should check as much as we can in the template definition. 786 if (CurContext->isDependentContext()) 787 return; 788 789 // Printf and scanf checking. 790 llvm::SmallBitVector CheckedVarArgs; 791 if (FDecl) { 792 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 793 // Only create vector if there are format attributes. 794 CheckedVarArgs.resize(Args.size()); 795 796 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 797 CheckedVarArgs); 798 } 799 } 800 801 // Refuse POD arguments that weren't caught by the format string 802 // checks above. 803 if (CallType != VariadicDoesNotApply) { 804 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 805 // Args[ArgIdx] can be null in malformed code. 806 if (const Expr *Arg = Args[ArgIdx]) { 807 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 808 checkVariadicArgument(Arg, CallType); 809 } 810 } 811 } 812 813 if (FDecl) { 814 CheckNonNullArguments(*this, FDecl, Args.data(), Loc); 815 816 // Type safety checking. 817 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 818 CheckArgumentWithTypeTag(I, Args.data()); 819 } 820 } 821 822 /// CheckConstructorCall - Check a constructor call for correctness and safety 823 /// properties not enforced by the C type system. 824 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 825 ArrayRef<const Expr *> Args, 826 const FunctionProtoType *Proto, 827 SourceLocation Loc) { 828 VariadicCallType CallType = 829 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 830 checkCall(FDecl, Args, Proto->getNumParams(), 831 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 832 } 833 834 /// CheckFunctionCall - Check a direct function call for various correctness 835 /// and safety properties not strictly enforced by the C type system. 836 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 837 const FunctionProtoType *Proto) { 838 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 839 isa<CXXMethodDecl>(FDecl); 840 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 841 IsMemberOperatorCall; 842 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 843 TheCall->getCallee()); 844 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 845 Expr** Args = TheCall->getArgs(); 846 unsigned NumArgs = TheCall->getNumArgs(); 847 if (IsMemberOperatorCall) { 848 // If this is a call to a member operator, hide the first argument 849 // from checkCall. 850 // FIXME: Our choice of AST representation here is less than ideal. 851 ++Args; 852 --NumArgs; 853 } 854 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams, 855 IsMemberFunction, TheCall->getRParenLoc(), 856 TheCall->getCallee()->getSourceRange(), CallType); 857 858 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 859 // None of the checks below are needed for functions that don't have 860 // simple names (e.g., C++ conversion functions). 861 if (!FnInfo) 862 return false; 863 864 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 865 866 unsigned CMId = FDecl->getMemoryFunctionKind(); 867 if (CMId == 0) 868 return false; 869 870 // Handle memory setting and copying functions. 871 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 872 CheckStrlcpycatArguments(TheCall, FnInfo); 873 else if (CMId == Builtin::BIstrncat) 874 CheckStrncatArguments(TheCall, FnInfo); 875 else 876 CheckMemaccessArguments(TheCall, CMId, FnInfo); 877 878 return false; 879 } 880 881 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 882 ArrayRef<const Expr *> Args) { 883 VariadicCallType CallType = 884 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 885 886 checkCall(Method, Args, Method->param_size(), 887 /*IsMemberFunction=*/false, 888 lbrac, Method->getSourceRange(), CallType); 889 890 return false; 891 } 892 893 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 894 const FunctionProtoType *Proto) { 895 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 896 if (!V) 897 return false; 898 899 QualType Ty = V->getType(); 900 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType()) 901 return false; 902 903 VariadicCallType CallType; 904 if (!Proto || !Proto->isVariadic()) { 905 CallType = VariadicDoesNotApply; 906 } else if (Ty->isBlockPointerType()) { 907 CallType = VariadicBlock; 908 } else { // Ty->isFunctionPointerType() 909 CallType = VariadicFunction; 910 } 911 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 912 913 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(), 914 TheCall->getNumArgs()), 915 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 916 TheCall->getCallee()->getSourceRange(), CallType); 917 918 return false; 919 } 920 921 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 922 /// such as function pointers returned from functions. 923 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 924 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 925 TheCall->getCallee()); 926 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 927 928 checkCall(/*FDecl=*/nullptr, 929 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(), 930 TheCall->getNumArgs()), 931 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 932 TheCall->getCallee()->getSourceRange(), CallType); 933 934 return false; 935 } 936 937 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 938 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed || 939 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst) 940 return false; 941 942 switch (Op) { 943 case AtomicExpr::AO__c11_atomic_init: 944 llvm_unreachable("There is no ordering argument for an init"); 945 946 case AtomicExpr::AO__c11_atomic_load: 947 case AtomicExpr::AO__atomic_load_n: 948 case AtomicExpr::AO__atomic_load: 949 return Ordering != AtomicExpr::AO_ABI_memory_order_release && 950 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 951 952 case AtomicExpr::AO__c11_atomic_store: 953 case AtomicExpr::AO__atomic_store: 954 case AtomicExpr::AO__atomic_store_n: 955 return Ordering != AtomicExpr::AO_ABI_memory_order_consume && 956 Ordering != AtomicExpr::AO_ABI_memory_order_acquire && 957 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 958 959 default: 960 return true; 961 } 962 } 963 964 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 965 AtomicExpr::AtomicOp Op) { 966 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 967 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 968 969 // All these operations take one of the following forms: 970 enum { 971 // C __c11_atomic_init(A *, C) 972 Init, 973 // C __c11_atomic_load(A *, int) 974 Load, 975 // void __atomic_load(A *, CP, int) 976 Copy, 977 // C __c11_atomic_add(A *, M, int) 978 Arithmetic, 979 // C __atomic_exchange_n(A *, CP, int) 980 Xchg, 981 // void __atomic_exchange(A *, C *, CP, int) 982 GNUXchg, 983 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 984 C11CmpXchg, 985 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 986 GNUCmpXchg 987 } Form = Init; 988 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 989 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 990 // where: 991 // C is an appropriate type, 992 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 993 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 994 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 995 // the int parameters are for orderings. 996 997 assert(AtomicExpr::AO__c11_atomic_init == 0 && 998 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 999 && "need to update code for modified C11 atomics"); 1000 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 1001 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 1002 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 1003 Op == AtomicExpr::AO__atomic_store_n || 1004 Op == AtomicExpr::AO__atomic_exchange_n || 1005 Op == AtomicExpr::AO__atomic_compare_exchange_n; 1006 bool IsAddSub = false; 1007 1008 switch (Op) { 1009 case AtomicExpr::AO__c11_atomic_init: 1010 Form = Init; 1011 break; 1012 1013 case AtomicExpr::AO__c11_atomic_load: 1014 case AtomicExpr::AO__atomic_load_n: 1015 Form = Load; 1016 break; 1017 1018 case AtomicExpr::AO__c11_atomic_store: 1019 case AtomicExpr::AO__atomic_load: 1020 case AtomicExpr::AO__atomic_store: 1021 case AtomicExpr::AO__atomic_store_n: 1022 Form = Copy; 1023 break; 1024 1025 case AtomicExpr::AO__c11_atomic_fetch_add: 1026 case AtomicExpr::AO__c11_atomic_fetch_sub: 1027 case AtomicExpr::AO__atomic_fetch_add: 1028 case AtomicExpr::AO__atomic_fetch_sub: 1029 case AtomicExpr::AO__atomic_add_fetch: 1030 case AtomicExpr::AO__atomic_sub_fetch: 1031 IsAddSub = true; 1032 // Fall through. 1033 case AtomicExpr::AO__c11_atomic_fetch_and: 1034 case AtomicExpr::AO__c11_atomic_fetch_or: 1035 case AtomicExpr::AO__c11_atomic_fetch_xor: 1036 case AtomicExpr::AO__atomic_fetch_and: 1037 case AtomicExpr::AO__atomic_fetch_or: 1038 case AtomicExpr::AO__atomic_fetch_xor: 1039 case AtomicExpr::AO__atomic_fetch_nand: 1040 case AtomicExpr::AO__atomic_and_fetch: 1041 case AtomicExpr::AO__atomic_or_fetch: 1042 case AtomicExpr::AO__atomic_xor_fetch: 1043 case AtomicExpr::AO__atomic_nand_fetch: 1044 Form = Arithmetic; 1045 break; 1046 1047 case AtomicExpr::AO__c11_atomic_exchange: 1048 case AtomicExpr::AO__atomic_exchange_n: 1049 Form = Xchg; 1050 break; 1051 1052 case AtomicExpr::AO__atomic_exchange: 1053 Form = GNUXchg; 1054 break; 1055 1056 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 1057 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 1058 Form = C11CmpXchg; 1059 break; 1060 1061 case AtomicExpr::AO__atomic_compare_exchange: 1062 case AtomicExpr::AO__atomic_compare_exchange_n: 1063 Form = GNUCmpXchg; 1064 break; 1065 } 1066 1067 // Check we have the right number of arguments. 1068 if (TheCall->getNumArgs() < NumArgs[Form]) { 1069 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1070 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1071 << TheCall->getCallee()->getSourceRange(); 1072 return ExprError(); 1073 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 1074 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 1075 diag::err_typecheck_call_too_many_args) 1076 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1077 << TheCall->getCallee()->getSourceRange(); 1078 return ExprError(); 1079 } 1080 1081 // Inspect the first argument of the atomic operation. 1082 Expr *Ptr = TheCall->getArg(0); 1083 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 1084 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 1085 if (!pointerType) { 1086 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1087 << Ptr->getType() << Ptr->getSourceRange(); 1088 return ExprError(); 1089 } 1090 1091 // For a __c11 builtin, this should be a pointer to an _Atomic type. 1092 QualType AtomTy = pointerType->getPointeeType(); // 'A' 1093 QualType ValType = AtomTy; // 'C' 1094 if (IsC11) { 1095 if (!AtomTy->isAtomicType()) { 1096 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 1097 << Ptr->getType() << Ptr->getSourceRange(); 1098 return ExprError(); 1099 } 1100 if (AtomTy.isConstQualified()) { 1101 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 1102 << Ptr->getType() << Ptr->getSourceRange(); 1103 return ExprError(); 1104 } 1105 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 1106 } 1107 1108 // For an arithmetic operation, the implied arithmetic must be well-formed. 1109 if (Form == Arithmetic) { 1110 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 1111 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 1112 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1113 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1114 return ExprError(); 1115 } 1116 if (!IsAddSub && !ValType->isIntegerType()) { 1117 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 1118 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1119 return ExprError(); 1120 } 1121 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 1122 // For __atomic_*_n operations, the value type must be a scalar integral or 1123 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 1124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1125 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1126 return ExprError(); 1127 } 1128 1129 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 1130 !AtomTy->isScalarType()) { 1131 // For GNU atomics, require a trivially-copyable type. This is not part of 1132 // the GNU atomics specification, but we enforce it for sanity. 1133 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 1134 << Ptr->getType() << Ptr->getSourceRange(); 1135 return ExprError(); 1136 } 1137 1138 // FIXME: For any builtin other than a load, the ValType must not be 1139 // const-qualified. 1140 1141 switch (ValType.getObjCLifetime()) { 1142 case Qualifiers::OCL_None: 1143 case Qualifiers::OCL_ExplicitNone: 1144 // okay 1145 break; 1146 1147 case Qualifiers::OCL_Weak: 1148 case Qualifiers::OCL_Strong: 1149 case Qualifiers::OCL_Autoreleasing: 1150 // FIXME: Can this happen? By this point, ValType should be known 1151 // to be trivially copyable. 1152 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1153 << ValType << Ptr->getSourceRange(); 1154 return ExprError(); 1155 } 1156 1157 QualType ResultType = ValType; 1158 if (Form == Copy || Form == GNUXchg || Form == Init) 1159 ResultType = Context.VoidTy; 1160 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 1161 ResultType = Context.BoolTy; 1162 1163 // The type of a parameter passed 'by value'. In the GNU atomics, such 1164 // arguments are actually passed as pointers. 1165 QualType ByValType = ValType; // 'CP' 1166 if (!IsC11 && !IsN) 1167 ByValType = Ptr->getType(); 1168 1169 // The first argument --- the pointer --- has a fixed type; we 1170 // deduce the types of the rest of the arguments accordingly. Walk 1171 // the remaining arguments, converting them to the deduced value type. 1172 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 1173 QualType Ty; 1174 if (i < NumVals[Form] + 1) { 1175 switch (i) { 1176 case 1: 1177 // The second argument is the non-atomic operand. For arithmetic, this 1178 // is always passed by value, and for a compare_exchange it is always 1179 // passed by address. For the rest, GNU uses by-address and C11 uses 1180 // by-value. 1181 assert(Form != Load); 1182 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 1183 Ty = ValType; 1184 else if (Form == Copy || Form == Xchg) 1185 Ty = ByValType; 1186 else if (Form == Arithmetic) 1187 Ty = Context.getPointerDiffType(); 1188 else 1189 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 1190 break; 1191 case 2: 1192 // The third argument to compare_exchange / GNU exchange is a 1193 // (pointer to a) desired value. 1194 Ty = ByValType; 1195 break; 1196 case 3: 1197 // The fourth argument to GNU compare_exchange is a 'weak' flag. 1198 Ty = Context.BoolTy; 1199 break; 1200 } 1201 } else { 1202 // The order(s) are always converted to int. 1203 Ty = Context.IntTy; 1204 } 1205 1206 InitializedEntity Entity = 1207 InitializedEntity::InitializeParameter(Context, Ty, false); 1208 ExprResult Arg = TheCall->getArg(i); 1209 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1210 if (Arg.isInvalid()) 1211 return true; 1212 TheCall->setArg(i, Arg.get()); 1213 } 1214 1215 // Permute the arguments into a 'consistent' order. 1216 SmallVector<Expr*, 5> SubExprs; 1217 SubExprs.push_back(Ptr); 1218 switch (Form) { 1219 case Init: 1220 // Note, AtomicExpr::getVal1() has a special case for this atomic. 1221 SubExprs.push_back(TheCall->getArg(1)); // Val1 1222 break; 1223 case Load: 1224 SubExprs.push_back(TheCall->getArg(1)); // Order 1225 break; 1226 case Copy: 1227 case Arithmetic: 1228 case Xchg: 1229 SubExprs.push_back(TheCall->getArg(2)); // Order 1230 SubExprs.push_back(TheCall->getArg(1)); // Val1 1231 break; 1232 case GNUXchg: 1233 // Note, AtomicExpr::getVal2() has a special case for this atomic. 1234 SubExprs.push_back(TheCall->getArg(3)); // Order 1235 SubExprs.push_back(TheCall->getArg(1)); // Val1 1236 SubExprs.push_back(TheCall->getArg(2)); // Val2 1237 break; 1238 case C11CmpXchg: 1239 SubExprs.push_back(TheCall->getArg(3)); // Order 1240 SubExprs.push_back(TheCall->getArg(1)); // Val1 1241 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 1242 SubExprs.push_back(TheCall->getArg(2)); // Val2 1243 break; 1244 case GNUCmpXchg: 1245 SubExprs.push_back(TheCall->getArg(4)); // Order 1246 SubExprs.push_back(TheCall->getArg(1)); // Val1 1247 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 1248 SubExprs.push_back(TheCall->getArg(2)); // Val2 1249 SubExprs.push_back(TheCall->getArg(3)); // Weak 1250 break; 1251 } 1252 1253 if (SubExprs.size() >= 2 && Form != Init) { 1254 llvm::APSInt Result(32); 1255 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 1256 !isValidOrderingForOp(Result.getSExtValue(), Op)) 1257 Diag(SubExprs[1]->getLocStart(), 1258 diag::warn_atomic_op_has_invalid_memory_order) 1259 << SubExprs[1]->getSourceRange(); 1260 } 1261 1262 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 1263 SubExprs, ResultType, Op, 1264 TheCall->getRParenLoc()); 1265 1266 if ((Op == AtomicExpr::AO__c11_atomic_load || 1267 (Op == AtomicExpr::AO__c11_atomic_store)) && 1268 Context.AtomicUsesUnsupportedLibcall(AE)) 1269 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 1270 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 1271 1272 return AE; 1273 } 1274 1275 1276 /// checkBuiltinArgument - Given a call to a builtin function, perform 1277 /// normal type-checking on the given argument, updating the call in 1278 /// place. This is useful when a builtin function requires custom 1279 /// type-checking for some of its arguments but not necessarily all of 1280 /// them. 1281 /// 1282 /// Returns true on error. 1283 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 1284 FunctionDecl *Fn = E->getDirectCallee(); 1285 assert(Fn && "builtin call without direct callee!"); 1286 1287 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 1288 InitializedEntity Entity = 1289 InitializedEntity::InitializeParameter(S.Context, Param); 1290 1291 ExprResult Arg = E->getArg(0); 1292 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 1293 if (Arg.isInvalid()) 1294 return true; 1295 1296 E->setArg(ArgIndex, Arg.get()); 1297 return false; 1298 } 1299 1300 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 1301 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 1302 /// type of its first argument. The main ActOnCallExpr routines have already 1303 /// promoted the types of arguments because all of these calls are prototyped as 1304 /// void(...). 1305 /// 1306 /// This function goes through and does final semantic checking for these 1307 /// builtins, 1308 ExprResult 1309 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 1310 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 1311 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1312 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1313 1314 // Ensure that we have at least one argument to do type inference from. 1315 if (TheCall->getNumArgs() < 1) { 1316 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1317 << 0 << 1 << TheCall->getNumArgs() 1318 << TheCall->getCallee()->getSourceRange(); 1319 return ExprError(); 1320 } 1321 1322 // Inspect the first argument of the atomic builtin. This should always be 1323 // a pointer type, whose element is an integral scalar or pointer type. 1324 // Because it is a pointer type, we don't have to worry about any implicit 1325 // casts here. 1326 // FIXME: We don't allow floating point scalars as input. 1327 Expr *FirstArg = TheCall->getArg(0); 1328 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 1329 if (FirstArgResult.isInvalid()) 1330 return ExprError(); 1331 FirstArg = FirstArgResult.get(); 1332 TheCall->setArg(0, FirstArg); 1333 1334 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 1335 if (!pointerType) { 1336 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1337 << FirstArg->getType() << FirstArg->getSourceRange(); 1338 return ExprError(); 1339 } 1340 1341 QualType ValType = pointerType->getPointeeType(); 1342 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1343 !ValType->isBlockPointerType()) { 1344 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 1345 << FirstArg->getType() << FirstArg->getSourceRange(); 1346 return ExprError(); 1347 } 1348 1349 switch (ValType.getObjCLifetime()) { 1350 case Qualifiers::OCL_None: 1351 case Qualifiers::OCL_ExplicitNone: 1352 // okay 1353 break; 1354 1355 case Qualifiers::OCL_Weak: 1356 case Qualifiers::OCL_Strong: 1357 case Qualifiers::OCL_Autoreleasing: 1358 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1359 << ValType << FirstArg->getSourceRange(); 1360 return ExprError(); 1361 } 1362 1363 // Strip any qualifiers off ValType. 1364 ValType = ValType.getUnqualifiedType(); 1365 1366 // The majority of builtins return a value, but a few have special return 1367 // types, so allow them to override appropriately below. 1368 QualType ResultType = ValType; 1369 1370 // We need to figure out which concrete builtin this maps onto. For example, 1371 // __sync_fetch_and_add with a 2 byte object turns into 1372 // __sync_fetch_and_add_2. 1373 #define BUILTIN_ROW(x) \ 1374 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 1375 Builtin::BI##x##_8, Builtin::BI##x##_16 } 1376 1377 static const unsigned BuiltinIndices[][5] = { 1378 BUILTIN_ROW(__sync_fetch_and_add), 1379 BUILTIN_ROW(__sync_fetch_and_sub), 1380 BUILTIN_ROW(__sync_fetch_and_or), 1381 BUILTIN_ROW(__sync_fetch_and_and), 1382 BUILTIN_ROW(__sync_fetch_and_xor), 1383 1384 BUILTIN_ROW(__sync_add_and_fetch), 1385 BUILTIN_ROW(__sync_sub_and_fetch), 1386 BUILTIN_ROW(__sync_and_and_fetch), 1387 BUILTIN_ROW(__sync_or_and_fetch), 1388 BUILTIN_ROW(__sync_xor_and_fetch), 1389 1390 BUILTIN_ROW(__sync_val_compare_and_swap), 1391 BUILTIN_ROW(__sync_bool_compare_and_swap), 1392 BUILTIN_ROW(__sync_lock_test_and_set), 1393 BUILTIN_ROW(__sync_lock_release), 1394 BUILTIN_ROW(__sync_swap) 1395 }; 1396 #undef BUILTIN_ROW 1397 1398 // Determine the index of the size. 1399 unsigned SizeIndex; 1400 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1401 case 1: SizeIndex = 0; break; 1402 case 2: SizeIndex = 1; break; 1403 case 4: SizeIndex = 2; break; 1404 case 8: SizeIndex = 3; break; 1405 case 16: SizeIndex = 4; break; 1406 default: 1407 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1408 << FirstArg->getType() << FirstArg->getSourceRange(); 1409 return ExprError(); 1410 } 1411 1412 // Each of these builtins has one pointer argument, followed by some number of 1413 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1414 // that we ignore. Find out which row of BuiltinIndices to read from as well 1415 // as the number of fixed args. 1416 unsigned BuiltinID = FDecl->getBuiltinID(); 1417 unsigned BuiltinIndex, NumFixed = 1; 1418 switch (BuiltinID) { 1419 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1420 case Builtin::BI__sync_fetch_and_add: 1421 case Builtin::BI__sync_fetch_and_add_1: 1422 case Builtin::BI__sync_fetch_and_add_2: 1423 case Builtin::BI__sync_fetch_and_add_4: 1424 case Builtin::BI__sync_fetch_and_add_8: 1425 case Builtin::BI__sync_fetch_and_add_16: 1426 BuiltinIndex = 0; 1427 break; 1428 1429 case Builtin::BI__sync_fetch_and_sub: 1430 case Builtin::BI__sync_fetch_and_sub_1: 1431 case Builtin::BI__sync_fetch_and_sub_2: 1432 case Builtin::BI__sync_fetch_and_sub_4: 1433 case Builtin::BI__sync_fetch_and_sub_8: 1434 case Builtin::BI__sync_fetch_and_sub_16: 1435 BuiltinIndex = 1; 1436 break; 1437 1438 case Builtin::BI__sync_fetch_and_or: 1439 case Builtin::BI__sync_fetch_and_or_1: 1440 case Builtin::BI__sync_fetch_and_or_2: 1441 case Builtin::BI__sync_fetch_and_or_4: 1442 case Builtin::BI__sync_fetch_and_or_8: 1443 case Builtin::BI__sync_fetch_and_or_16: 1444 BuiltinIndex = 2; 1445 break; 1446 1447 case Builtin::BI__sync_fetch_and_and: 1448 case Builtin::BI__sync_fetch_and_and_1: 1449 case Builtin::BI__sync_fetch_and_and_2: 1450 case Builtin::BI__sync_fetch_and_and_4: 1451 case Builtin::BI__sync_fetch_and_and_8: 1452 case Builtin::BI__sync_fetch_and_and_16: 1453 BuiltinIndex = 3; 1454 break; 1455 1456 case Builtin::BI__sync_fetch_and_xor: 1457 case Builtin::BI__sync_fetch_and_xor_1: 1458 case Builtin::BI__sync_fetch_and_xor_2: 1459 case Builtin::BI__sync_fetch_and_xor_4: 1460 case Builtin::BI__sync_fetch_and_xor_8: 1461 case Builtin::BI__sync_fetch_and_xor_16: 1462 BuiltinIndex = 4; 1463 break; 1464 1465 case Builtin::BI__sync_add_and_fetch: 1466 case Builtin::BI__sync_add_and_fetch_1: 1467 case Builtin::BI__sync_add_and_fetch_2: 1468 case Builtin::BI__sync_add_and_fetch_4: 1469 case Builtin::BI__sync_add_and_fetch_8: 1470 case Builtin::BI__sync_add_and_fetch_16: 1471 BuiltinIndex = 5; 1472 break; 1473 1474 case Builtin::BI__sync_sub_and_fetch: 1475 case Builtin::BI__sync_sub_and_fetch_1: 1476 case Builtin::BI__sync_sub_and_fetch_2: 1477 case Builtin::BI__sync_sub_and_fetch_4: 1478 case Builtin::BI__sync_sub_and_fetch_8: 1479 case Builtin::BI__sync_sub_and_fetch_16: 1480 BuiltinIndex = 6; 1481 break; 1482 1483 case Builtin::BI__sync_and_and_fetch: 1484 case Builtin::BI__sync_and_and_fetch_1: 1485 case Builtin::BI__sync_and_and_fetch_2: 1486 case Builtin::BI__sync_and_and_fetch_4: 1487 case Builtin::BI__sync_and_and_fetch_8: 1488 case Builtin::BI__sync_and_and_fetch_16: 1489 BuiltinIndex = 7; 1490 break; 1491 1492 case Builtin::BI__sync_or_and_fetch: 1493 case Builtin::BI__sync_or_and_fetch_1: 1494 case Builtin::BI__sync_or_and_fetch_2: 1495 case Builtin::BI__sync_or_and_fetch_4: 1496 case Builtin::BI__sync_or_and_fetch_8: 1497 case Builtin::BI__sync_or_and_fetch_16: 1498 BuiltinIndex = 8; 1499 break; 1500 1501 case Builtin::BI__sync_xor_and_fetch: 1502 case Builtin::BI__sync_xor_and_fetch_1: 1503 case Builtin::BI__sync_xor_and_fetch_2: 1504 case Builtin::BI__sync_xor_and_fetch_4: 1505 case Builtin::BI__sync_xor_and_fetch_8: 1506 case Builtin::BI__sync_xor_and_fetch_16: 1507 BuiltinIndex = 9; 1508 break; 1509 1510 case Builtin::BI__sync_val_compare_and_swap: 1511 case Builtin::BI__sync_val_compare_and_swap_1: 1512 case Builtin::BI__sync_val_compare_and_swap_2: 1513 case Builtin::BI__sync_val_compare_and_swap_4: 1514 case Builtin::BI__sync_val_compare_and_swap_8: 1515 case Builtin::BI__sync_val_compare_and_swap_16: 1516 BuiltinIndex = 10; 1517 NumFixed = 2; 1518 break; 1519 1520 case Builtin::BI__sync_bool_compare_and_swap: 1521 case Builtin::BI__sync_bool_compare_and_swap_1: 1522 case Builtin::BI__sync_bool_compare_and_swap_2: 1523 case Builtin::BI__sync_bool_compare_and_swap_4: 1524 case Builtin::BI__sync_bool_compare_and_swap_8: 1525 case Builtin::BI__sync_bool_compare_and_swap_16: 1526 BuiltinIndex = 11; 1527 NumFixed = 2; 1528 ResultType = Context.BoolTy; 1529 break; 1530 1531 case Builtin::BI__sync_lock_test_and_set: 1532 case Builtin::BI__sync_lock_test_and_set_1: 1533 case Builtin::BI__sync_lock_test_and_set_2: 1534 case Builtin::BI__sync_lock_test_and_set_4: 1535 case Builtin::BI__sync_lock_test_and_set_8: 1536 case Builtin::BI__sync_lock_test_and_set_16: 1537 BuiltinIndex = 12; 1538 break; 1539 1540 case Builtin::BI__sync_lock_release: 1541 case Builtin::BI__sync_lock_release_1: 1542 case Builtin::BI__sync_lock_release_2: 1543 case Builtin::BI__sync_lock_release_4: 1544 case Builtin::BI__sync_lock_release_8: 1545 case Builtin::BI__sync_lock_release_16: 1546 BuiltinIndex = 13; 1547 NumFixed = 0; 1548 ResultType = Context.VoidTy; 1549 break; 1550 1551 case Builtin::BI__sync_swap: 1552 case Builtin::BI__sync_swap_1: 1553 case Builtin::BI__sync_swap_2: 1554 case Builtin::BI__sync_swap_4: 1555 case Builtin::BI__sync_swap_8: 1556 case Builtin::BI__sync_swap_16: 1557 BuiltinIndex = 14; 1558 break; 1559 } 1560 1561 // Now that we know how many fixed arguments we expect, first check that we 1562 // have at least that many. 1563 if (TheCall->getNumArgs() < 1+NumFixed) { 1564 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1565 << 0 << 1+NumFixed << TheCall->getNumArgs() 1566 << TheCall->getCallee()->getSourceRange(); 1567 return ExprError(); 1568 } 1569 1570 // Get the decl for the concrete builtin from this, we can tell what the 1571 // concrete integer type we should convert to is. 1572 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1573 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1574 FunctionDecl *NewBuiltinDecl; 1575 if (NewBuiltinID == BuiltinID) 1576 NewBuiltinDecl = FDecl; 1577 else { 1578 // Perform builtin lookup to avoid redeclaring it. 1579 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 1580 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 1581 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 1582 assert(Res.getFoundDecl()); 1583 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 1584 if (!NewBuiltinDecl) 1585 return ExprError(); 1586 } 1587 1588 // The first argument --- the pointer --- has a fixed type; we 1589 // deduce the types of the rest of the arguments accordingly. Walk 1590 // the remaining arguments, converting them to the deduced value type. 1591 for (unsigned i = 0; i != NumFixed; ++i) { 1592 ExprResult Arg = TheCall->getArg(i+1); 1593 1594 // GCC does an implicit conversion to the pointer or integer ValType. This 1595 // can fail in some cases (1i -> int**), check for this error case now. 1596 // Initialize the argument. 1597 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1598 ValType, /*consume*/ false); 1599 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1600 if (Arg.isInvalid()) 1601 return ExprError(); 1602 1603 // Okay, we have something that *can* be converted to the right type. Check 1604 // to see if there is a potentially weird extension going on here. This can 1605 // happen when you do an atomic operation on something like an char* and 1606 // pass in 42. The 42 gets converted to char. This is even more strange 1607 // for things like 45.123 -> char, etc. 1608 // FIXME: Do this check. 1609 TheCall->setArg(i+1, Arg.get()); 1610 } 1611 1612 ASTContext& Context = this->getASTContext(); 1613 1614 // Create a new DeclRefExpr to refer to the new decl. 1615 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1616 Context, 1617 DRE->getQualifierLoc(), 1618 SourceLocation(), 1619 NewBuiltinDecl, 1620 /*enclosing*/ false, 1621 DRE->getLocation(), 1622 Context.BuiltinFnTy, 1623 DRE->getValueKind()); 1624 1625 // Set the callee in the CallExpr. 1626 // FIXME: This loses syntactic information. 1627 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 1628 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 1629 CK_BuiltinFnToFnPtr); 1630 TheCall->setCallee(PromotedCall.get()); 1631 1632 // Change the result type of the call to match the original value type. This 1633 // is arbitrary, but the codegen for these builtins ins design to handle it 1634 // gracefully. 1635 TheCall->setType(ResultType); 1636 1637 return TheCallResult; 1638 } 1639 1640 /// CheckObjCString - Checks that the argument to the builtin 1641 /// CFString constructor is correct 1642 /// Note: It might also make sense to do the UTF-16 conversion here (would 1643 /// simplify the backend). 1644 bool Sema::CheckObjCString(Expr *Arg) { 1645 Arg = Arg->IgnoreParenCasts(); 1646 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1647 1648 if (!Literal || !Literal->isAscii()) { 1649 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1650 << Arg->getSourceRange(); 1651 return true; 1652 } 1653 1654 if (Literal->containsNonAsciiOrNull()) { 1655 StringRef String = Literal->getString(); 1656 unsigned NumBytes = String.size(); 1657 SmallVector<UTF16, 128> ToBuf(NumBytes); 1658 const UTF8 *FromPtr = (const UTF8 *)String.data(); 1659 UTF16 *ToPtr = &ToBuf[0]; 1660 1661 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1662 &ToPtr, ToPtr + NumBytes, 1663 strictConversion); 1664 // Check for conversion failure. 1665 if (Result != conversionOK) 1666 Diag(Arg->getLocStart(), 1667 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1668 } 1669 return false; 1670 } 1671 1672 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1673 /// Emit an error and return true on failure, return false on success. 1674 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1675 Expr *Fn = TheCall->getCallee(); 1676 if (TheCall->getNumArgs() > 2) { 1677 Diag(TheCall->getArg(2)->getLocStart(), 1678 diag::err_typecheck_call_too_many_args) 1679 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1680 << Fn->getSourceRange() 1681 << SourceRange(TheCall->getArg(2)->getLocStart(), 1682 (*(TheCall->arg_end()-1))->getLocEnd()); 1683 return true; 1684 } 1685 1686 if (TheCall->getNumArgs() < 2) { 1687 return Diag(TheCall->getLocEnd(), 1688 diag::err_typecheck_call_too_few_args_at_least) 1689 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1690 } 1691 1692 // Type-check the first argument normally. 1693 if (checkBuiltinArgument(*this, TheCall, 0)) 1694 return true; 1695 1696 // Determine whether the current function is variadic or not. 1697 BlockScopeInfo *CurBlock = getCurBlock(); 1698 bool isVariadic; 1699 if (CurBlock) 1700 isVariadic = CurBlock->TheDecl->isVariadic(); 1701 else if (FunctionDecl *FD = getCurFunctionDecl()) 1702 isVariadic = FD->isVariadic(); 1703 else 1704 isVariadic = getCurMethodDecl()->isVariadic(); 1705 1706 if (!isVariadic) { 1707 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1708 return true; 1709 } 1710 1711 // Verify that the second argument to the builtin is the last argument of the 1712 // current function or method. 1713 bool SecondArgIsLastNamedArgument = false; 1714 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1715 1716 // These are valid if SecondArgIsLastNamedArgument is false after the next 1717 // block. 1718 QualType Type; 1719 SourceLocation ParamLoc; 1720 1721 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1722 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1723 // FIXME: This isn't correct for methods (results in bogus warning). 1724 // Get the last formal in the current function. 1725 const ParmVarDecl *LastArg; 1726 if (CurBlock) 1727 LastArg = *(CurBlock->TheDecl->param_end()-1); 1728 else if (FunctionDecl *FD = getCurFunctionDecl()) 1729 LastArg = *(FD->param_end()-1); 1730 else 1731 LastArg = *(getCurMethodDecl()->param_end()-1); 1732 SecondArgIsLastNamedArgument = PV == LastArg; 1733 1734 Type = PV->getType(); 1735 ParamLoc = PV->getLocation(); 1736 } 1737 } 1738 1739 if (!SecondArgIsLastNamedArgument) 1740 Diag(TheCall->getArg(1)->getLocStart(), 1741 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1742 else if (Type->isReferenceType()) { 1743 Diag(Arg->getLocStart(), 1744 diag::warn_va_start_of_reference_type_is_undefined); 1745 Diag(ParamLoc, diag::note_parameter_type) << Type; 1746 } 1747 1748 TheCall->setType(Context.VoidTy); 1749 return false; 1750 } 1751 1752 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 1753 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 1754 // const char *named_addr); 1755 1756 Expr *Func = Call->getCallee(); 1757 1758 if (Call->getNumArgs() < 3) 1759 return Diag(Call->getLocEnd(), 1760 diag::err_typecheck_call_too_few_args_at_least) 1761 << 0 /*function call*/ << 3 << Call->getNumArgs(); 1762 1763 // Determine whether the current function is variadic or not. 1764 bool IsVariadic; 1765 if (BlockScopeInfo *CurBlock = getCurBlock()) 1766 IsVariadic = CurBlock->TheDecl->isVariadic(); 1767 else if (FunctionDecl *FD = getCurFunctionDecl()) 1768 IsVariadic = FD->isVariadic(); 1769 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1770 IsVariadic = MD->isVariadic(); 1771 else 1772 llvm_unreachable("unexpected statement type"); 1773 1774 if (!IsVariadic) { 1775 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1776 return true; 1777 } 1778 1779 // Type-check the first argument normally. 1780 if (checkBuiltinArgument(*this, Call, 0)) 1781 return true; 1782 1783 static const struct { 1784 unsigned ArgNo; 1785 QualType Type; 1786 } ArgumentTypes[] = { 1787 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 1788 { 2, Context.getSizeType() }, 1789 }; 1790 1791 for (const auto &AT : ArgumentTypes) { 1792 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 1793 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 1794 continue; 1795 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 1796 << Arg->getType() << AT.Type << 1 /* different class */ 1797 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 1798 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 1799 } 1800 1801 return false; 1802 } 1803 1804 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1805 /// friends. This is declared to take (...), so we have to check everything. 1806 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1807 if (TheCall->getNumArgs() < 2) 1808 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1809 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1810 if (TheCall->getNumArgs() > 2) 1811 return Diag(TheCall->getArg(2)->getLocStart(), 1812 diag::err_typecheck_call_too_many_args) 1813 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1814 << SourceRange(TheCall->getArg(2)->getLocStart(), 1815 (*(TheCall->arg_end()-1))->getLocEnd()); 1816 1817 ExprResult OrigArg0 = TheCall->getArg(0); 1818 ExprResult OrigArg1 = TheCall->getArg(1); 1819 1820 // Do standard promotions between the two arguments, returning their common 1821 // type. 1822 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1823 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1824 return true; 1825 1826 // Make sure any conversions are pushed back into the call; this is 1827 // type safe since unordered compare builtins are declared as "_Bool 1828 // foo(...)". 1829 TheCall->setArg(0, OrigArg0.get()); 1830 TheCall->setArg(1, OrigArg1.get()); 1831 1832 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1833 return false; 1834 1835 // If the common type isn't a real floating type, then the arguments were 1836 // invalid for this operation. 1837 if (Res.isNull() || !Res->isRealFloatingType()) 1838 return Diag(OrigArg0.get()->getLocStart(), 1839 diag::err_typecheck_call_invalid_ordered_compare) 1840 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1841 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1842 1843 return false; 1844 } 1845 1846 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1847 /// __builtin_isnan and friends. This is declared to take (...), so we have 1848 /// to check everything. We expect the last argument to be a floating point 1849 /// value. 1850 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1851 if (TheCall->getNumArgs() < NumArgs) 1852 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1853 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1854 if (TheCall->getNumArgs() > NumArgs) 1855 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1856 diag::err_typecheck_call_too_many_args) 1857 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1858 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1859 (*(TheCall->arg_end()-1))->getLocEnd()); 1860 1861 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1862 1863 if (OrigArg->isTypeDependent()) 1864 return false; 1865 1866 // This operation requires a non-_Complex floating-point number. 1867 if (!OrigArg->getType()->isRealFloatingType()) 1868 return Diag(OrigArg->getLocStart(), 1869 diag::err_typecheck_call_invalid_unary_fp) 1870 << OrigArg->getType() << OrigArg->getSourceRange(); 1871 1872 // If this is an implicit conversion from float -> double, remove it. 1873 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1874 Expr *CastArg = Cast->getSubExpr(); 1875 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1876 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1877 "promotion from float to double is the only expected cast here"); 1878 Cast->setSubExpr(nullptr); 1879 TheCall->setArg(NumArgs-1, CastArg); 1880 } 1881 } 1882 1883 return false; 1884 } 1885 1886 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1887 // This is declared to take (...), so we have to check everything. 1888 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1889 if (TheCall->getNumArgs() < 2) 1890 return ExprError(Diag(TheCall->getLocEnd(), 1891 diag::err_typecheck_call_too_few_args_at_least) 1892 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1893 << TheCall->getSourceRange()); 1894 1895 // Determine which of the following types of shufflevector we're checking: 1896 // 1) unary, vector mask: (lhs, mask) 1897 // 2) binary, vector mask: (lhs, rhs, mask) 1898 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1899 QualType resType = TheCall->getArg(0)->getType(); 1900 unsigned numElements = 0; 1901 1902 if (!TheCall->getArg(0)->isTypeDependent() && 1903 !TheCall->getArg(1)->isTypeDependent()) { 1904 QualType LHSType = TheCall->getArg(0)->getType(); 1905 QualType RHSType = TheCall->getArg(1)->getType(); 1906 1907 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 1908 return ExprError(Diag(TheCall->getLocStart(), 1909 diag::err_shufflevector_non_vector) 1910 << SourceRange(TheCall->getArg(0)->getLocStart(), 1911 TheCall->getArg(1)->getLocEnd())); 1912 1913 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1914 unsigned numResElements = TheCall->getNumArgs() - 2; 1915 1916 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1917 // with mask. If so, verify that RHS is an integer vector type with the 1918 // same number of elts as lhs. 1919 if (TheCall->getNumArgs() == 2) { 1920 if (!RHSType->hasIntegerRepresentation() || 1921 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1922 return ExprError(Diag(TheCall->getLocStart(), 1923 diag::err_shufflevector_incompatible_vector) 1924 << SourceRange(TheCall->getArg(1)->getLocStart(), 1925 TheCall->getArg(1)->getLocEnd())); 1926 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1927 return ExprError(Diag(TheCall->getLocStart(), 1928 diag::err_shufflevector_incompatible_vector) 1929 << SourceRange(TheCall->getArg(0)->getLocStart(), 1930 TheCall->getArg(1)->getLocEnd())); 1931 } else if (numElements != numResElements) { 1932 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1933 resType = Context.getVectorType(eltType, numResElements, 1934 VectorType::GenericVector); 1935 } 1936 } 1937 1938 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1939 if (TheCall->getArg(i)->isTypeDependent() || 1940 TheCall->getArg(i)->isValueDependent()) 1941 continue; 1942 1943 llvm::APSInt Result(32); 1944 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1945 return ExprError(Diag(TheCall->getLocStart(), 1946 diag::err_shufflevector_nonconstant_argument) 1947 << TheCall->getArg(i)->getSourceRange()); 1948 1949 // Allow -1 which will be translated to undef in the IR. 1950 if (Result.isSigned() && Result.isAllOnesValue()) 1951 continue; 1952 1953 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1954 return ExprError(Diag(TheCall->getLocStart(), 1955 diag::err_shufflevector_argument_too_large) 1956 << TheCall->getArg(i)->getSourceRange()); 1957 } 1958 1959 SmallVector<Expr*, 32> exprs; 1960 1961 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1962 exprs.push_back(TheCall->getArg(i)); 1963 TheCall->setArg(i, nullptr); 1964 } 1965 1966 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 1967 TheCall->getCallee()->getLocStart(), 1968 TheCall->getRParenLoc()); 1969 } 1970 1971 /// SemaConvertVectorExpr - Handle __builtin_convertvector 1972 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 1973 SourceLocation BuiltinLoc, 1974 SourceLocation RParenLoc) { 1975 ExprValueKind VK = VK_RValue; 1976 ExprObjectKind OK = OK_Ordinary; 1977 QualType DstTy = TInfo->getType(); 1978 QualType SrcTy = E->getType(); 1979 1980 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 1981 return ExprError(Diag(BuiltinLoc, 1982 diag::err_convertvector_non_vector) 1983 << E->getSourceRange()); 1984 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 1985 return ExprError(Diag(BuiltinLoc, 1986 diag::err_convertvector_non_vector_type)); 1987 1988 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 1989 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 1990 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 1991 if (SrcElts != DstElts) 1992 return ExprError(Diag(BuiltinLoc, 1993 diag::err_convertvector_incompatible_vector) 1994 << E->getSourceRange()); 1995 } 1996 1997 return new (Context) 1998 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 1999 } 2000 2001 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 2002 // This is declared to take (const void*, ...) and can take two 2003 // optional constant int args. 2004 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 2005 unsigned NumArgs = TheCall->getNumArgs(); 2006 2007 if (NumArgs > 3) 2008 return Diag(TheCall->getLocEnd(), 2009 diag::err_typecheck_call_too_many_args_at_most) 2010 << 0 /*function call*/ << 3 << NumArgs 2011 << TheCall->getSourceRange(); 2012 2013 // Argument 0 is checked for us and the remaining arguments must be 2014 // constant integers. 2015 for (unsigned i = 1; i != NumArgs; ++i) 2016 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 2017 return true; 2018 2019 return false; 2020 } 2021 2022 /// SemaBuiltinAssume - Handle __assume (MS Extension). 2023 // __assume does not evaluate its arguments, and should warn if its argument 2024 // has side effects. 2025 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 2026 Expr *Arg = TheCall->getArg(0); 2027 if (Arg->isInstantiationDependent()) return false; 2028 2029 if (Arg->HasSideEffects(Context)) 2030 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 2031 << Arg->getSourceRange(); 2032 2033 return false; 2034 } 2035 2036 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 2037 /// TheCall is a constant expression. 2038 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 2039 llvm::APSInt &Result) { 2040 Expr *Arg = TheCall->getArg(ArgNum); 2041 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2042 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2043 2044 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 2045 2046 if (!Arg->isIntegerConstantExpr(Result, Context)) 2047 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 2048 << FDecl->getDeclName() << Arg->getSourceRange(); 2049 2050 return false; 2051 } 2052 2053 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 2054 /// TheCall is a constant expression in the range [Low, High]. 2055 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 2056 int Low, int High) { 2057 llvm::APSInt Result; 2058 2059 // We can't check the value of a dependent argument. 2060 Expr *Arg = TheCall->getArg(ArgNum); 2061 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2062 return false; 2063 2064 // Check constant-ness first. 2065 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2066 return true; 2067 2068 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 2069 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 2070 << Low << High << Arg->getSourceRange(); 2071 2072 return false; 2073 } 2074 2075 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 2076 /// This checks that val is a constant 1. 2077 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 2078 Expr *Arg = TheCall->getArg(1); 2079 llvm::APSInt Result; 2080 2081 // TODO: This is less than ideal. Overload this to take a value. 2082 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2083 return true; 2084 2085 if (Result != 1) 2086 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 2087 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 2088 2089 return false; 2090 } 2091 2092 namespace { 2093 enum StringLiteralCheckType { 2094 SLCT_NotALiteral, 2095 SLCT_UncheckedLiteral, 2096 SLCT_CheckedLiteral 2097 }; 2098 } 2099 2100 // Determine if an expression is a string literal or constant string. 2101 // If this function returns false on the arguments to a function expecting a 2102 // format string, we will usually need to emit a warning. 2103 // True string literals are then checked by CheckFormatString. 2104 static StringLiteralCheckType 2105 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 2106 bool HasVAListArg, unsigned format_idx, 2107 unsigned firstDataArg, Sema::FormatStringType Type, 2108 Sema::VariadicCallType CallType, bool InFunctionCall, 2109 llvm::SmallBitVector &CheckedVarArgs) { 2110 tryAgain: 2111 if (E->isTypeDependent() || E->isValueDependent()) 2112 return SLCT_NotALiteral; 2113 2114 E = E->IgnoreParenCasts(); 2115 2116 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 2117 // Technically -Wformat-nonliteral does not warn about this case. 2118 // The behavior of printf and friends in this case is implementation 2119 // dependent. Ideally if the format string cannot be null then 2120 // it should have a 'nonnull' attribute in the function prototype. 2121 return SLCT_UncheckedLiteral; 2122 2123 switch (E->getStmtClass()) { 2124 case Stmt::BinaryConditionalOperatorClass: 2125 case Stmt::ConditionalOperatorClass: { 2126 // The expression is a literal if both sub-expressions were, and it was 2127 // completely checked only if both sub-expressions were checked. 2128 const AbstractConditionalOperator *C = 2129 cast<AbstractConditionalOperator>(E); 2130 StringLiteralCheckType Left = 2131 checkFormatStringExpr(S, C->getTrueExpr(), Args, 2132 HasVAListArg, format_idx, firstDataArg, 2133 Type, CallType, InFunctionCall, CheckedVarArgs); 2134 if (Left == SLCT_NotALiteral) 2135 return SLCT_NotALiteral; 2136 StringLiteralCheckType Right = 2137 checkFormatStringExpr(S, C->getFalseExpr(), Args, 2138 HasVAListArg, format_idx, firstDataArg, 2139 Type, CallType, InFunctionCall, CheckedVarArgs); 2140 return Left < Right ? Left : Right; 2141 } 2142 2143 case Stmt::ImplicitCastExprClass: { 2144 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 2145 goto tryAgain; 2146 } 2147 2148 case Stmt::OpaqueValueExprClass: 2149 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 2150 E = src; 2151 goto tryAgain; 2152 } 2153 return SLCT_NotALiteral; 2154 2155 case Stmt::PredefinedExprClass: 2156 // While __func__, etc., are technically not string literals, they 2157 // cannot contain format specifiers and thus are not a security 2158 // liability. 2159 return SLCT_UncheckedLiteral; 2160 2161 case Stmt::DeclRefExprClass: { 2162 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 2163 2164 // As an exception, do not flag errors for variables binding to 2165 // const string literals. 2166 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 2167 bool isConstant = false; 2168 QualType T = DR->getType(); 2169 2170 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 2171 isConstant = AT->getElementType().isConstant(S.Context); 2172 } else if (const PointerType *PT = T->getAs<PointerType>()) { 2173 isConstant = T.isConstant(S.Context) && 2174 PT->getPointeeType().isConstant(S.Context); 2175 } else if (T->isObjCObjectPointerType()) { 2176 // In ObjC, there is usually no "const ObjectPointer" type, 2177 // so don't check if the pointee type is constant. 2178 isConstant = T.isConstant(S.Context); 2179 } 2180 2181 if (isConstant) { 2182 if (const Expr *Init = VD->getAnyInitializer()) { 2183 // Look through initializers like const char c[] = { "foo" } 2184 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2185 if (InitList->isStringLiteralInit()) 2186 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 2187 } 2188 return checkFormatStringExpr(S, Init, Args, 2189 HasVAListArg, format_idx, 2190 firstDataArg, Type, CallType, 2191 /*InFunctionCall*/false, CheckedVarArgs); 2192 } 2193 } 2194 2195 // For vprintf* functions (i.e., HasVAListArg==true), we add a 2196 // special check to see if the format string is a function parameter 2197 // of the function calling the printf function. If the function 2198 // has an attribute indicating it is a printf-like function, then we 2199 // should suppress warnings concerning non-literals being used in a call 2200 // to a vprintf function. For example: 2201 // 2202 // void 2203 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 2204 // va_list ap; 2205 // va_start(ap, fmt); 2206 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 2207 // ... 2208 // } 2209 if (HasVAListArg) { 2210 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 2211 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 2212 int PVIndex = PV->getFunctionScopeIndex() + 1; 2213 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 2214 // adjust for implicit parameter 2215 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2216 if (MD->isInstance()) 2217 ++PVIndex; 2218 // We also check if the formats are compatible. 2219 // We can't pass a 'scanf' string to a 'printf' function. 2220 if (PVIndex == PVFormat->getFormatIdx() && 2221 Type == S.GetFormatStringType(PVFormat)) 2222 return SLCT_UncheckedLiteral; 2223 } 2224 } 2225 } 2226 } 2227 } 2228 2229 return SLCT_NotALiteral; 2230 } 2231 2232 case Stmt::CallExprClass: 2233 case Stmt::CXXMemberCallExprClass: { 2234 const CallExpr *CE = cast<CallExpr>(E); 2235 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 2236 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 2237 unsigned ArgIndex = FA->getFormatIdx(); 2238 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2239 if (MD->isInstance()) 2240 --ArgIndex; 2241 const Expr *Arg = CE->getArg(ArgIndex - 1); 2242 2243 return checkFormatStringExpr(S, Arg, Args, 2244 HasVAListArg, format_idx, firstDataArg, 2245 Type, CallType, InFunctionCall, 2246 CheckedVarArgs); 2247 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 2248 unsigned BuiltinID = FD->getBuiltinID(); 2249 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 2250 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 2251 const Expr *Arg = CE->getArg(0); 2252 return checkFormatStringExpr(S, Arg, Args, 2253 HasVAListArg, format_idx, 2254 firstDataArg, Type, CallType, 2255 InFunctionCall, CheckedVarArgs); 2256 } 2257 } 2258 } 2259 2260 return SLCT_NotALiteral; 2261 } 2262 case Stmt::ObjCStringLiteralClass: 2263 case Stmt::StringLiteralClass: { 2264 const StringLiteral *StrE = nullptr; 2265 2266 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 2267 StrE = ObjCFExpr->getString(); 2268 else 2269 StrE = cast<StringLiteral>(E); 2270 2271 if (StrE) { 2272 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg, 2273 Type, InFunctionCall, CallType, CheckedVarArgs); 2274 return SLCT_CheckedLiteral; 2275 } 2276 2277 return SLCT_NotALiteral; 2278 } 2279 2280 default: 2281 return SLCT_NotALiteral; 2282 } 2283 } 2284 2285 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 2286 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 2287 .Case("scanf", FST_Scanf) 2288 .Cases("printf", "printf0", FST_Printf) 2289 .Cases("NSString", "CFString", FST_NSString) 2290 .Case("strftime", FST_Strftime) 2291 .Case("strfmon", FST_Strfmon) 2292 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 2293 .Default(FST_Unknown); 2294 } 2295 2296 /// CheckFormatArguments - Check calls to printf and scanf (and similar 2297 /// functions) for correct use of format strings. 2298 /// Returns true if a format string has been fully checked. 2299 bool Sema::CheckFormatArguments(const FormatAttr *Format, 2300 ArrayRef<const Expr *> Args, 2301 bool IsCXXMember, 2302 VariadicCallType CallType, 2303 SourceLocation Loc, SourceRange Range, 2304 llvm::SmallBitVector &CheckedVarArgs) { 2305 FormatStringInfo FSI; 2306 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 2307 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 2308 FSI.FirstDataArg, GetFormatStringType(Format), 2309 CallType, Loc, Range, CheckedVarArgs); 2310 return false; 2311 } 2312 2313 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 2314 bool HasVAListArg, unsigned format_idx, 2315 unsigned firstDataArg, FormatStringType Type, 2316 VariadicCallType CallType, 2317 SourceLocation Loc, SourceRange Range, 2318 llvm::SmallBitVector &CheckedVarArgs) { 2319 // CHECK: printf/scanf-like function is called with no format string. 2320 if (format_idx >= Args.size()) { 2321 Diag(Loc, diag::warn_missing_format_string) << Range; 2322 return false; 2323 } 2324 2325 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 2326 2327 // CHECK: format string is not a string literal. 2328 // 2329 // Dynamically generated format strings are difficult to 2330 // automatically vet at compile time. Requiring that format strings 2331 // are string literals: (1) permits the checking of format strings by 2332 // the compiler and thereby (2) can practically remove the source of 2333 // many format string exploits. 2334 2335 // Format string can be either ObjC string (e.g. @"%d") or 2336 // C string (e.g. "%d") 2337 // ObjC string uses the same format specifiers as C string, so we can use 2338 // the same format string checking logic for both ObjC and C strings. 2339 StringLiteralCheckType CT = 2340 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 2341 format_idx, firstDataArg, Type, CallType, 2342 /*IsFunctionCall*/true, CheckedVarArgs); 2343 if (CT != SLCT_NotALiteral) 2344 // Literal format string found, check done! 2345 return CT == SLCT_CheckedLiteral; 2346 2347 // Strftime is particular as it always uses a single 'time' argument, 2348 // so it is safe to pass a non-literal string. 2349 if (Type == FST_Strftime) 2350 return false; 2351 2352 // Do not emit diag when the string param is a macro expansion and the 2353 // format is either NSString or CFString. This is a hack to prevent 2354 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 2355 // which are usually used in place of NS and CF string literals. 2356 if (Type == FST_NSString && 2357 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 2358 return false; 2359 2360 // If there are no arguments specified, warn with -Wformat-security, otherwise 2361 // warn only with -Wformat-nonliteral. 2362 if (Args.size() == firstDataArg) 2363 Diag(Args[format_idx]->getLocStart(), 2364 diag::warn_format_nonliteral_noargs) 2365 << OrigFormatExpr->getSourceRange(); 2366 else 2367 Diag(Args[format_idx]->getLocStart(), 2368 diag::warn_format_nonliteral) 2369 << OrigFormatExpr->getSourceRange(); 2370 return false; 2371 } 2372 2373 namespace { 2374 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 2375 protected: 2376 Sema &S; 2377 const StringLiteral *FExpr; 2378 const Expr *OrigFormatExpr; 2379 const unsigned FirstDataArg; 2380 const unsigned NumDataArgs; 2381 const char *Beg; // Start of format string. 2382 const bool HasVAListArg; 2383 ArrayRef<const Expr *> Args; 2384 unsigned FormatIdx; 2385 llvm::SmallBitVector CoveredArgs; 2386 bool usesPositionalArgs; 2387 bool atFirstArg; 2388 bool inFunctionCall; 2389 Sema::VariadicCallType CallType; 2390 llvm::SmallBitVector &CheckedVarArgs; 2391 public: 2392 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 2393 const Expr *origFormatExpr, unsigned firstDataArg, 2394 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2395 ArrayRef<const Expr *> Args, 2396 unsigned formatIdx, bool inFunctionCall, 2397 Sema::VariadicCallType callType, 2398 llvm::SmallBitVector &CheckedVarArgs) 2399 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 2400 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 2401 Beg(beg), HasVAListArg(hasVAListArg), 2402 Args(Args), FormatIdx(formatIdx), 2403 usesPositionalArgs(false), atFirstArg(true), 2404 inFunctionCall(inFunctionCall), CallType(callType), 2405 CheckedVarArgs(CheckedVarArgs) { 2406 CoveredArgs.resize(numDataArgs); 2407 CoveredArgs.reset(); 2408 } 2409 2410 void DoneProcessing(); 2411 2412 void HandleIncompleteSpecifier(const char *startSpecifier, 2413 unsigned specifierLen) override; 2414 2415 void HandleInvalidLengthModifier( 2416 const analyze_format_string::FormatSpecifier &FS, 2417 const analyze_format_string::ConversionSpecifier &CS, 2418 const char *startSpecifier, unsigned specifierLen, 2419 unsigned DiagID); 2420 2421 void HandleNonStandardLengthModifier( 2422 const analyze_format_string::FormatSpecifier &FS, 2423 const char *startSpecifier, unsigned specifierLen); 2424 2425 void HandleNonStandardConversionSpecifier( 2426 const analyze_format_string::ConversionSpecifier &CS, 2427 const char *startSpecifier, unsigned specifierLen); 2428 2429 void HandlePosition(const char *startPos, unsigned posLen) override; 2430 2431 void HandleInvalidPosition(const char *startSpecifier, 2432 unsigned specifierLen, 2433 analyze_format_string::PositionContext p) override; 2434 2435 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 2436 2437 void HandleNullChar(const char *nullCharacter) override; 2438 2439 template <typename Range> 2440 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 2441 const Expr *ArgumentExpr, 2442 PartialDiagnostic PDiag, 2443 SourceLocation StringLoc, 2444 bool IsStringLocation, Range StringRange, 2445 ArrayRef<FixItHint> Fixit = None); 2446 2447 protected: 2448 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 2449 const char *startSpec, 2450 unsigned specifierLen, 2451 const char *csStart, unsigned csLen); 2452 2453 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 2454 const char *startSpec, 2455 unsigned specifierLen); 2456 2457 SourceRange getFormatStringRange(); 2458 CharSourceRange getSpecifierRange(const char *startSpecifier, 2459 unsigned specifierLen); 2460 SourceLocation getLocationOfByte(const char *x); 2461 2462 const Expr *getDataArg(unsigned i) const; 2463 2464 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 2465 const analyze_format_string::ConversionSpecifier &CS, 2466 const char *startSpecifier, unsigned specifierLen, 2467 unsigned argIndex); 2468 2469 template <typename Range> 2470 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 2471 bool IsStringLocation, Range StringRange, 2472 ArrayRef<FixItHint> Fixit = None); 2473 }; 2474 } 2475 2476 SourceRange CheckFormatHandler::getFormatStringRange() { 2477 return OrigFormatExpr->getSourceRange(); 2478 } 2479 2480 CharSourceRange CheckFormatHandler:: 2481 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2482 SourceLocation Start = getLocationOfByte(startSpecifier); 2483 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2484 2485 // Advance the end SourceLocation by one due to half-open ranges. 2486 End = End.getLocWithOffset(1); 2487 2488 return CharSourceRange::getCharRange(Start, End); 2489 } 2490 2491 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2492 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2493 } 2494 2495 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2496 unsigned specifierLen){ 2497 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2498 getLocationOfByte(startSpecifier), 2499 /*IsStringLocation*/true, 2500 getSpecifierRange(startSpecifier, specifierLen)); 2501 } 2502 2503 void CheckFormatHandler::HandleInvalidLengthModifier( 2504 const analyze_format_string::FormatSpecifier &FS, 2505 const analyze_format_string::ConversionSpecifier &CS, 2506 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 2507 using namespace analyze_format_string; 2508 2509 const LengthModifier &LM = FS.getLengthModifier(); 2510 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2511 2512 // See if we know how to fix this length modifier. 2513 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2514 if (FixedLM) { 2515 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2516 getLocationOfByte(LM.getStart()), 2517 /*IsStringLocation*/true, 2518 getSpecifierRange(startSpecifier, specifierLen)); 2519 2520 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2521 << FixedLM->toString() 2522 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2523 2524 } else { 2525 FixItHint Hint; 2526 if (DiagID == diag::warn_format_nonsensical_length) 2527 Hint = FixItHint::CreateRemoval(LMRange); 2528 2529 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2530 getLocationOfByte(LM.getStart()), 2531 /*IsStringLocation*/true, 2532 getSpecifierRange(startSpecifier, specifierLen), 2533 Hint); 2534 } 2535 } 2536 2537 void CheckFormatHandler::HandleNonStandardLengthModifier( 2538 const analyze_format_string::FormatSpecifier &FS, 2539 const char *startSpecifier, unsigned specifierLen) { 2540 using namespace analyze_format_string; 2541 2542 const LengthModifier &LM = FS.getLengthModifier(); 2543 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2544 2545 // See if we know how to fix this length modifier. 2546 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2547 if (FixedLM) { 2548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2549 << LM.toString() << 0, 2550 getLocationOfByte(LM.getStart()), 2551 /*IsStringLocation*/true, 2552 getSpecifierRange(startSpecifier, specifierLen)); 2553 2554 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2555 << FixedLM->toString() 2556 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2557 2558 } else { 2559 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2560 << LM.toString() << 0, 2561 getLocationOfByte(LM.getStart()), 2562 /*IsStringLocation*/true, 2563 getSpecifierRange(startSpecifier, specifierLen)); 2564 } 2565 } 2566 2567 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2568 const analyze_format_string::ConversionSpecifier &CS, 2569 const char *startSpecifier, unsigned specifierLen) { 2570 using namespace analyze_format_string; 2571 2572 // See if we know how to fix this conversion specifier. 2573 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 2574 if (FixedCS) { 2575 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2576 << CS.toString() << /*conversion specifier*/1, 2577 getLocationOfByte(CS.getStart()), 2578 /*IsStringLocation*/true, 2579 getSpecifierRange(startSpecifier, specifierLen)); 2580 2581 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 2582 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 2583 << FixedCS->toString() 2584 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 2585 } else { 2586 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2587 << CS.toString() << /*conversion specifier*/1, 2588 getLocationOfByte(CS.getStart()), 2589 /*IsStringLocation*/true, 2590 getSpecifierRange(startSpecifier, specifierLen)); 2591 } 2592 } 2593 2594 void CheckFormatHandler::HandlePosition(const char *startPos, 2595 unsigned posLen) { 2596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2597 getLocationOfByte(startPos), 2598 /*IsStringLocation*/true, 2599 getSpecifierRange(startPos, posLen)); 2600 } 2601 2602 void 2603 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2604 analyze_format_string::PositionContext p) { 2605 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2606 << (unsigned) p, 2607 getLocationOfByte(startPos), /*IsStringLocation*/true, 2608 getSpecifierRange(startPos, posLen)); 2609 } 2610 2611 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2612 unsigned posLen) { 2613 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 2614 getLocationOfByte(startPos), 2615 /*IsStringLocation*/true, 2616 getSpecifierRange(startPos, posLen)); 2617 } 2618 2619 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 2620 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 2621 // The presence of a null character is likely an error. 2622 EmitFormatDiagnostic( 2623 S.PDiag(diag::warn_printf_format_string_contains_null_char), 2624 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 2625 getFormatStringRange()); 2626 } 2627 } 2628 2629 // Note that this may return NULL if there was an error parsing or building 2630 // one of the argument expressions. 2631 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 2632 return Args[FirstDataArg + i]; 2633 } 2634 2635 void CheckFormatHandler::DoneProcessing() { 2636 // Does the number of data arguments exceed the number of 2637 // format conversions in the format string? 2638 if (!HasVAListArg) { 2639 // Find any arguments that weren't covered. 2640 CoveredArgs.flip(); 2641 signed notCoveredArg = CoveredArgs.find_first(); 2642 if (notCoveredArg >= 0) { 2643 assert((unsigned)notCoveredArg < NumDataArgs); 2644 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 2645 SourceLocation Loc = E->getLocStart(); 2646 if (!S.getSourceManager().isInSystemMacro(Loc)) { 2647 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 2648 Loc, /*IsStringLocation*/false, 2649 getFormatStringRange()); 2650 } 2651 } 2652 } 2653 } 2654 } 2655 2656 bool 2657 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2658 SourceLocation Loc, 2659 const char *startSpec, 2660 unsigned specifierLen, 2661 const char *csStart, 2662 unsigned csLen) { 2663 2664 bool keepGoing = true; 2665 if (argIndex < NumDataArgs) { 2666 // Consider the argument coverered, even though the specifier doesn't 2667 // make sense. 2668 CoveredArgs.set(argIndex); 2669 } 2670 else { 2671 // If argIndex exceeds the number of data arguments we 2672 // don't issue a warning because that is just a cascade of warnings (and 2673 // they may have intended '%%' anyway). We don't want to continue processing 2674 // the format string after this point, however, as we will like just get 2675 // gibberish when trying to match arguments. 2676 keepGoing = false; 2677 } 2678 2679 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2680 << StringRef(csStart, csLen), 2681 Loc, /*IsStringLocation*/true, 2682 getSpecifierRange(startSpec, specifierLen)); 2683 2684 return keepGoing; 2685 } 2686 2687 void 2688 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2689 const char *startSpec, 2690 unsigned specifierLen) { 2691 EmitFormatDiagnostic( 2692 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2693 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2694 } 2695 2696 bool 2697 CheckFormatHandler::CheckNumArgs( 2698 const analyze_format_string::FormatSpecifier &FS, 2699 const analyze_format_string::ConversionSpecifier &CS, 2700 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2701 2702 if (argIndex >= NumDataArgs) { 2703 PartialDiagnostic PDiag = FS.usesPositionalArg() 2704 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2705 << (argIndex+1) << NumDataArgs) 2706 : S.PDiag(diag::warn_printf_insufficient_data_args); 2707 EmitFormatDiagnostic( 2708 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2709 getSpecifierRange(startSpecifier, specifierLen)); 2710 return false; 2711 } 2712 return true; 2713 } 2714 2715 template<typename Range> 2716 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2717 SourceLocation Loc, 2718 bool IsStringLocation, 2719 Range StringRange, 2720 ArrayRef<FixItHint> FixIt) { 2721 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2722 Loc, IsStringLocation, StringRange, FixIt); 2723 } 2724 2725 /// \brief If the format string is not within the funcion call, emit a note 2726 /// so that the function call and string are in diagnostic messages. 2727 /// 2728 /// \param InFunctionCall if true, the format string is within the function 2729 /// call and only one diagnostic message will be produced. Otherwise, an 2730 /// extra note will be emitted pointing to location of the format string. 2731 /// 2732 /// \param ArgumentExpr the expression that is passed as the format string 2733 /// argument in the function call. Used for getting locations when two 2734 /// diagnostics are emitted. 2735 /// 2736 /// \param PDiag the callee should already have provided any strings for the 2737 /// diagnostic message. This function only adds locations and fixits 2738 /// to diagnostics. 2739 /// 2740 /// \param Loc primary location for diagnostic. If two diagnostics are 2741 /// required, one will be at Loc and a new SourceLocation will be created for 2742 /// the other one. 2743 /// 2744 /// \param IsStringLocation if true, Loc points to the format string should be 2745 /// used for the note. Otherwise, Loc points to the argument list and will 2746 /// be used with PDiag. 2747 /// 2748 /// \param StringRange some or all of the string to highlight. This is 2749 /// templated so it can accept either a CharSourceRange or a SourceRange. 2750 /// 2751 /// \param FixIt optional fix it hint for the format string. 2752 template<typename Range> 2753 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2754 const Expr *ArgumentExpr, 2755 PartialDiagnostic PDiag, 2756 SourceLocation Loc, 2757 bool IsStringLocation, 2758 Range StringRange, 2759 ArrayRef<FixItHint> FixIt) { 2760 if (InFunctionCall) { 2761 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 2762 D << StringRange; 2763 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2764 I != E; ++I) { 2765 D << *I; 2766 } 2767 } else { 2768 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2769 << ArgumentExpr->getSourceRange(); 2770 2771 const Sema::SemaDiagnosticBuilder &Note = 2772 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2773 diag::note_format_string_defined); 2774 2775 Note << StringRange; 2776 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2777 I != E; ++I) { 2778 Note << *I; 2779 } 2780 } 2781 } 2782 2783 //===--- CHECK: Printf format string checking ------------------------------===// 2784 2785 namespace { 2786 class CheckPrintfHandler : public CheckFormatHandler { 2787 bool ObjCContext; 2788 public: 2789 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2790 const Expr *origFormatExpr, unsigned firstDataArg, 2791 unsigned numDataArgs, bool isObjC, 2792 const char *beg, bool hasVAListArg, 2793 ArrayRef<const Expr *> Args, 2794 unsigned formatIdx, bool inFunctionCall, 2795 Sema::VariadicCallType CallType, 2796 llvm::SmallBitVector &CheckedVarArgs) 2797 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2798 numDataArgs, beg, hasVAListArg, Args, 2799 formatIdx, inFunctionCall, CallType, CheckedVarArgs), 2800 ObjCContext(isObjC) 2801 {} 2802 2803 2804 bool HandleInvalidPrintfConversionSpecifier( 2805 const analyze_printf::PrintfSpecifier &FS, 2806 const char *startSpecifier, 2807 unsigned specifierLen) override; 2808 2809 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2810 const char *startSpecifier, 2811 unsigned specifierLen) override; 2812 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2813 const char *StartSpecifier, 2814 unsigned SpecifierLen, 2815 const Expr *E); 2816 2817 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2818 const char *startSpecifier, unsigned specifierLen); 2819 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2820 const analyze_printf::OptionalAmount &Amt, 2821 unsigned type, 2822 const char *startSpecifier, unsigned specifierLen); 2823 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2824 const analyze_printf::OptionalFlag &flag, 2825 const char *startSpecifier, unsigned specifierLen); 2826 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2827 const analyze_printf::OptionalFlag &ignoredFlag, 2828 const analyze_printf::OptionalFlag &flag, 2829 const char *startSpecifier, unsigned specifierLen); 2830 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 2831 const Expr *E); 2832 2833 }; 2834 } 2835 2836 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2837 const analyze_printf::PrintfSpecifier &FS, 2838 const char *startSpecifier, 2839 unsigned specifierLen) { 2840 const analyze_printf::PrintfConversionSpecifier &CS = 2841 FS.getConversionSpecifier(); 2842 2843 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2844 getLocationOfByte(CS.getStart()), 2845 startSpecifier, specifierLen, 2846 CS.getStart(), CS.getLength()); 2847 } 2848 2849 bool CheckPrintfHandler::HandleAmount( 2850 const analyze_format_string::OptionalAmount &Amt, 2851 unsigned k, const char *startSpecifier, 2852 unsigned specifierLen) { 2853 2854 if (Amt.hasDataArgument()) { 2855 if (!HasVAListArg) { 2856 unsigned argIndex = Amt.getArgIndex(); 2857 if (argIndex >= NumDataArgs) { 2858 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2859 << k, 2860 getLocationOfByte(Amt.getStart()), 2861 /*IsStringLocation*/true, 2862 getSpecifierRange(startSpecifier, specifierLen)); 2863 // Don't do any more checking. We will just emit 2864 // spurious errors. 2865 return false; 2866 } 2867 2868 // Type check the data argument. It should be an 'int'. 2869 // Although not in conformance with C99, we also allow the argument to be 2870 // an 'unsigned int' as that is a reasonably safe case. GCC also 2871 // doesn't emit a warning for that case. 2872 CoveredArgs.set(argIndex); 2873 const Expr *Arg = getDataArg(argIndex); 2874 if (!Arg) 2875 return false; 2876 2877 QualType T = Arg->getType(); 2878 2879 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 2880 assert(AT.isValid()); 2881 2882 if (!AT.matchesType(S.Context, T)) { 2883 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2884 << k << AT.getRepresentativeTypeName(S.Context) 2885 << T << Arg->getSourceRange(), 2886 getLocationOfByte(Amt.getStart()), 2887 /*IsStringLocation*/true, 2888 getSpecifierRange(startSpecifier, specifierLen)); 2889 // Don't do any more checking. We will just emit 2890 // spurious errors. 2891 return false; 2892 } 2893 } 2894 } 2895 return true; 2896 } 2897 2898 void CheckPrintfHandler::HandleInvalidAmount( 2899 const analyze_printf::PrintfSpecifier &FS, 2900 const analyze_printf::OptionalAmount &Amt, 2901 unsigned type, 2902 const char *startSpecifier, 2903 unsigned specifierLen) { 2904 const analyze_printf::PrintfConversionSpecifier &CS = 2905 FS.getConversionSpecifier(); 2906 2907 FixItHint fixit = 2908 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2909 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2910 Amt.getConstantLength())) 2911 : FixItHint(); 2912 2913 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2914 << type << CS.toString(), 2915 getLocationOfByte(Amt.getStart()), 2916 /*IsStringLocation*/true, 2917 getSpecifierRange(startSpecifier, specifierLen), 2918 fixit); 2919 } 2920 2921 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2922 const analyze_printf::OptionalFlag &flag, 2923 const char *startSpecifier, 2924 unsigned specifierLen) { 2925 // Warn about pointless flag with a fixit removal. 2926 const analyze_printf::PrintfConversionSpecifier &CS = 2927 FS.getConversionSpecifier(); 2928 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2929 << flag.toString() << CS.toString(), 2930 getLocationOfByte(flag.getPosition()), 2931 /*IsStringLocation*/true, 2932 getSpecifierRange(startSpecifier, specifierLen), 2933 FixItHint::CreateRemoval( 2934 getSpecifierRange(flag.getPosition(), 1))); 2935 } 2936 2937 void CheckPrintfHandler::HandleIgnoredFlag( 2938 const analyze_printf::PrintfSpecifier &FS, 2939 const analyze_printf::OptionalFlag &ignoredFlag, 2940 const analyze_printf::OptionalFlag &flag, 2941 const char *startSpecifier, 2942 unsigned specifierLen) { 2943 // Warn about ignored flag with a fixit removal. 2944 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2945 << ignoredFlag.toString() << flag.toString(), 2946 getLocationOfByte(ignoredFlag.getPosition()), 2947 /*IsStringLocation*/true, 2948 getSpecifierRange(startSpecifier, specifierLen), 2949 FixItHint::CreateRemoval( 2950 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2951 } 2952 2953 // Determines if the specified is a C++ class or struct containing 2954 // a member with the specified name and kind (e.g. a CXXMethodDecl named 2955 // "c_str()"). 2956 template<typename MemberKind> 2957 static llvm::SmallPtrSet<MemberKind*, 1> 2958 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 2959 const RecordType *RT = Ty->getAs<RecordType>(); 2960 llvm::SmallPtrSet<MemberKind*, 1> Results; 2961 2962 if (!RT) 2963 return Results; 2964 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2965 if (!RD || !RD->getDefinition()) 2966 return Results; 2967 2968 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 2969 Sema::LookupMemberName); 2970 R.suppressDiagnostics(); 2971 2972 // We just need to include all members of the right kind turned up by the 2973 // filter, at this point. 2974 if (S.LookupQualifiedName(R, RT->getDecl())) 2975 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2976 NamedDecl *decl = (*I)->getUnderlyingDecl(); 2977 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 2978 Results.insert(FK); 2979 } 2980 return Results; 2981 } 2982 2983 /// Check if we could call '.c_str()' on an object. 2984 /// 2985 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 2986 /// allow the call, or if it would be ambiguous). 2987 bool Sema::hasCStrMethod(const Expr *E) { 2988 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 2989 MethodSet Results = 2990 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 2991 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 2992 MI != ME; ++MI) 2993 if ((*MI)->getMinRequiredArguments() == 0) 2994 return true; 2995 return false; 2996 } 2997 2998 // Check if a (w)string was passed when a (w)char* was needed, and offer a 2999 // better diagnostic if so. AT is assumed to be valid. 3000 // Returns true when a c_str() conversion method is found. 3001 bool CheckPrintfHandler::checkForCStrMembers( 3002 const analyze_printf::ArgType &AT, const Expr *E) { 3003 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 3004 3005 MethodSet Results = 3006 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 3007 3008 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 3009 MI != ME; ++MI) { 3010 const CXXMethodDecl *Method = *MI; 3011 if (Method->getMinRequiredArguments() == 0 && 3012 AT.matchesType(S.Context, Method->getReturnType())) { 3013 // FIXME: Suggest parens if the expression needs them. 3014 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 3015 S.Diag(E->getLocStart(), diag::note_printf_c_str) 3016 << "c_str()" 3017 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 3018 return true; 3019 } 3020 } 3021 3022 return false; 3023 } 3024 3025 bool 3026 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 3027 &FS, 3028 const char *startSpecifier, 3029 unsigned specifierLen) { 3030 3031 using namespace analyze_format_string; 3032 using namespace analyze_printf; 3033 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 3034 3035 if (FS.consumesDataArgument()) { 3036 if (atFirstArg) { 3037 atFirstArg = false; 3038 usesPositionalArgs = FS.usesPositionalArg(); 3039 } 3040 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3041 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3042 startSpecifier, specifierLen); 3043 return false; 3044 } 3045 } 3046 3047 // First check if the field width, precision, and conversion specifier 3048 // have matching data arguments. 3049 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 3050 startSpecifier, specifierLen)) { 3051 return false; 3052 } 3053 3054 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 3055 startSpecifier, specifierLen)) { 3056 return false; 3057 } 3058 3059 if (!CS.consumesDataArgument()) { 3060 // FIXME: Technically specifying a precision or field width here 3061 // makes no sense. Worth issuing a warning at some point. 3062 return true; 3063 } 3064 3065 // Consume the argument. 3066 unsigned argIndex = FS.getArgIndex(); 3067 if (argIndex < NumDataArgs) { 3068 // The check to see if the argIndex is valid will come later. 3069 // We set the bit here because we may exit early from this 3070 // function if we encounter some other error. 3071 CoveredArgs.set(argIndex); 3072 } 3073 3074 // Check for using an Objective-C specific conversion specifier 3075 // in a non-ObjC literal. 3076 if (!ObjCContext && CS.isObjCArg()) { 3077 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 3078 specifierLen); 3079 } 3080 3081 // Check for invalid use of field width 3082 if (!FS.hasValidFieldWidth()) { 3083 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 3084 startSpecifier, specifierLen); 3085 } 3086 3087 // Check for invalid use of precision 3088 if (!FS.hasValidPrecision()) { 3089 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 3090 startSpecifier, specifierLen); 3091 } 3092 3093 // Check each flag does not conflict with any other component. 3094 if (!FS.hasValidThousandsGroupingPrefix()) 3095 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 3096 if (!FS.hasValidLeadingZeros()) 3097 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 3098 if (!FS.hasValidPlusPrefix()) 3099 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 3100 if (!FS.hasValidSpacePrefix()) 3101 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 3102 if (!FS.hasValidAlternativeForm()) 3103 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 3104 if (!FS.hasValidLeftJustified()) 3105 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 3106 3107 // Check that flags are not ignored by another flag 3108 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 3109 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 3110 startSpecifier, specifierLen); 3111 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 3112 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 3113 startSpecifier, specifierLen); 3114 3115 // Check the length modifier is valid with the given conversion specifier. 3116 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3117 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3118 diag::warn_format_nonsensical_length); 3119 else if (!FS.hasStandardLengthModifier()) 3120 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3121 else if (!FS.hasStandardLengthConversionCombination()) 3122 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3123 diag::warn_format_non_standard_conversion_spec); 3124 3125 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3126 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3127 3128 // The remaining checks depend on the data arguments. 3129 if (HasVAListArg) 3130 return true; 3131 3132 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3133 return false; 3134 3135 const Expr *Arg = getDataArg(argIndex); 3136 if (!Arg) 3137 return true; 3138 3139 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 3140 } 3141 3142 static bool requiresParensToAddCast(const Expr *E) { 3143 // FIXME: We should have a general way to reason about operator 3144 // precedence and whether parens are actually needed here. 3145 // Take care of a few common cases where they aren't. 3146 const Expr *Inside = E->IgnoreImpCasts(); 3147 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 3148 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 3149 3150 switch (Inside->getStmtClass()) { 3151 case Stmt::ArraySubscriptExprClass: 3152 case Stmt::CallExprClass: 3153 case Stmt::CharacterLiteralClass: 3154 case Stmt::CXXBoolLiteralExprClass: 3155 case Stmt::DeclRefExprClass: 3156 case Stmt::FloatingLiteralClass: 3157 case Stmt::IntegerLiteralClass: 3158 case Stmt::MemberExprClass: 3159 case Stmt::ObjCArrayLiteralClass: 3160 case Stmt::ObjCBoolLiteralExprClass: 3161 case Stmt::ObjCBoxedExprClass: 3162 case Stmt::ObjCDictionaryLiteralClass: 3163 case Stmt::ObjCEncodeExprClass: 3164 case Stmt::ObjCIvarRefExprClass: 3165 case Stmt::ObjCMessageExprClass: 3166 case Stmt::ObjCPropertyRefExprClass: 3167 case Stmt::ObjCStringLiteralClass: 3168 case Stmt::ObjCSubscriptRefExprClass: 3169 case Stmt::ParenExprClass: 3170 case Stmt::StringLiteralClass: 3171 case Stmt::UnaryOperatorClass: 3172 return false; 3173 default: 3174 return true; 3175 } 3176 } 3177 3178 bool 3179 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3180 const char *StartSpecifier, 3181 unsigned SpecifierLen, 3182 const Expr *E) { 3183 using namespace analyze_format_string; 3184 using namespace analyze_printf; 3185 // Now type check the data expression that matches the 3186 // format specifier. 3187 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 3188 ObjCContext); 3189 if (!AT.isValid()) 3190 return true; 3191 3192 QualType ExprTy = E->getType(); 3193 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 3194 ExprTy = TET->getUnderlyingExpr()->getType(); 3195 } 3196 3197 if (AT.matchesType(S.Context, ExprTy)) 3198 return true; 3199 3200 // Look through argument promotions for our error message's reported type. 3201 // This includes the integral and floating promotions, but excludes array 3202 // and function pointer decay; seeing that an argument intended to be a 3203 // string has type 'char [6]' is probably more confusing than 'char *'. 3204 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3205 if (ICE->getCastKind() == CK_IntegralCast || 3206 ICE->getCastKind() == CK_FloatingCast) { 3207 E = ICE->getSubExpr(); 3208 ExprTy = E->getType(); 3209 3210 // Check if we didn't match because of an implicit cast from a 'char' 3211 // or 'short' to an 'int'. This is done because printf is a varargs 3212 // function. 3213 if (ICE->getType() == S.Context.IntTy || 3214 ICE->getType() == S.Context.UnsignedIntTy) { 3215 // All further checking is done on the subexpression. 3216 if (AT.matchesType(S.Context, ExprTy)) 3217 return true; 3218 } 3219 } 3220 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 3221 // Special case for 'a', which has type 'int' in C. 3222 // Note, however, that we do /not/ want to treat multibyte constants like 3223 // 'MooV' as characters! This form is deprecated but still exists. 3224 if (ExprTy == S.Context.IntTy) 3225 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 3226 ExprTy = S.Context.CharTy; 3227 } 3228 3229 // Look through enums to their underlying type. 3230 bool IsEnum = false; 3231 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 3232 ExprTy = EnumTy->getDecl()->getIntegerType(); 3233 IsEnum = true; 3234 } 3235 3236 // %C in an Objective-C context prints a unichar, not a wchar_t. 3237 // If the argument is an integer of some kind, believe the %C and suggest 3238 // a cast instead of changing the conversion specifier. 3239 QualType IntendedTy = ExprTy; 3240 if (ObjCContext && 3241 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 3242 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 3243 !ExprTy->isCharType()) { 3244 // 'unichar' is defined as a typedef of unsigned short, but we should 3245 // prefer using the typedef if it is visible. 3246 IntendedTy = S.Context.UnsignedShortTy; 3247 3248 // While we are here, check if the value is an IntegerLiteral that happens 3249 // to be within the valid range. 3250 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 3251 const llvm::APInt &V = IL->getValue(); 3252 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 3253 return true; 3254 } 3255 3256 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 3257 Sema::LookupOrdinaryName); 3258 if (S.LookupName(Result, S.getCurScope())) { 3259 NamedDecl *ND = Result.getFoundDecl(); 3260 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 3261 if (TD->getUnderlyingType() == IntendedTy) 3262 IntendedTy = S.Context.getTypedefType(TD); 3263 } 3264 } 3265 } 3266 3267 // Special-case some of Darwin's platform-independence types by suggesting 3268 // casts to primitive types that are known to be large enough. 3269 bool ShouldNotPrintDirectly = false; 3270 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 3271 // Use a 'while' to peel off layers of typedefs. 3272 QualType TyTy = IntendedTy; 3273 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 3274 StringRef Name = UserTy->getDecl()->getName(); 3275 QualType CastTy = llvm::StringSwitch<QualType>(Name) 3276 .Case("NSInteger", S.Context.LongTy) 3277 .Case("NSUInteger", S.Context.UnsignedLongTy) 3278 .Case("SInt32", S.Context.IntTy) 3279 .Case("UInt32", S.Context.UnsignedIntTy) 3280 .Default(QualType()); 3281 3282 if (!CastTy.isNull()) { 3283 ShouldNotPrintDirectly = true; 3284 IntendedTy = CastTy; 3285 break; 3286 } 3287 TyTy = UserTy->desugar(); 3288 } 3289 } 3290 3291 // We may be able to offer a FixItHint if it is a supported type. 3292 PrintfSpecifier fixedFS = FS; 3293 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 3294 S.Context, ObjCContext); 3295 3296 if (success) { 3297 // Get the fix string from the fixed format specifier 3298 SmallString<16> buf; 3299 llvm::raw_svector_ostream os(buf); 3300 fixedFS.toString(os); 3301 3302 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 3303 3304 if (IntendedTy == ExprTy) { 3305 // In this case, the specifier is wrong and should be changed to match 3306 // the argument. 3307 EmitFormatDiagnostic( 3308 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3309 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum 3310 << E->getSourceRange(), 3311 E->getLocStart(), 3312 /*IsStringLocation*/false, 3313 SpecRange, 3314 FixItHint::CreateReplacement(SpecRange, os.str())); 3315 3316 } else { 3317 // The canonical type for formatting this value is different from the 3318 // actual type of the expression. (This occurs, for example, with Darwin's 3319 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 3320 // should be printed as 'long' for 64-bit compatibility.) 3321 // Rather than emitting a normal format/argument mismatch, we want to 3322 // add a cast to the recommended type (and correct the format string 3323 // if necessary). 3324 SmallString<16> CastBuf; 3325 llvm::raw_svector_ostream CastFix(CastBuf); 3326 CastFix << "("; 3327 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 3328 CastFix << ")"; 3329 3330 SmallVector<FixItHint,4> Hints; 3331 if (!AT.matchesType(S.Context, IntendedTy)) 3332 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 3333 3334 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 3335 // If there's already a cast present, just replace it. 3336 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 3337 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 3338 3339 } else if (!requiresParensToAddCast(E)) { 3340 // If the expression has high enough precedence, 3341 // just write the C-style cast. 3342 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3343 CastFix.str())); 3344 } else { 3345 // Otherwise, add parens around the expression as well as the cast. 3346 CastFix << "("; 3347 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3348 CastFix.str())); 3349 3350 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 3351 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 3352 } 3353 3354 if (ShouldNotPrintDirectly) { 3355 // The expression has a type that should not be printed directly. 3356 // We extract the name from the typedef because we don't want to show 3357 // the underlying type in the diagnostic. 3358 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName(); 3359 3360 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 3361 << Name << IntendedTy << IsEnum 3362 << E->getSourceRange(), 3363 E->getLocStart(), /*IsStringLocation=*/false, 3364 SpecRange, Hints); 3365 } else { 3366 // In this case, the expression could be printed using a different 3367 // specifier, but we've decided that the specifier is probably correct 3368 // and we should cast instead. Just use the normal warning message. 3369 EmitFormatDiagnostic( 3370 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3371 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 3372 << E->getSourceRange(), 3373 E->getLocStart(), /*IsStringLocation*/false, 3374 SpecRange, Hints); 3375 } 3376 } 3377 } else { 3378 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 3379 SpecifierLen); 3380 // Since the warning for passing non-POD types to variadic functions 3381 // was deferred until now, we emit a warning for non-POD 3382 // arguments here. 3383 switch (S.isValidVarArgType(ExprTy)) { 3384 case Sema::VAK_Valid: 3385 case Sema::VAK_ValidInCXX11: 3386 EmitFormatDiagnostic( 3387 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3388 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 3389 << CSR 3390 << E->getSourceRange(), 3391 E->getLocStart(), /*IsStringLocation*/false, CSR); 3392 break; 3393 3394 case Sema::VAK_Undefined: 3395 EmitFormatDiagnostic( 3396 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 3397 << S.getLangOpts().CPlusPlus11 3398 << ExprTy 3399 << CallType 3400 << AT.getRepresentativeTypeName(S.Context) 3401 << CSR 3402 << E->getSourceRange(), 3403 E->getLocStart(), /*IsStringLocation*/false, CSR); 3404 checkForCStrMembers(AT, E); 3405 break; 3406 3407 case Sema::VAK_Invalid: 3408 if (ExprTy->isObjCObjectType()) 3409 EmitFormatDiagnostic( 3410 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 3411 << S.getLangOpts().CPlusPlus11 3412 << ExprTy 3413 << CallType 3414 << AT.getRepresentativeTypeName(S.Context) 3415 << CSR 3416 << E->getSourceRange(), 3417 E->getLocStart(), /*IsStringLocation*/false, CSR); 3418 else 3419 // FIXME: If this is an initializer list, suggest removing the braces 3420 // or inserting a cast to the target type. 3421 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 3422 << isa<InitListExpr>(E) << ExprTy << CallType 3423 << AT.getRepresentativeTypeName(S.Context) 3424 << E->getSourceRange(); 3425 break; 3426 } 3427 3428 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 3429 "format string specifier index out of range"); 3430 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 3431 } 3432 3433 return true; 3434 } 3435 3436 //===--- CHECK: Scanf format string checking ------------------------------===// 3437 3438 namespace { 3439 class CheckScanfHandler : public CheckFormatHandler { 3440 public: 3441 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 3442 const Expr *origFormatExpr, unsigned firstDataArg, 3443 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3444 ArrayRef<const Expr *> Args, 3445 unsigned formatIdx, bool inFunctionCall, 3446 Sema::VariadicCallType CallType, 3447 llvm::SmallBitVector &CheckedVarArgs) 3448 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3449 numDataArgs, beg, hasVAListArg, 3450 Args, formatIdx, inFunctionCall, CallType, 3451 CheckedVarArgs) 3452 {} 3453 3454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 3455 const char *startSpecifier, 3456 unsigned specifierLen) override; 3457 3458 bool HandleInvalidScanfConversionSpecifier( 3459 const analyze_scanf::ScanfSpecifier &FS, 3460 const char *startSpecifier, 3461 unsigned specifierLen) override; 3462 3463 void HandleIncompleteScanList(const char *start, const char *end) override; 3464 }; 3465 } 3466 3467 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 3468 const char *end) { 3469 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 3470 getLocationOfByte(end), /*IsStringLocation*/true, 3471 getSpecifierRange(start, end - start)); 3472 } 3473 3474 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 3475 const analyze_scanf::ScanfSpecifier &FS, 3476 const char *startSpecifier, 3477 unsigned specifierLen) { 3478 3479 const analyze_scanf::ScanfConversionSpecifier &CS = 3480 FS.getConversionSpecifier(); 3481 3482 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3483 getLocationOfByte(CS.getStart()), 3484 startSpecifier, specifierLen, 3485 CS.getStart(), CS.getLength()); 3486 } 3487 3488 bool CheckScanfHandler::HandleScanfSpecifier( 3489 const analyze_scanf::ScanfSpecifier &FS, 3490 const char *startSpecifier, 3491 unsigned specifierLen) { 3492 3493 using namespace analyze_scanf; 3494 using namespace analyze_format_string; 3495 3496 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 3497 3498 // Handle case where '%' and '*' don't consume an argument. These shouldn't 3499 // be used to decide if we are using positional arguments consistently. 3500 if (FS.consumesDataArgument()) { 3501 if (atFirstArg) { 3502 atFirstArg = false; 3503 usesPositionalArgs = FS.usesPositionalArg(); 3504 } 3505 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3506 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3507 startSpecifier, specifierLen); 3508 return false; 3509 } 3510 } 3511 3512 // Check if the field with is non-zero. 3513 const OptionalAmount &Amt = FS.getFieldWidth(); 3514 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 3515 if (Amt.getConstantAmount() == 0) { 3516 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 3517 Amt.getConstantLength()); 3518 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 3519 getLocationOfByte(Amt.getStart()), 3520 /*IsStringLocation*/true, R, 3521 FixItHint::CreateRemoval(R)); 3522 } 3523 } 3524 3525 if (!FS.consumesDataArgument()) { 3526 // FIXME: Technically specifying a precision or field width here 3527 // makes no sense. Worth issuing a warning at some point. 3528 return true; 3529 } 3530 3531 // Consume the argument. 3532 unsigned argIndex = FS.getArgIndex(); 3533 if (argIndex < NumDataArgs) { 3534 // The check to see if the argIndex is valid will come later. 3535 // We set the bit here because we may exit early from this 3536 // function if we encounter some other error. 3537 CoveredArgs.set(argIndex); 3538 } 3539 3540 // Check the length modifier is valid with the given conversion specifier. 3541 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3542 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3543 diag::warn_format_nonsensical_length); 3544 else if (!FS.hasStandardLengthModifier()) 3545 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3546 else if (!FS.hasStandardLengthConversionCombination()) 3547 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3548 diag::warn_format_non_standard_conversion_spec); 3549 3550 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3551 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3552 3553 // The remaining checks depend on the data arguments. 3554 if (HasVAListArg) 3555 return true; 3556 3557 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3558 return false; 3559 3560 // Check that the argument type matches the format specifier. 3561 const Expr *Ex = getDataArg(argIndex); 3562 if (!Ex) 3563 return true; 3564 3565 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 3566 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 3567 ScanfSpecifier fixedFS = FS; 3568 bool success = fixedFS.fixType(Ex->getType(), 3569 Ex->IgnoreImpCasts()->getType(), 3570 S.getLangOpts(), S.Context); 3571 3572 if (success) { 3573 // Get the fix string from the fixed format specifier. 3574 SmallString<128> buf; 3575 llvm::raw_svector_ostream os(buf); 3576 fixedFS.toString(os); 3577 3578 EmitFormatDiagnostic( 3579 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3580 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false 3581 << Ex->getSourceRange(), 3582 Ex->getLocStart(), 3583 /*IsStringLocation*/false, 3584 getSpecifierRange(startSpecifier, specifierLen), 3585 FixItHint::CreateReplacement( 3586 getSpecifierRange(startSpecifier, specifierLen), 3587 os.str())); 3588 } else { 3589 EmitFormatDiagnostic( 3590 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3591 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false 3592 << Ex->getSourceRange(), 3593 Ex->getLocStart(), 3594 /*IsStringLocation*/false, 3595 getSpecifierRange(startSpecifier, specifierLen)); 3596 } 3597 } 3598 3599 return true; 3600 } 3601 3602 void Sema::CheckFormatString(const StringLiteral *FExpr, 3603 const Expr *OrigFormatExpr, 3604 ArrayRef<const Expr *> Args, 3605 bool HasVAListArg, unsigned format_idx, 3606 unsigned firstDataArg, FormatStringType Type, 3607 bool inFunctionCall, VariadicCallType CallType, 3608 llvm::SmallBitVector &CheckedVarArgs) { 3609 3610 // CHECK: is the format string a wide literal? 3611 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 3612 CheckFormatHandler::EmitFormatDiagnostic( 3613 *this, inFunctionCall, Args[format_idx], 3614 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 3615 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3616 return; 3617 } 3618 3619 // Str - The format string. NOTE: this is NOT null-terminated! 3620 StringRef StrRef = FExpr->getString(); 3621 const char *Str = StrRef.data(); 3622 // Account for cases where the string literal is truncated in a declaration. 3623 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 3624 assert(T && "String literal not of constant array type!"); 3625 size_t TypeSize = T->getSize().getZExtValue(); 3626 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 3627 const unsigned numDataArgs = Args.size() - firstDataArg; 3628 3629 // Emit a warning if the string literal is truncated and does not contain an 3630 // embedded null character. 3631 if (TypeSize <= StrRef.size() && 3632 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 3633 CheckFormatHandler::EmitFormatDiagnostic( 3634 *this, inFunctionCall, Args[format_idx], 3635 PDiag(diag::warn_printf_format_string_not_null_terminated), 3636 FExpr->getLocStart(), 3637 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 3638 return; 3639 } 3640 3641 // CHECK: empty format string? 3642 if (StrLen == 0 && numDataArgs > 0) { 3643 CheckFormatHandler::EmitFormatDiagnostic( 3644 *this, inFunctionCall, Args[format_idx], 3645 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 3646 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3647 return; 3648 } 3649 3650 if (Type == FST_Printf || Type == FST_NSString) { 3651 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 3652 numDataArgs, (Type == FST_NSString), 3653 Str, HasVAListArg, Args, format_idx, 3654 inFunctionCall, CallType, CheckedVarArgs); 3655 3656 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 3657 getLangOpts(), 3658 Context.getTargetInfo())) 3659 H.DoneProcessing(); 3660 } else if (Type == FST_Scanf) { 3661 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 3662 Str, HasVAListArg, Args, format_idx, 3663 inFunctionCall, CallType, CheckedVarArgs); 3664 3665 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 3666 getLangOpts(), 3667 Context.getTargetInfo())) 3668 H.DoneProcessing(); 3669 } // TODO: handle other formats 3670 } 3671 3672 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 3673 3674 // Returns the related absolute value function that is larger, of 0 if one 3675 // does not exist. 3676 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 3677 switch (AbsFunction) { 3678 default: 3679 return 0; 3680 3681 case Builtin::BI__builtin_abs: 3682 return Builtin::BI__builtin_labs; 3683 case Builtin::BI__builtin_labs: 3684 return Builtin::BI__builtin_llabs; 3685 case Builtin::BI__builtin_llabs: 3686 return 0; 3687 3688 case Builtin::BI__builtin_fabsf: 3689 return Builtin::BI__builtin_fabs; 3690 case Builtin::BI__builtin_fabs: 3691 return Builtin::BI__builtin_fabsl; 3692 case Builtin::BI__builtin_fabsl: 3693 return 0; 3694 3695 case Builtin::BI__builtin_cabsf: 3696 return Builtin::BI__builtin_cabs; 3697 case Builtin::BI__builtin_cabs: 3698 return Builtin::BI__builtin_cabsl; 3699 case Builtin::BI__builtin_cabsl: 3700 return 0; 3701 3702 case Builtin::BIabs: 3703 return Builtin::BIlabs; 3704 case Builtin::BIlabs: 3705 return Builtin::BIllabs; 3706 case Builtin::BIllabs: 3707 return 0; 3708 3709 case Builtin::BIfabsf: 3710 return Builtin::BIfabs; 3711 case Builtin::BIfabs: 3712 return Builtin::BIfabsl; 3713 case Builtin::BIfabsl: 3714 return 0; 3715 3716 case Builtin::BIcabsf: 3717 return Builtin::BIcabs; 3718 case Builtin::BIcabs: 3719 return Builtin::BIcabsl; 3720 case Builtin::BIcabsl: 3721 return 0; 3722 } 3723 } 3724 3725 // Returns the argument type of the absolute value function. 3726 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 3727 unsigned AbsType) { 3728 if (AbsType == 0) 3729 return QualType(); 3730 3731 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3732 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 3733 if (Error != ASTContext::GE_None) 3734 return QualType(); 3735 3736 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 3737 if (!FT) 3738 return QualType(); 3739 3740 if (FT->getNumParams() != 1) 3741 return QualType(); 3742 3743 return FT->getParamType(0); 3744 } 3745 3746 // Returns the best absolute value function, or zero, based on type and 3747 // current absolute value function. 3748 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 3749 unsigned AbsFunctionKind) { 3750 unsigned BestKind = 0; 3751 uint64_t ArgSize = Context.getTypeSize(ArgType); 3752 for (unsigned Kind = AbsFunctionKind; Kind != 0; 3753 Kind = getLargerAbsoluteValueFunction(Kind)) { 3754 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 3755 if (Context.getTypeSize(ParamType) >= ArgSize) { 3756 if (BestKind == 0) 3757 BestKind = Kind; 3758 else if (Context.hasSameType(ParamType, ArgType)) { 3759 BestKind = Kind; 3760 break; 3761 } 3762 } 3763 } 3764 return BestKind; 3765 } 3766 3767 enum AbsoluteValueKind { 3768 AVK_Integer, 3769 AVK_Floating, 3770 AVK_Complex 3771 }; 3772 3773 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 3774 if (T->isIntegralOrEnumerationType()) 3775 return AVK_Integer; 3776 if (T->isRealFloatingType()) 3777 return AVK_Floating; 3778 if (T->isAnyComplexType()) 3779 return AVK_Complex; 3780 3781 llvm_unreachable("Type not integer, floating, or complex"); 3782 } 3783 3784 // Changes the absolute value function to a different type. Preserves whether 3785 // the function is a builtin. 3786 static unsigned changeAbsFunction(unsigned AbsKind, 3787 AbsoluteValueKind ValueKind) { 3788 switch (ValueKind) { 3789 case AVK_Integer: 3790 switch (AbsKind) { 3791 default: 3792 return 0; 3793 case Builtin::BI__builtin_fabsf: 3794 case Builtin::BI__builtin_fabs: 3795 case Builtin::BI__builtin_fabsl: 3796 case Builtin::BI__builtin_cabsf: 3797 case Builtin::BI__builtin_cabs: 3798 case Builtin::BI__builtin_cabsl: 3799 return Builtin::BI__builtin_abs; 3800 case Builtin::BIfabsf: 3801 case Builtin::BIfabs: 3802 case Builtin::BIfabsl: 3803 case Builtin::BIcabsf: 3804 case Builtin::BIcabs: 3805 case Builtin::BIcabsl: 3806 return Builtin::BIabs; 3807 } 3808 case AVK_Floating: 3809 switch (AbsKind) { 3810 default: 3811 return 0; 3812 case Builtin::BI__builtin_abs: 3813 case Builtin::BI__builtin_labs: 3814 case Builtin::BI__builtin_llabs: 3815 case Builtin::BI__builtin_cabsf: 3816 case Builtin::BI__builtin_cabs: 3817 case Builtin::BI__builtin_cabsl: 3818 return Builtin::BI__builtin_fabsf; 3819 case Builtin::BIabs: 3820 case Builtin::BIlabs: 3821 case Builtin::BIllabs: 3822 case Builtin::BIcabsf: 3823 case Builtin::BIcabs: 3824 case Builtin::BIcabsl: 3825 return Builtin::BIfabsf; 3826 } 3827 case AVK_Complex: 3828 switch (AbsKind) { 3829 default: 3830 return 0; 3831 case Builtin::BI__builtin_abs: 3832 case Builtin::BI__builtin_labs: 3833 case Builtin::BI__builtin_llabs: 3834 case Builtin::BI__builtin_fabsf: 3835 case Builtin::BI__builtin_fabs: 3836 case Builtin::BI__builtin_fabsl: 3837 return Builtin::BI__builtin_cabsf; 3838 case Builtin::BIabs: 3839 case Builtin::BIlabs: 3840 case Builtin::BIllabs: 3841 case Builtin::BIfabsf: 3842 case Builtin::BIfabs: 3843 case Builtin::BIfabsl: 3844 return Builtin::BIcabsf; 3845 } 3846 } 3847 llvm_unreachable("Unable to convert function"); 3848 } 3849 3850 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 3851 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3852 if (!FnInfo) 3853 return 0; 3854 3855 switch (FDecl->getBuiltinID()) { 3856 default: 3857 return 0; 3858 case Builtin::BI__builtin_abs: 3859 case Builtin::BI__builtin_fabs: 3860 case Builtin::BI__builtin_fabsf: 3861 case Builtin::BI__builtin_fabsl: 3862 case Builtin::BI__builtin_labs: 3863 case Builtin::BI__builtin_llabs: 3864 case Builtin::BI__builtin_cabs: 3865 case Builtin::BI__builtin_cabsf: 3866 case Builtin::BI__builtin_cabsl: 3867 case Builtin::BIabs: 3868 case Builtin::BIlabs: 3869 case Builtin::BIllabs: 3870 case Builtin::BIfabs: 3871 case Builtin::BIfabsf: 3872 case Builtin::BIfabsl: 3873 case Builtin::BIcabs: 3874 case Builtin::BIcabsf: 3875 case Builtin::BIcabsl: 3876 return FDecl->getBuiltinID(); 3877 } 3878 llvm_unreachable("Unknown Builtin type"); 3879 } 3880 3881 // If the replacement is valid, emit a note with replacement function. 3882 // Additionally, suggest including the proper header if not already included. 3883 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 3884 unsigned AbsKind, QualType ArgType) { 3885 bool EmitHeaderHint = true; 3886 const char *HeaderName = nullptr; 3887 const char *FunctionName = nullptr; 3888 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 3889 FunctionName = "std::abs"; 3890 if (ArgType->isIntegralOrEnumerationType()) { 3891 HeaderName = "cstdlib"; 3892 } else if (ArgType->isRealFloatingType()) { 3893 HeaderName = "cmath"; 3894 } else { 3895 llvm_unreachable("Invalid Type"); 3896 } 3897 3898 // Lookup all std::abs 3899 if (NamespaceDecl *Std = S.getStdNamespace()) { 3900 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 3901 R.suppressDiagnostics(); 3902 S.LookupQualifiedName(R, Std); 3903 3904 for (const auto *I : R) { 3905 const FunctionDecl *FDecl = nullptr; 3906 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 3907 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 3908 } else { 3909 FDecl = dyn_cast<FunctionDecl>(I); 3910 } 3911 if (!FDecl) 3912 continue; 3913 3914 // Found std::abs(), check that they are the right ones. 3915 if (FDecl->getNumParams() != 1) 3916 continue; 3917 3918 // Check that the parameter type can handle the argument. 3919 QualType ParamType = FDecl->getParamDecl(0)->getType(); 3920 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 3921 S.Context.getTypeSize(ArgType) <= 3922 S.Context.getTypeSize(ParamType)) { 3923 // Found a function, don't need the header hint. 3924 EmitHeaderHint = false; 3925 break; 3926 } 3927 } 3928 } 3929 } else { 3930 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind); 3931 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 3932 3933 if (HeaderName) { 3934 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 3935 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 3936 R.suppressDiagnostics(); 3937 S.LookupName(R, S.getCurScope()); 3938 3939 if (R.isSingleResult()) { 3940 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3941 if (FD && FD->getBuiltinID() == AbsKind) { 3942 EmitHeaderHint = false; 3943 } else { 3944 return; 3945 } 3946 } else if (!R.empty()) { 3947 return; 3948 } 3949 } 3950 } 3951 3952 S.Diag(Loc, diag::note_replace_abs_function) 3953 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 3954 3955 if (!HeaderName) 3956 return; 3957 3958 if (!EmitHeaderHint) 3959 return; 3960 3961 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 3962 << FunctionName; 3963 } 3964 3965 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 3966 if (!FDecl) 3967 return false; 3968 3969 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 3970 return false; 3971 3972 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 3973 3974 while (ND && ND->isInlineNamespace()) { 3975 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 3976 } 3977 3978 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 3979 return false; 3980 3981 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 3982 return false; 3983 3984 return true; 3985 } 3986 3987 // Warn when using the wrong abs() function. 3988 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 3989 const FunctionDecl *FDecl, 3990 IdentifierInfo *FnInfo) { 3991 if (Call->getNumArgs() != 1) 3992 return; 3993 3994 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 3995 bool IsStdAbs = IsFunctionStdAbs(FDecl); 3996 if (AbsKind == 0 && !IsStdAbs) 3997 return; 3998 3999 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 4000 QualType ParamType = Call->getArg(0)->getType(); 4001 4002 // Unsigned types cannot be negative. Suggest removing the absolute value 4003 // function call. 4004 if (ArgType->isUnsignedIntegerType()) { 4005 const char *FunctionName = 4006 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind); 4007 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 4008 Diag(Call->getExprLoc(), diag::note_remove_abs) 4009 << FunctionName 4010 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 4011 return; 4012 } 4013 4014 // std::abs has overloads which prevent most of the absolute value problems 4015 // from occurring. 4016 if (IsStdAbs) 4017 return; 4018 4019 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 4020 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 4021 4022 // The argument and parameter are the same kind. Check if they are the right 4023 // size. 4024 if (ArgValueKind == ParamValueKind) { 4025 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 4026 return; 4027 4028 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 4029 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 4030 << FDecl << ArgType << ParamType; 4031 4032 if (NewAbsKind == 0) 4033 return; 4034 4035 emitReplacement(*this, Call->getExprLoc(), 4036 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4037 return; 4038 } 4039 4040 // ArgValueKind != ParamValueKind 4041 // The wrong type of absolute value function was used. Attempt to find the 4042 // proper one. 4043 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 4044 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 4045 if (NewAbsKind == 0) 4046 return; 4047 4048 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 4049 << FDecl << ParamValueKind << ArgValueKind; 4050 4051 emitReplacement(*this, Call->getExprLoc(), 4052 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4053 return; 4054 } 4055 4056 //===--- CHECK: Standard memory functions ---------------------------------===// 4057 4058 /// \brief Takes the expression passed to the size_t parameter of functions 4059 /// such as memcmp, strncat, etc and warns if it's a comparison. 4060 /// 4061 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 4062 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 4063 IdentifierInfo *FnName, 4064 SourceLocation FnLoc, 4065 SourceLocation RParenLoc) { 4066 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 4067 if (!Size) 4068 return false; 4069 4070 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 4071 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 4072 return false; 4073 4074 SourceRange SizeRange = Size->getSourceRange(); 4075 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 4076 << SizeRange << FnName; 4077 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 4078 << FnName << FixItHint::CreateInsertion( 4079 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 4080 << FixItHint::CreateRemoval(RParenLoc); 4081 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 4082 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 4083 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 4084 ")"); 4085 4086 return true; 4087 } 4088 4089 /// \brief Determine whether the given type is or contains a dynamic class type 4090 /// (e.g., whether it has a vtable). 4091 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 4092 bool &IsContained) { 4093 // Look through array types while ignoring qualifiers. 4094 const Type *Ty = T->getBaseElementTypeUnsafe(); 4095 IsContained = false; 4096 4097 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 4098 RD = RD ? RD->getDefinition() : nullptr; 4099 if (!RD) 4100 return nullptr; 4101 4102 if (RD->isDynamicClass()) 4103 return RD; 4104 4105 // Check all the fields. If any bases were dynamic, the class is dynamic. 4106 // It's impossible for a class to transitively contain itself by value, so 4107 // infinite recursion is impossible. 4108 for (auto *FD : RD->fields()) { 4109 bool SubContained; 4110 if (const CXXRecordDecl *ContainedRD = 4111 getContainedDynamicClass(FD->getType(), SubContained)) { 4112 IsContained = true; 4113 return ContainedRD; 4114 } 4115 } 4116 4117 return nullptr; 4118 } 4119 4120 /// \brief If E is a sizeof expression, returns its argument expression, 4121 /// otherwise returns NULL. 4122 static const Expr *getSizeOfExprArg(const Expr* E) { 4123 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4124 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4125 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 4126 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 4127 4128 return nullptr; 4129 } 4130 4131 /// \brief If E is a sizeof expression, returns its argument type. 4132 static QualType getSizeOfArgType(const Expr* E) { 4133 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4134 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4135 if (SizeOf->getKind() == clang::UETT_SizeOf) 4136 return SizeOf->getTypeOfArgument(); 4137 4138 return QualType(); 4139 } 4140 4141 /// \brief Check for dangerous or invalid arguments to memset(). 4142 /// 4143 /// This issues warnings on known problematic, dangerous or unspecified 4144 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 4145 /// function calls. 4146 /// 4147 /// \param Call The call expression to diagnose. 4148 void Sema::CheckMemaccessArguments(const CallExpr *Call, 4149 unsigned BId, 4150 IdentifierInfo *FnName) { 4151 assert(BId != 0); 4152 4153 // It is possible to have a non-standard definition of memset. Validate 4154 // we have enough arguments, and if not, abort further checking. 4155 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 4156 if (Call->getNumArgs() < ExpectedNumArgs) 4157 return; 4158 4159 unsigned LastArg = (BId == Builtin::BImemset || 4160 BId == Builtin::BIstrndup ? 1 : 2); 4161 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 4162 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 4163 4164 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 4165 Call->getLocStart(), Call->getRParenLoc())) 4166 return; 4167 4168 // We have special checking when the length is a sizeof expression. 4169 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 4170 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 4171 llvm::FoldingSetNodeID SizeOfArgID; 4172 4173 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 4174 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 4175 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 4176 4177 QualType DestTy = Dest->getType(); 4178 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 4179 QualType PointeeTy = DestPtrTy->getPointeeType(); 4180 4181 // Never warn about void type pointers. This can be used to suppress 4182 // false positives. 4183 if (PointeeTy->isVoidType()) 4184 continue; 4185 4186 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 4187 // actually comparing the expressions for equality. Because computing the 4188 // expression IDs can be expensive, we only do this if the diagnostic is 4189 // enabled. 4190 if (SizeOfArg && 4191 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 4192 SizeOfArg->getExprLoc())) { 4193 // We only compute IDs for expressions if the warning is enabled, and 4194 // cache the sizeof arg's ID. 4195 if (SizeOfArgID == llvm::FoldingSetNodeID()) 4196 SizeOfArg->Profile(SizeOfArgID, Context, true); 4197 llvm::FoldingSetNodeID DestID; 4198 Dest->Profile(DestID, Context, true); 4199 if (DestID == SizeOfArgID) { 4200 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 4201 // over sizeof(src) as well. 4202 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 4203 StringRef ReadableName = FnName->getName(); 4204 4205 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 4206 if (UnaryOp->getOpcode() == UO_AddrOf) 4207 ActionIdx = 1; // If its an address-of operator, just remove it. 4208 if (!PointeeTy->isIncompleteType() && 4209 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 4210 ActionIdx = 2; // If the pointee's size is sizeof(char), 4211 // suggest an explicit length. 4212 4213 // If the function is defined as a builtin macro, do not show macro 4214 // expansion. 4215 SourceLocation SL = SizeOfArg->getExprLoc(); 4216 SourceRange DSR = Dest->getSourceRange(); 4217 SourceRange SSR = SizeOfArg->getSourceRange(); 4218 SourceManager &SM = getSourceManager(); 4219 4220 if (SM.isMacroArgExpansion(SL)) { 4221 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 4222 SL = SM.getSpellingLoc(SL); 4223 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 4224 SM.getSpellingLoc(DSR.getEnd())); 4225 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 4226 SM.getSpellingLoc(SSR.getEnd())); 4227 } 4228 4229 DiagRuntimeBehavior(SL, SizeOfArg, 4230 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 4231 << ReadableName 4232 << PointeeTy 4233 << DestTy 4234 << DSR 4235 << SSR); 4236 DiagRuntimeBehavior(SL, SizeOfArg, 4237 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 4238 << ActionIdx 4239 << SSR); 4240 4241 break; 4242 } 4243 } 4244 4245 // Also check for cases where the sizeof argument is the exact same 4246 // type as the memory argument, and where it points to a user-defined 4247 // record type. 4248 if (SizeOfArgTy != QualType()) { 4249 if (PointeeTy->isRecordType() && 4250 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 4251 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 4252 PDiag(diag::warn_sizeof_pointer_type_memaccess) 4253 << FnName << SizeOfArgTy << ArgIdx 4254 << PointeeTy << Dest->getSourceRange() 4255 << LenExpr->getSourceRange()); 4256 break; 4257 } 4258 } 4259 4260 // Always complain about dynamic classes. 4261 bool IsContained; 4262 if (const CXXRecordDecl *ContainedRD = 4263 getContainedDynamicClass(PointeeTy, IsContained)) { 4264 4265 unsigned OperationType = 0; 4266 // "overwritten" if we're warning about the destination for any call 4267 // but memcmp; otherwise a verb appropriate to the call. 4268 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 4269 if (BId == Builtin::BImemcpy) 4270 OperationType = 1; 4271 else if(BId == Builtin::BImemmove) 4272 OperationType = 2; 4273 else if (BId == Builtin::BImemcmp) 4274 OperationType = 3; 4275 } 4276 4277 DiagRuntimeBehavior( 4278 Dest->getExprLoc(), Dest, 4279 PDiag(diag::warn_dyn_class_memaccess) 4280 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 4281 << FnName << IsContained << ContainedRD << OperationType 4282 << Call->getCallee()->getSourceRange()); 4283 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 4284 BId != Builtin::BImemset) 4285 DiagRuntimeBehavior( 4286 Dest->getExprLoc(), Dest, 4287 PDiag(diag::warn_arc_object_memaccess) 4288 << ArgIdx << FnName << PointeeTy 4289 << Call->getCallee()->getSourceRange()); 4290 else 4291 continue; 4292 4293 DiagRuntimeBehavior( 4294 Dest->getExprLoc(), Dest, 4295 PDiag(diag::note_bad_memaccess_silence) 4296 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 4297 break; 4298 } 4299 } 4300 } 4301 4302 // A little helper routine: ignore addition and subtraction of integer literals. 4303 // This intentionally does not ignore all integer constant expressions because 4304 // we don't want to remove sizeof(). 4305 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 4306 Ex = Ex->IgnoreParenCasts(); 4307 4308 for (;;) { 4309 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 4310 if (!BO || !BO->isAdditiveOp()) 4311 break; 4312 4313 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 4314 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 4315 4316 if (isa<IntegerLiteral>(RHS)) 4317 Ex = LHS; 4318 else if (isa<IntegerLiteral>(LHS)) 4319 Ex = RHS; 4320 else 4321 break; 4322 } 4323 4324 return Ex; 4325 } 4326 4327 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 4328 ASTContext &Context) { 4329 // Only handle constant-sized or VLAs, but not flexible members. 4330 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 4331 // Only issue the FIXIT for arrays of size > 1. 4332 if (CAT->getSize().getSExtValue() <= 1) 4333 return false; 4334 } else if (!Ty->isVariableArrayType()) { 4335 return false; 4336 } 4337 return true; 4338 } 4339 4340 // Warn if the user has made the 'size' argument to strlcpy or strlcat 4341 // be the size of the source, instead of the destination. 4342 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 4343 IdentifierInfo *FnName) { 4344 4345 // Don't crash if the user has the wrong number of arguments 4346 if (Call->getNumArgs() != 3) 4347 return; 4348 4349 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 4350 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 4351 const Expr *CompareWithSrc = nullptr; 4352 4353 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 4354 Call->getLocStart(), Call->getRParenLoc())) 4355 return; 4356 4357 // Look for 'strlcpy(dst, x, sizeof(x))' 4358 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 4359 CompareWithSrc = Ex; 4360 else { 4361 // Look for 'strlcpy(dst, x, strlen(x))' 4362 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 4363 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 4364 SizeCall->getNumArgs() == 1) 4365 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 4366 } 4367 } 4368 4369 if (!CompareWithSrc) 4370 return; 4371 4372 // Determine if the argument to sizeof/strlen is equal to the source 4373 // argument. In principle there's all kinds of things you could do 4374 // here, for instance creating an == expression and evaluating it with 4375 // EvaluateAsBooleanCondition, but this uses a more direct technique: 4376 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 4377 if (!SrcArgDRE) 4378 return; 4379 4380 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 4381 if (!CompareWithSrcDRE || 4382 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 4383 return; 4384 4385 const Expr *OriginalSizeArg = Call->getArg(2); 4386 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 4387 << OriginalSizeArg->getSourceRange() << FnName; 4388 4389 // Output a FIXIT hint if the destination is an array (rather than a 4390 // pointer to an array). This could be enhanced to handle some 4391 // pointers if we know the actual size, like if DstArg is 'array+2' 4392 // we could say 'sizeof(array)-2'. 4393 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 4394 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 4395 return; 4396 4397 SmallString<128> sizeString; 4398 llvm::raw_svector_ostream OS(sizeString); 4399 OS << "sizeof("; 4400 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4401 OS << ")"; 4402 4403 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 4404 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 4405 OS.str()); 4406 } 4407 4408 /// Check if two expressions refer to the same declaration. 4409 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 4410 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 4411 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 4412 return D1->getDecl() == D2->getDecl(); 4413 return false; 4414 } 4415 4416 static const Expr *getStrlenExprArg(const Expr *E) { 4417 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 4418 const FunctionDecl *FD = CE->getDirectCallee(); 4419 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 4420 return nullptr; 4421 return CE->getArg(0)->IgnoreParenCasts(); 4422 } 4423 return nullptr; 4424 } 4425 4426 // Warn on anti-patterns as the 'size' argument to strncat. 4427 // The correct size argument should look like following: 4428 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 4429 void Sema::CheckStrncatArguments(const CallExpr *CE, 4430 IdentifierInfo *FnName) { 4431 // Don't crash if the user has the wrong number of arguments. 4432 if (CE->getNumArgs() < 3) 4433 return; 4434 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 4435 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 4436 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 4437 4438 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 4439 CE->getRParenLoc())) 4440 return; 4441 4442 // Identify common expressions, which are wrongly used as the size argument 4443 // to strncat and may lead to buffer overflows. 4444 unsigned PatternType = 0; 4445 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 4446 // - sizeof(dst) 4447 if (referToTheSameDecl(SizeOfArg, DstArg)) 4448 PatternType = 1; 4449 // - sizeof(src) 4450 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 4451 PatternType = 2; 4452 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 4453 if (BE->getOpcode() == BO_Sub) { 4454 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 4455 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 4456 // - sizeof(dst) - strlen(dst) 4457 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 4458 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 4459 PatternType = 1; 4460 // - sizeof(src) - (anything) 4461 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 4462 PatternType = 2; 4463 } 4464 } 4465 4466 if (PatternType == 0) 4467 return; 4468 4469 // Generate the diagnostic. 4470 SourceLocation SL = LenArg->getLocStart(); 4471 SourceRange SR = LenArg->getSourceRange(); 4472 SourceManager &SM = getSourceManager(); 4473 4474 // If the function is defined as a builtin macro, do not show macro expansion. 4475 if (SM.isMacroArgExpansion(SL)) { 4476 SL = SM.getSpellingLoc(SL); 4477 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 4478 SM.getSpellingLoc(SR.getEnd())); 4479 } 4480 4481 // Check if the destination is an array (rather than a pointer to an array). 4482 QualType DstTy = DstArg->getType(); 4483 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 4484 Context); 4485 if (!isKnownSizeArray) { 4486 if (PatternType == 1) 4487 Diag(SL, diag::warn_strncat_wrong_size) << SR; 4488 else 4489 Diag(SL, diag::warn_strncat_src_size) << SR; 4490 return; 4491 } 4492 4493 if (PatternType == 1) 4494 Diag(SL, diag::warn_strncat_large_size) << SR; 4495 else 4496 Diag(SL, diag::warn_strncat_src_size) << SR; 4497 4498 SmallString<128> sizeString; 4499 llvm::raw_svector_ostream OS(sizeString); 4500 OS << "sizeof("; 4501 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4502 OS << ") - "; 4503 OS << "strlen("; 4504 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4505 OS << ") - 1"; 4506 4507 Diag(SL, diag::note_strncat_wrong_size) 4508 << FixItHint::CreateReplacement(SR, OS.str()); 4509 } 4510 4511 //===--- CHECK: Return Address of Stack Variable --------------------------===// 4512 4513 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4514 Decl *ParentDecl); 4515 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 4516 Decl *ParentDecl); 4517 4518 /// CheckReturnStackAddr - Check if a return statement returns the address 4519 /// of a stack variable. 4520 static void 4521 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 4522 SourceLocation ReturnLoc) { 4523 4524 Expr *stackE = nullptr; 4525 SmallVector<DeclRefExpr *, 8> refVars; 4526 4527 // Perform checking for returned stack addresses, local blocks, 4528 // label addresses or references to temporaries. 4529 if (lhsType->isPointerType() || 4530 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 4531 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 4532 } else if (lhsType->isReferenceType()) { 4533 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 4534 } 4535 4536 if (!stackE) 4537 return; // Nothing suspicious was found. 4538 4539 SourceLocation diagLoc; 4540 SourceRange diagRange; 4541 if (refVars.empty()) { 4542 diagLoc = stackE->getLocStart(); 4543 diagRange = stackE->getSourceRange(); 4544 } else { 4545 // We followed through a reference variable. 'stackE' contains the 4546 // problematic expression but we will warn at the return statement pointing 4547 // at the reference variable. We will later display the "trail" of 4548 // reference variables using notes. 4549 diagLoc = refVars[0]->getLocStart(); 4550 diagRange = refVars[0]->getSourceRange(); 4551 } 4552 4553 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 4554 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 4555 : diag::warn_ret_stack_addr) 4556 << DR->getDecl()->getDeclName() << diagRange; 4557 } else if (isa<BlockExpr>(stackE)) { // local block. 4558 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 4559 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 4560 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 4561 } else { // local temporary. 4562 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 4563 : diag::warn_ret_local_temp_addr) 4564 << diagRange; 4565 } 4566 4567 // Display the "trail" of reference variables that we followed until we 4568 // found the problematic expression using notes. 4569 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 4570 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 4571 // If this var binds to another reference var, show the range of the next 4572 // var, otherwise the var binds to the problematic expression, in which case 4573 // show the range of the expression. 4574 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 4575 : stackE->getSourceRange(); 4576 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 4577 << VD->getDeclName() << range; 4578 } 4579 } 4580 4581 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 4582 /// check if the expression in a return statement evaluates to an address 4583 /// to a location on the stack, a local block, an address of a label, or a 4584 /// reference to local temporary. The recursion is used to traverse the 4585 /// AST of the return expression, with recursion backtracking when we 4586 /// encounter a subexpression that (1) clearly does not lead to one of the 4587 /// above problematic expressions (2) is something we cannot determine leads to 4588 /// a problematic expression based on such local checking. 4589 /// 4590 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 4591 /// the expression that they point to. Such variables are added to the 4592 /// 'refVars' vector so that we know what the reference variable "trail" was. 4593 /// 4594 /// EvalAddr processes expressions that are pointers that are used as 4595 /// references (and not L-values). EvalVal handles all other values. 4596 /// At the base case of the recursion is a check for the above problematic 4597 /// expressions. 4598 /// 4599 /// This implementation handles: 4600 /// 4601 /// * pointer-to-pointer casts 4602 /// * implicit conversions from array references to pointers 4603 /// * taking the address of fields 4604 /// * arbitrary interplay between "&" and "*" operators 4605 /// * pointer arithmetic from an address of a stack variable 4606 /// * taking the address of an array element where the array is on the stack 4607 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4608 Decl *ParentDecl) { 4609 if (E->isTypeDependent()) 4610 return nullptr; 4611 4612 // We should only be called for evaluating pointer expressions. 4613 assert((E->getType()->isAnyPointerType() || 4614 E->getType()->isBlockPointerType() || 4615 E->getType()->isObjCQualifiedIdType()) && 4616 "EvalAddr only works on pointers"); 4617 4618 E = E->IgnoreParens(); 4619 4620 // Our "symbolic interpreter" is just a dispatch off the currently 4621 // viewed AST node. We then recursively traverse the AST by calling 4622 // EvalAddr and EvalVal appropriately. 4623 switch (E->getStmtClass()) { 4624 case Stmt::DeclRefExprClass: { 4625 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4626 4627 // If we leave the immediate function, the lifetime isn't about to end. 4628 if (DR->refersToEnclosingLocal()) 4629 return nullptr; 4630 4631 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 4632 // If this is a reference variable, follow through to the expression that 4633 // it points to. 4634 if (V->hasLocalStorage() && 4635 V->getType()->isReferenceType() && V->hasInit()) { 4636 // Add the reference variable to the "trail". 4637 refVars.push_back(DR); 4638 return EvalAddr(V->getInit(), refVars, ParentDecl); 4639 } 4640 4641 return nullptr; 4642 } 4643 4644 case Stmt::UnaryOperatorClass: { 4645 // The only unary operator that make sense to handle here 4646 // is AddrOf. All others don't make sense as pointers. 4647 UnaryOperator *U = cast<UnaryOperator>(E); 4648 4649 if (U->getOpcode() == UO_AddrOf) 4650 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 4651 else 4652 return nullptr; 4653 } 4654 4655 case Stmt::BinaryOperatorClass: { 4656 // Handle pointer arithmetic. All other binary operators are not valid 4657 // in this context. 4658 BinaryOperator *B = cast<BinaryOperator>(E); 4659 BinaryOperatorKind op = B->getOpcode(); 4660 4661 if (op != BO_Add && op != BO_Sub) 4662 return nullptr; 4663 4664 Expr *Base = B->getLHS(); 4665 4666 // Determine which argument is the real pointer base. It could be 4667 // the RHS argument instead of the LHS. 4668 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 4669 4670 assert (Base->getType()->isPointerType()); 4671 return EvalAddr(Base, refVars, ParentDecl); 4672 } 4673 4674 // For conditional operators we need to see if either the LHS or RHS are 4675 // valid DeclRefExpr*s. If one of them is valid, we return it. 4676 case Stmt::ConditionalOperatorClass: { 4677 ConditionalOperator *C = cast<ConditionalOperator>(E); 4678 4679 // Handle the GNU extension for missing LHS. 4680 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 4681 if (Expr *LHSExpr = C->getLHS()) { 4682 // In C++, we can have a throw-expression, which has 'void' type. 4683 if (!LHSExpr->getType()->isVoidType()) 4684 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 4685 return LHS; 4686 } 4687 4688 // In C++, we can have a throw-expression, which has 'void' type. 4689 if (C->getRHS()->getType()->isVoidType()) 4690 return nullptr; 4691 4692 return EvalAddr(C->getRHS(), refVars, ParentDecl); 4693 } 4694 4695 case Stmt::BlockExprClass: 4696 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 4697 return E; // local block. 4698 return nullptr; 4699 4700 case Stmt::AddrLabelExprClass: 4701 return E; // address of label. 4702 4703 case Stmt::ExprWithCleanupsClass: 4704 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 4705 ParentDecl); 4706 4707 // For casts, we need to handle conversions from arrays to 4708 // pointer values, and pointer-to-pointer conversions. 4709 case Stmt::ImplicitCastExprClass: 4710 case Stmt::CStyleCastExprClass: 4711 case Stmt::CXXFunctionalCastExprClass: 4712 case Stmt::ObjCBridgedCastExprClass: 4713 case Stmt::CXXStaticCastExprClass: 4714 case Stmt::CXXDynamicCastExprClass: 4715 case Stmt::CXXConstCastExprClass: 4716 case Stmt::CXXReinterpretCastExprClass: { 4717 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 4718 switch (cast<CastExpr>(E)->getCastKind()) { 4719 case CK_LValueToRValue: 4720 case CK_NoOp: 4721 case CK_BaseToDerived: 4722 case CK_DerivedToBase: 4723 case CK_UncheckedDerivedToBase: 4724 case CK_Dynamic: 4725 case CK_CPointerToObjCPointerCast: 4726 case CK_BlockPointerToObjCPointerCast: 4727 case CK_AnyPointerToBlockPointerCast: 4728 return EvalAddr(SubExpr, refVars, ParentDecl); 4729 4730 case CK_ArrayToPointerDecay: 4731 return EvalVal(SubExpr, refVars, ParentDecl); 4732 4733 case CK_BitCast: 4734 if (SubExpr->getType()->isAnyPointerType() || 4735 SubExpr->getType()->isBlockPointerType() || 4736 SubExpr->getType()->isObjCQualifiedIdType()) 4737 return EvalAddr(SubExpr, refVars, ParentDecl); 4738 else 4739 return nullptr; 4740 4741 default: 4742 return nullptr; 4743 } 4744 } 4745 4746 case Stmt::MaterializeTemporaryExprClass: 4747 if (Expr *Result = EvalAddr( 4748 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4749 refVars, ParentDecl)) 4750 return Result; 4751 4752 return E; 4753 4754 // Everything else: we simply don't reason about them. 4755 default: 4756 return nullptr; 4757 } 4758 } 4759 4760 4761 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 4762 /// See the comments for EvalAddr for more details. 4763 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4764 Decl *ParentDecl) { 4765 do { 4766 // We should only be called for evaluating non-pointer expressions, or 4767 // expressions with a pointer type that are not used as references but instead 4768 // are l-values (e.g., DeclRefExpr with a pointer type). 4769 4770 // Our "symbolic interpreter" is just a dispatch off the currently 4771 // viewed AST node. We then recursively traverse the AST by calling 4772 // EvalAddr and EvalVal appropriately. 4773 4774 E = E->IgnoreParens(); 4775 switch (E->getStmtClass()) { 4776 case Stmt::ImplicitCastExprClass: { 4777 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 4778 if (IE->getValueKind() == VK_LValue) { 4779 E = IE->getSubExpr(); 4780 continue; 4781 } 4782 return nullptr; 4783 } 4784 4785 case Stmt::ExprWithCleanupsClass: 4786 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 4787 4788 case Stmt::DeclRefExprClass: { 4789 // When we hit a DeclRefExpr we are looking at code that refers to a 4790 // variable's name. If it's not a reference variable we check if it has 4791 // local storage within the function, and if so, return the expression. 4792 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4793 4794 // If we leave the immediate function, the lifetime isn't about to end. 4795 if (DR->refersToEnclosingLocal()) 4796 return nullptr; 4797 4798 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 4799 // Check if it refers to itself, e.g. "int& i = i;". 4800 if (V == ParentDecl) 4801 return DR; 4802 4803 if (V->hasLocalStorage()) { 4804 if (!V->getType()->isReferenceType()) 4805 return DR; 4806 4807 // Reference variable, follow through to the expression that 4808 // it points to. 4809 if (V->hasInit()) { 4810 // Add the reference variable to the "trail". 4811 refVars.push_back(DR); 4812 return EvalVal(V->getInit(), refVars, V); 4813 } 4814 } 4815 } 4816 4817 return nullptr; 4818 } 4819 4820 case Stmt::UnaryOperatorClass: { 4821 // The only unary operator that make sense to handle here 4822 // is Deref. All others don't resolve to a "name." This includes 4823 // handling all sorts of rvalues passed to a unary operator. 4824 UnaryOperator *U = cast<UnaryOperator>(E); 4825 4826 if (U->getOpcode() == UO_Deref) 4827 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 4828 4829 return nullptr; 4830 } 4831 4832 case Stmt::ArraySubscriptExprClass: { 4833 // Array subscripts are potential references to data on the stack. We 4834 // retrieve the DeclRefExpr* for the array variable if it indeed 4835 // has local storage. 4836 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 4837 } 4838 4839 case Stmt::ConditionalOperatorClass: { 4840 // For conditional operators we need to see if either the LHS or RHS are 4841 // non-NULL Expr's. If one is non-NULL, we return it. 4842 ConditionalOperator *C = cast<ConditionalOperator>(E); 4843 4844 // Handle the GNU extension for missing LHS. 4845 if (Expr *LHSExpr = C->getLHS()) { 4846 // In C++, we can have a throw-expression, which has 'void' type. 4847 if (!LHSExpr->getType()->isVoidType()) 4848 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 4849 return LHS; 4850 } 4851 4852 // In C++, we can have a throw-expression, which has 'void' type. 4853 if (C->getRHS()->getType()->isVoidType()) 4854 return nullptr; 4855 4856 return EvalVal(C->getRHS(), refVars, ParentDecl); 4857 } 4858 4859 // Accesses to members are potential references to data on the stack. 4860 case Stmt::MemberExprClass: { 4861 MemberExpr *M = cast<MemberExpr>(E); 4862 4863 // Check for indirect access. We only want direct field accesses. 4864 if (M->isArrow()) 4865 return nullptr; 4866 4867 // Check whether the member type is itself a reference, in which case 4868 // we're not going to refer to the member, but to what the member refers to. 4869 if (M->getMemberDecl()->getType()->isReferenceType()) 4870 return nullptr; 4871 4872 return EvalVal(M->getBase(), refVars, ParentDecl); 4873 } 4874 4875 case Stmt::MaterializeTemporaryExprClass: 4876 if (Expr *Result = EvalVal( 4877 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4878 refVars, ParentDecl)) 4879 return Result; 4880 4881 return E; 4882 4883 default: 4884 // Check that we don't return or take the address of a reference to a 4885 // temporary. This is only useful in C++. 4886 if (!E->isTypeDependent() && E->isRValue()) 4887 return E; 4888 4889 // Everything else: we simply don't reason about them. 4890 return nullptr; 4891 } 4892 } while (true); 4893 } 4894 4895 void 4896 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 4897 SourceLocation ReturnLoc, 4898 bool isObjCMethod, 4899 const AttrVec *Attrs, 4900 const FunctionDecl *FD) { 4901 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 4902 4903 // Check if the return value is null but should not be. 4904 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) && 4905 CheckNonNullExpr(*this, RetValExp)) 4906 Diag(ReturnLoc, diag::warn_null_ret) 4907 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 4908 4909 // C++11 [basic.stc.dynamic.allocation]p4: 4910 // If an allocation function declared with a non-throwing 4911 // exception-specification fails to allocate storage, it shall return 4912 // a null pointer. Any other allocation function that fails to allocate 4913 // storage shall indicate failure only by throwing an exception [...] 4914 if (FD) { 4915 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 4916 if (Op == OO_New || Op == OO_Array_New) { 4917 const FunctionProtoType *Proto 4918 = FD->getType()->castAs<FunctionProtoType>(); 4919 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 4920 CheckNonNullExpr(*this, RetValExp)) 4921 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 4922 << FD << getLangOpts().CPlusPlus11; 4923 } 4924 } 4925 } 4926 4927 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 4928 4929 /// Check for comparisons of floating point operands using != and ==. 4930 /// Issue a warning if these are no self-comparisons, as they are not likely 4931 /// to do what the programmer intended. 4932 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 4933 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 4934 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 4935 4936 // Special case: check for x == x (which is OK). 4937 // Do not emit warnings for such cases. 4938 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 4939 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 4940 if (DRL->getDecl() == DRR->getDecl()) 4941 return; 4942 4943 4944 // Special case: check for comparisons against literals that can be exactly 4945 // represented by APFloat. In such cases, do not emit a warning. This 4946 // is a heuristic: often comparison against such literals are used to 4947 // detect if a value in a variable has not changed. This clearly can 4948 // lead to false negatives. 4949 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 4950 if (FLL->isExact()) 4951 return; 4952 } else 4953 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 4954 if (FLR->isExact()) 4955 return; 4956 4957 // Check for comparisons with builtin types. 4958 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 4959 if (CL->getBuiltinCallee()) 4960 return; 4961 4962 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 4963 if (CR->getBuiltinCallee()) 4964 return; 4965 4966 // Emit the diagnostic. 4967 Diag(Loc, diag::warn_floatingpoint_eq) 4968 << LHS->getSourceRange() << RHS->getSourceRange(); 4969 } 4970 4971 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 4972 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 4973 4974 namespace { 4975 4976 /// Structure recording the 'active' range of an integer-valued 4977 /// expression. 4978 struct IntRange { 4979 /// The number of bits active in the int. 4980 unsigned Width; 4981 4982 /// True if the int is known not to have negative values. 4983 bool NonNegative; 4984 4985 IntRange(unsigned Width, bool NonNegative) 4986 : Width(Width), NonNegative(NonNegative) 4987 {} 4988 4989 /// Returns the range of the bool type. 4990 static IntRange forBoolType() { 4991 return IntRange(1, true); 4992 } 4993 4994 /// Returns the range of an opaque value of the given integral type. 4995 static IntRange forValueOfType(ASTContext &C, QualType T) { 4996 return forValueOfCanonicalType(C, 4997 T->getCanonicalTypeInternal().getTypePtr()); 4998 } 4999 5000 /// Returns the range of an opaque value of a canonical integral type. 5001 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 5002 assert(T->isCanonicalUnqualified()); 5003 5004 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5005 T = VT->getElementType().getTypePtr(); 5006 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5007 T = CT->getElementType().getTypePtr(); 5008 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5009 T = AT->getValueType().getTypePtr(); 5010 5011 // For enum types, use the known bit width of the enumerators. 5012 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 5013 EnumDecl *Enum = ET->getDecl(); 5014 if (!Enum->isCompleteDefinition()) 5015 return IntRange(C.getIntWidth(QualType(T, 0)), false); 5016 5017 unsigned NumPositive = Enum->getNumPositiveBits(); 5018 unsigned NumNegative = Enum->getNumNegativeBits(); 5019 5020 if (NumNegative == 0) 5021 return IntRange(NumPositive, true/*NonNegative*/); 5022 else 5023 return IntRange(std::max(NumPositive + 1, NumNegative), 5024 false/*NonNegative*/); 5025 } 5026 5027 const BuiltinType *BT = cast<BuiltinType>(T); 5028 assert(BT->isInteger()); 5029 5030 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5031 } 5032 5033 /// Returns the "target" range of a canonical integral type, i.e. 5034 /// the range of values expressible in the type. 5035 /// 5036 /// This matches forValueOfCanonicalType except that enums have the 5037 /// full range of their type, not the range of their enumerators. 5038 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 5039 assert(T->isCanonicalUnqualified()); 5040 5041 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5042 T = VT->getElementType().getTypePtr(); 5043 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5044 T = CT->getElementType().getTypePtr(); 5045 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5046 T = AT->getValueType().getTypePtr(); 5047 if (const EnumType *ET = dyn_cast<EnumType>(T)) 5048 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 5049 5050 const BuiltinType *BT = cast<BuiltinType>(T); 5051 assert(BT->isInteger()); 5052 5053 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5054 } 5055 5056 /// Returns the supremum of two ranges: i.e. their conservative merge. 5057 static IntRange join(IntRange L, IntRange R) { 5058 return IntRange(std::max(L.Width, R.Width), 5059 L.NonNegative && R.NonNegative); 5060 } 5061 5062 /// Returns the infinum of two ranges: i.e. their aggressive merge. 5063 static IntRange meet(IntRange L, IntRange R) { 5064 return IntRange(std::min(L.Width, R.Width), 5065 L.NonNegative || R.NonNegative); 5066 } 5067 }; 5068 5069 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 5070 unsigned MaxWidth) { 5071 if (value.isSigned() && value.isNegative()) 5072 return IntRange(value.getMinSignedBits(), false); 5073 5074 if (value.getBitWidth() > MaxWidth) 5075 value = value.trunc(MaxWidth); 5076 5077 // isNonNegative() just checks the sign bit without considering 5078 // signedness. 5079 return IntRange(value.getActiveBits(), true); 5080 } 5081 5082 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 5083 unsigned MaxWidth) { 5084 if (result.isInt()) 5085 return GetValueRange(C, result.getInt(), MaxWidth); 5086 5087 if (result.isVector()) { 5088 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 5089 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 5090 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 5091 R = IntRange::join(R, El); 5092 } 5093 return R; 5094 } 5095 5096 if (result.isComplexInt()) { 5097 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 5098 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 5099 return IntRange::join(R, I); 5100 } 5101 5102 // This can happen with lossless casts to intptr_t of "based" lvalues. 5103 // Assume it might use arbitrary bits. 5104 // FIXME: The only reason we need to pass the type in here is to get 5105 // the sign right on this one case. It would be nice if APValue 5106 // preserved this. 5107 assert(result.isLValue() || result.isAddrLabelDiff()); 5108 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 5109 } 5110 5111 static QualType GetExprType(Expr *E) { 5112 QualType Ty = E->getType(); 5113 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 5114 Ty = AtomicRHS->getValueType(); 5115 return Ty; 5116 } 5117 5118 /// Pseudo-evaluate the given integer expression, estimating the 5119 /// range of values it might take. 5120 /// 5121 /// \param MaxWidth - the width to which the value will be truncated 5122 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 5123 E = E->IgnoreParens(); 5124 5125 // Try a full evaluation first. 5126 Expr::EvalResult result; 5127 if (E->EvaluateAsRValue(result, C)) 5128 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 5129 5130 // I think we only want to look through implicit casts here; if the 5131 // user has an explicit widening cast, we should treat the value as 5132 // being of the new, wider type. 5133 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 5134 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 5135 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 5136 5137 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 5138 5139 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 5140 5141 // Assume that non-integer casts can span the full range of the type. 5142 if (!isIntegerCast) 5143 return OutputTypeRange; 5144 5145 IntRange SubRange 5146 = GetExprRange(C, CE->getSubExpr(), 5147 std::min(MaxWidth, OutputTypeRange.Width)); 5148 5149 // Bail out if the subexpr's range is as wide as the cast type. 5150 if (SubRange.Width >= OutputTypeRange.Width) 5151 return OutputTypeRange; 5152 5153 // Otherwise, we take the smaller width, and we're non-negative if 5154 // either the output type or the subexpr is. 5155 return IntRange(SubRange.Width, 5156 SubRange.NonNegative || OutputTypeRange.NonNegative); 5157 } 5158 5159 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5160 // If we can fold the condition, just take that operand. 5161 bool CondResult; 5162 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 5163 return GetExprRange(C, CondResult ? CO->getTrueExpr() 5164 : CO->getFalseExpr(), 5165 MaxWidth); 5166 5167 // Otherwise, conservatively merge. 5168 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 5169 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 5170 return IntRange::join(L, R); 5171 } 5172 5173 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5174 switch (BO->getOpcode()) { 5175 5176 // Boolean-valued operations are single-bit and positive. 5177 case BO_LAnd: 5178 case BO_LOr: 5179 case BO_LT: 5180 case BO_GT: 5181 case BO_LE: 5182 case BO_GE: 5183 case BO_EQ: 5184 case BO_NE: 5185 return IntRange::forBoolType(); 5186 5187 // The type of the assignments is the type of the LHS, so the RHS 5188 // is not necessarily the same type. 5189 case BO_MulAssign: 5190 case BO_DivAssign: 5191 case BO_RemAssign: 5192 case BO_AddAssign: 5193 case BO_SubAssign: 5194 case BO_XorAssign: 5195 case BO_OrAssign: 5196 // TODO: bitfields? 5197 return IntRange::forValueOfType(C, GetExprType(E)); 5198 5199 // Simple assignments just pass through the RHS, which will have 5200 // been coerced to the LHS type. 5201 case BO_Assign: 5202 // TODO: bitfields? 5203 return GetExprRange(C, BO->getRHS(), MaxWidth); 5204 5205 // Operations with opaque sources are black-listed. 5206 case BO_PtrMemD: 5207 case BO_PtrMemI: 5208 return IntRange::forValueOfType(C, GetExprType(E)); 5209 5210 // Bitwise-and uses the *infinum* of the two source ranges. 5211 case BO_And: 5212 case BO_AndAssign: 5213 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 5214 GetExprRange(C, BO->getRHS(), MaxWidth)); 5215 5216 // Left shift gets black-listed based on a judgement call. 5217 case BO_Shl: 5218 // ...except that we want to treat '1 << (blah)' as logically 5219 // positive. It's an important idiom. 5220 if (IntegerLiteral *I 5221 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 5222 if (I->getValue() == 1) { 5223 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 5224 return IntRange(R.Width, /*NonNegative*/ true); 5225 } 5226 } 5227 // fallthrough 5228 5229 case BO_ShlAssign: 5230 return IntRange::forValueOfType(C, GetExprType(E)); 5231 5232 // Right shift by a constant can narrow its left argument. 5233 case BO_Shr: 5234 case BO_ShrAssign: { 5235 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5236 5237 // If the shift amount is a positive constant, drop the width by 5238 // that much. 5239 llvm::APSInt shift; 5240 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 5241 shift.isNonNegative()) { 5242 unsigned zext = shift.getZExtValue(); 5243 if (zext >= L.Width) 5244 L.Width = (L.NonNegative ? 0 : 1); 5245 else 5246 L.Width -= zext; 5247 } 5248 5249 return L; 5250 } 5251 5252 // Comma acts as its right operand. 5253 case BO_Comma: 5254 return GetExprRange(C, BO->getRHS(), MaxWidth); 5255 5256 // Black-list pointer subtractions. 5257 case BO_Sub: 5258 if (BO->getLHS()->getType()->isPointerType()) 5259 return IntRange::forValueOfType(C, GetExprType(E)); 5260 break; 5261 5262 // The width of a division result is mostly determined by the size 5263 // of the LHS. 5264 case BO_Div: { 5265 // Don't 'pre-truncate' the operands. 5266 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5267 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5268 5269 // If the divisor is constant, use that. 5270 llvm::APSInt divisor; 5271 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 5272 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 5273 if (log2 >= L.Width) 5274 L.Width = (L.NonNegative ? 0 : 1); 5275 else 5276 L.Width = std::min(L.Width - log2, MaxWidth); 5277 return L; 5278 } 5279 5280 // Otherwise, just use the LHS's width. 5281 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5282 return IntRange(L.Width, L.NonNegative && R.NonNegative); 5283 } 5284 5285 // The result of a remainder can't be larger than the result of 5286 // either side. 5287 case BO_Rem: { 5288 // Don't 'pre-truncate' the operands. 5289 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5290 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5291 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5292 5293 IntRange meet = IntRange::meet(L, R); 5294 meet.Width = std::min(meet.Width, MaxWidth); 5295 return meet; 5296 } 5297 5298 // The default behavior is okay for these. 5299 case BO_Mul: 5300 case BO_Add: 5301 case BO_Xor: 5302 case BO_Or: 5303 break; 5304 } 5305 5306 // The default case is to treat the operation as if it were closed 5307 // on the narrowest type that encompasses both operands. 5308 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5309 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 5310 return IntRange::join(L, R); 5311 } 5312 5313 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 5314 switch (UO->getOpcode()) { 5315 // Boolean-valued operations are white-listed. 5316 case UO_LNot: 5317 return IntRange::forBoolType(); 5318 5319 // Operations with opaque sources are black-listed. 5320 case UO_Deref: 5321 case UO_AddrOf: // should be impossible 5322 return IntRange::forValueOfType(C, GetExprType(E)); 5323 5324 default: 5325 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 5326 } 5327 } 5328 5329 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 5330 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 5331 5332 if (FieldDecl *BitField = E->getSourceBitField()) 5333 return IntRange(BitField->getBitWidthValue(C), 5334 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 5335 5336 return IntRange::forValueOfType(C, GetExprType(E)); 5337 } 5338 5339 static IntRange GetExprRange(ASTContext &C, Expr *E) { 5340 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 5341 } 5342 5343 /// Checks whether the given value, which currently has the given 5344 /// source semantics, has the same value when coerced through the 5345 /// target semantics. 5346 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 5347 const llvm::fltSemantics &Src, 5348 const llvm::fltSemantics &Tgt) { 5349 llvm::APFloat truncated = value; 5350 5351 bool ignored; 5352 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 5353 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 5354 5355 return truncated.bitwiseIsEqual(value); 5356 } 5357 5358 /// Checks whether the given value, which currently has the given 5359 /// source semantics, has the same value when coerced through the 5360 /// target semantics. 5361 /// 5362 /// The value might be a vector of floats (or a complex number). 5363 static bool IsSameFloatAfterCast(const APValue &value, 5364 const llvm::fltSemantics &Src, 5365 const llvm::fltSemantics &Tgt) { 5366 if (value.isFloat()) 5367 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 5368 5369 if (value.isVector()) { 5370 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 5371 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 5372 return false; 5373 return true; 5374 } 5375 5376 assert(value.isComplexFloat()); 5377 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 5378 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 5379 } 5380 5381 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 5382 5383 static bool IsZero(Sema &S, Expr *E) { 5384 // Suppress cases where we are comparing against an enum constant. 5385 if (const DeclRefExpr *DR = 5386 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 5387 if (isa<EnumConstantDecl>(DR->getDecl())) 5388 return false; 5389 5390 // Suppress cases where the '0' value is expanded from a macro. 5391 if (E->getLocStart().isMacroID()) 5392 return false; 5393 5394 llvm::APSInt Value; 5395 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 5396 } 5397 5398 static bool HasEnumType(Expr *E) { 5399 // Strip off implicit integral promotions. 5400 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5401 if (ICE->getCastKind() != CK_IntegralCast && 5402 ICE->getCastKind() != CK_NoOp) 5403 break; 5404 E = ICE->getSubExpr(); 5405 } 5406 5407 return E->getType()->isEnumeralType(); 5408 } 5409 5410 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 5411 // Disable warning in template instantiations. 5412 if (!S.ActiveTemplateInstantiations.empty()) 5413 return; 5414 5415 BinaryOperatorKind op = E->getOpcode(); 5416 if (E->isValueDependent()) 5417 return; 5418 5419 if (op == BO_LT && IsZero(S, E->getRHS())) { 5420 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5421 << "< 0" << "false" << HasEnumType(E->getLHS()) 5422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5423 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 5424 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5425 << ">= 0" << "true" << HasEnumType(E->getLHS()) 5426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5427 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 5428 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5429 << "0 >" << "false" << HasEnumType(E->getRHS()) 5430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5431 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 5432 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5433 << "0 <=" << "true" << HasEnumType(E->getRHS()) 5434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5435 } 5436 } 5437 5438 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 5439 Expr *Constant, Expr *Other, 5440 llvm::APSInt Value, 5441 bool RhsConstant) { 5442 // Disable warning in template instantiations. 5443 if (!S.ActiveTemplateInstantiations.empty()) 5444 return; 5445 5446 // TODO: Investigate using GetExprRange() to get tighter bounds 5447 // on the bit ranges. 5448 QualType OtherT = Other->getType(); 5449 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT)) 5450 OtherT = AT->getValueType(); 5451 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 5452 unsigned OtherWidth = OtherRange.Width; 5453 5454 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 5455 5456 // 0 values are handled later by CheckTrivialUnsignedComparison(). 5457 if ((Value == 0) && (!OtherIsBooleanType)) 5458 return; 5459 5460 BinaryOperatorKind op = E->getOpcode(); 5461 bool IsTrue = true; 5462 5463 // Used for diagnostic printout. 5464 enum { 5465 LiteralConstant = 0, 5466 CXXBoolLiteralTrue, 5467 CXXBoolLiteralFalse 5468 } LiteralOrBoolConstant = LiteralConstant; 5469 5470 if (!OtherIsBooleanType) { 5471 QualType ConstantT = Constant->getType(); 5472 QualType CommonT = E->getLHS()->getType(); 5473 5474 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 5475 return; 5476 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 5477 "comparison with non-integer type"); 5478 5479 bool ConstantSigned = ConstantT->isSignedIntegerType(); 5480 bool CommonSigned = CommonT->isSignedIntegerType(); 5481 5482 bool EqualityOnly = false; 5483 5484 if (CommonSigned) { 5485 // The common type is signed, therefore no signed to unsigned conversion. 5486 if (!OtherRange.NonNegative) { 5487 // Check that the constant is representable in type OtherT. 5488 if (ConstantSigned) { 5489 if (OtherWidth >= Value.getMinSignedBits()) 5490 return; 5491 } else { // !ConstantSigned 5492 if (OtherWidth >= Value.getActiveBits() + 1) 5493 return; 5494 } 5495 } else { // !OtherSigned 5496 // Check that the constant is representable in type OtherT. 5497 // Negative values are out of range. 5498 if (ConstantSigned) { 5499 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 5500 return; 5501 } else { // !ConstantSigned 5502 if (OtherWidth >= Value.getActiveBits()) 5503 return; 5504 } 5505 } 5506 } else { // !CommonSigned 5507 if (OtherRange.NonNegative) { 5508 if (OtherWidth >= Value.getActiveBits()) 5509 return; 5510 } else { // OtherSigned 5511 assert(!ConstantSigned && 5512 "Two signed types converted to unsigned types."); 5513 // Check to see if the constant is representable in OtherT. 5514 if (OtherWidth > Value.getActiveBits()) 5515 return; 5516 // Check to see if the constant is equivalent to a negative value 5517 // cast to CommonT. 5518 if (S.Context.getIntWidth(ConstantT) == 5519 S.Context.getIntWidth(CommonT) && 5520 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 5521 return; 5522 // The constant value rests between values that OtherT can represent 5523 // after conversion. Relational comparison still works, but equality 5524 // comparisons will be tautological. 5525 EqualityOnly = true; 5526 } 5527 } 5528 5529 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 5530 5531 if (op == BO_EQ || op == BO_NE) { 5532 IsTrue = op == BO_NE; 5533 } else if (EqualityOnly) { 5534 return; 5535 } else if (RhsConstant) { 5536 if (op == BO_GT || op == BO_GE) 5537 IsTrue = !PositiveConstant; 5538 else // op == BO_LT || op == BO_LE 5539 IsTrue = PositiveConstant; 5540 } else { 5541 if (op == BO_LT || op == BO_LE) 5542 IsTrue = !PositiveConstant; 5543 else // op == BO_GT || op == BO_GE 5544 IsTrue = PositiveConstant; 5545 } 5546 } else { 5547 // Other isKnownToHaveBooleanValue 5548 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 5549 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 5550 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 5551 5552 static const struct LinkedConditions { 5553 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 5554 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 5555 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 5556 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 5557 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 5558 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 5559 5560 } TruthTable = { 5561 // Constant on LHS. | Constant on RHS. | 5562 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 5563 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 5564 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 5565 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 5566 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 5567 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 5568 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 5569 }; 5570 5571 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 5572 5573 enum ConstantValue ConstVal = Zero; 5574 if (Value.isUnsigned() || Value.isNonNegative()) { 5575 if (Value == 0) { 5576 LiteralOrBoolConstant = 5577 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 5578 ConstVal = Zero; 5579 } else if (Value == 1) { 5580 LiteralOrBoolConstant = 5581 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 5582 ConstVal = One; 5583 } else { 5584 LiteralOrBoolConstant = LiteralConstant; 5585 ConstVal = GT_One; 5586 } 5587 } else { 5588 ConstVal = LT_Zero; 5589 } 5590 5591 CompareBoolWithConstantResult CmpRes; 5592 5593 switch (op) { 5594 case BO_LT: 5595 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 5596 break; 5597 case BO_GT: 5598 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 5599 break; 5600 case BO_LE: 5601 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 5602 break; 5603 case BO_GE: 5604 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 5605 break; 5606 case BO_EQ: 5607 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 5608 break; 5609 case BO_NE: 5610 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 5611 break; 5612 default: 5613 CmpRes = Unkwn; 5614 break; 5615 } 5616 5617 if (CmpRes == AFals) { 5618 IsTrue = false; 5619 } else if (CmpRes == ATrue) { 5620 IsTrue = true; 5621 } else { 5622 return; 5623 } 5624 } 5625 5626 // If this is a comparison to an enum constant, include that 5627 // constant in the diagnostic. 5628 const EnumConstantDecl *ED = nullptr; 5629 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 5630 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 5631 5632 SmallString<64> PrettySourceValue; 5633 llvm::raw_svector_ostream OS(PrettySourceValue); 5634 if (ED) 5635 OS << '\'' << *ED << "' (" << Value << ")"; 5636 else 5637 OS << Value; 5638 5639 S.DiagRuntimeBehavior( 5640 E->getOperatorLoc(), E, 5641 S.PDiag(diag::warn_out_of_range_compare) 5642 << OS.str() << LiteralOrBoolConstant 5643 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 5644 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 5645 } 5646 5647 /// Analyze the operands of the given comparison. Implements the 5648 /// fallback case from AnalyzeComparison. 5649 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 5650 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5651 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5652 } 5653 5654 /// \brief Implements -Wsign-compare. 5655 /// 5656 /// \param E the binary operator to check for warnings 5657 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 5658 // The type the comparison is being performed in. 5659 QualType T = E->getLHS()->getType(); 5660 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 5661 && "comparison with mismatched types"); 5662 if (E->isValueDependent()) 5663 return AnalyzeImpConvsInComparison(S, E); 5664 5665 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 5666 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 5667 5668 bool IsComparisonConstant = false; 5669 5670 // Check whether an integer constant comparison results in a value 5671 // of 'true' or 'false'. 5672 if (T->isIntegralType(S.Context)) { 5673 llvm::APSInt RHSValue; 5674 bool IsRHSIntegralLiteral = 5675 RHS->isIntegerConstantExpr(RHSValue, S.Context); 5676 llvm::APSInt LHSValue; 5677 bool IsLHSIntegralLiteral = 5678 LHS->isIntegerConstantExpr(LHSValue, S.Context); 5679 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 5680 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 5681 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 5682 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 5683 else 5684 IsComparisonConstant = 5685 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 5686 } else if (!T->hasUnsignedIntegerRepresentation()) 5687 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 5688 5689 // We don't do anything special if this isn't an unsigned integral 5690 // comparison: we're only interested in integral comparisons, and 5691 // signed comparisons only happen in cases we don't care to warn about. 5692 // 5693 // We also don't care about value-dependent expressions or expressions 5694 // whose result is a constant. 5695 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 5696 return AnalyzeImpConvsInComparison(S, E); 5697 5698 // Check to see if one of the (unmodified) operands is of different 5699 // signedness. 5700 Expr *signedOperand, *unsignedOperand; 5701 if (LHS->getType()->hasSignedIntegerRepresentation()) { 5702 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 5703 "unsigned comparison between two signed integer expressions?"); 5704 signedOperand = LHS; 5705 unsignedOperand = RHS; 5706 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 5707 signedOperand = RHS; 5708 unsignedOperand = LHS; 5709 } else { 5710 CheckTrivialUnsignedComparison(S, E); 5711 return AnalyzeImpConvsInComparison(S, E); 5712 } 5713 5714 // Otherwise, calculate the effective range of the signed operand. 5715 IntRange signedRange = GetExprRange(S.Context, signedOperand); 5716 5717 // Go ahead and analyze implicit conversions in the operands. Note 5718 // that we skip the implicit conversions on both sides. 5719 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 5720 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 5721 5722 // If the signed range is non-negative, -Wsign-compare won't fire, 5723 // but we should still check for comparisons which are always true 5724 // or false. 5725 if (signedRange.NonNegative) 5726 return CheckTrivialUnsignedComparison(S, E); 5727 5728 // For (in)equality comparisons, if the unsigned operand is a 5729 // constant which cannot collide with a overflowed signed operand, 5730 // then reinterpreting the signed operand as unsigned will not 5731 // change the result of the comparison. 5732 if (E->isEqualityOp()) { 5733 unsigned comparisonWidth = S.Context.getIntWidth(T); 5734 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 5735 5736 // We should never be unable to prove that the unsigned operand is 5737 // non-negative. 5738 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 5739 5740 if (unsignedRange.Width < comparisonWidth) 5741 return; 5742 } 5743 5744 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 5745 S.PDiag(diag::warn_mixed_sign_comparison) 5746 << LHS->getType() << RHS->getType() 5747 << LHS->getSourceRange() << RHS->getSourceRange()); 5748 } 5749 5750 /// Analyzes an attempt to assign the given value to a bitfield. 5751 /// 5752 /// Returns true if there was something fishy about the attempt. 5753 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 5754 SourceLocation InitLoc) { 5755 assert(Bitfield->isBitField()); 5756 if (Bitfield->isInvalidDecl()) 5757 return false; 5758 5759 // White-list bool bitfields. 5760 if (Bitfield->getType()->isBooleanType()) 5761 return false; 5762 5763 // Ignore value- or type-dependent expressions. 5764 if (Bitfield->getBitWidth()->isValueDependent() || 5765 Bitfield->getBitWidth()->isTypeDependent() || 5766 Init->isValueDependent() || 5767 Init->isTypeDependent()) 5768 return false; 5769 5770 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 5771 5772 llvm::APSInt Value; 5773 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 5774 return false; 5775 5776 unsigned OriginalWidth = Value.getBitWidth(); 5777 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 5778 5779 if (OriginalWidth <= FieldWidth) 5780 return false; 5781 5782 // Compute the value which the bitfield will contain. 5783 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 5784 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 5785 5786 // Check whether the stored value is equal to the original value. 5787 TruncatedValue = TruncatedValue.extend(OriginalWidth); 5788 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 5789 return false; 5790 5791 // Special-case bitfields of width 1: booleans are naturally 0/1, and 5792 // therefore don't strictly fit into a signed bitfield of width 1. 5793 if (FieldWidth == 1 && Value == 1) 5794 return false; 5795 5796 std::string PrettyValue = Value.toString(10); 5797 std::string PrettyTrunc = TruncatedValue.toString(10); 5798 5799 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 5800 << PrettyValue << PrettyTrunc << OriginalInit->getType() 5801 << Init->getSourceRange(); 5802 5803 return true; 5804 } 5805 5806 /// Analyze the given simple or compound assignment for warning-worthy 5807 /// operations. 5808 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 5809 // Just recurse on the LHS. 5810 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5811 5812 // We want to recurse on the RHS as normal unless we're assigning to 5813 // a bitfield. 5814 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 5815 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 5816 E->getOperatorLoc())) { 5817 // Recurse, ignoring any implicit conversions on the RHS. 5818 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 5819 E->getOperatorLoc()); 5820 } 5821 } 5822 5823 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5824 } 5825 5826 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5827 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 5828 SourceLocation CContext, unsigned diag, 5829 bool pruneControlFlow = false) { 5830 if (pruneControlFlow) { 5831 S.DiagRuntimeBehavior(E->getExprLoc(), E, 5832 S.PDiag(diag) 5833 << SourceType << T << E->getSourceRange() 5834 << SourceRange(CContext)); 5835 return; 5836 } 5837 S.Diag(E->getExprLoc(), diag) 5838 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 5839 } 5840 5841 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 5842 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 5843 SourceLocation CContext, unsigned diag, 5844 bool pruneControlFlow = false) { 5845 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 5846 } 5847 5848 /// Diagnose an implicit cast from a literal expression. Does not warn when the 5849 /// cast wouldn't lose information. 5850 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 5851 SourceLocation CContext) { 5852 // Try to convert the literal exactly to an integer. If we can, don't warn. 5853 bool isExact = false; 5854 const llvm::APFloat &Value = FL->getValue(); 5855 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 5856 T->hasUnsignedIntegerRepresentation()); 5857 if (Value.convertToInteger(IntegerValue, 5858 llvm::APFloat::rmTowardZero, &isExact) 5859 == llvm::APFloat::opOK && isExact) 5860 return; 5861 5862 // FIXME: Force the precision of the source value down so we don't print 5863 // digits which are usually useless (we don't really care here if we 5864 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 5865 // would automatically print the shortest representation, but it's a bit 5866 // tricky to implement. 5867 SmallString<16> PrettySourceValue; 5868 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 5869 precision = (precision * 59 + 195) / 196; 5870 Value.toString(PrettySourceValue, precision); 5871 5872 SmallString<16> PrettyTargetValue; 5873 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 5874 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 5875 else 5876 IntegerValue.toString(PrettyTargetValue); 5877 5878 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 5879 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 5880 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 5881 } 5882 5883 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 5884 if (!Range.Width) return "0"; 5885 5886 llvm::APSInt ValueInRange = Value; 5887 ValueInRange.setIsSigned(!Range.NonNegative); 5888 ValueInRange = ValueInRange.trunc(Range.Width); 5889 return ValueInRange.toString(10); 5890 } 5891 5892 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 5893 if (!isa<ImplicitCastExpr>(Ex)) 5894 return false; 5895 5896 Expr *InnerE = Ex->IgnoreParenImpCasts(); 5897 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 5898 const Type *Source = 5899 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 5900 if (Target->isDependentType()) 5901 return false; 5902 5903 const BuiltinType *FloatCandidateBT = 5904 dyn_cast<BuiltinType>(ToBool ? Source : Target); 5905 const Type *BoolCandidateType = ToBool ? Target : Source; 5906 5907 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 5908 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 5909 } 5910 5911 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 5912 SourceLocation CC) { 5913 unsigned NumArgs = TheCall->getNumArgs(); 5914 for (unsigned i = 0; i < NumArgs; ++i) { 5915 Expr *CurrA = TheCall->getArg(i); 5916 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 5917 continue; 5918 5919 bool IsSwapped = ((i > 0) && 5920 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 5921 IsSwapped |= ((i < (NumArgs - 1)) && 5922 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 5923 if (IsSwapped) { 5924 // Warn on this floating-point to bool conversion. 5925 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 5926 CurrA->getType(), CC, 5927 diag::warn_impcast_floating_point_to_bool); 5928 } 5929 } 5930 } 5931 5932 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 5933 SourceLocation CC, bool *ICContext = nullptr) { 5934 if (E->isTypeDependent() || E->isValueDependent()) return; 5935 5936 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 5937 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 5938 if (Source == Target) return; 5939 if (Target->isDependentType()) return; 5940 5941 // If the conversion context location is invalid don't complain. We also 5942 // don't want to emit a warning if the issue occurs from the expansion of 5943 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 5944 // delay this check as long as possible. Once we detect we are in that 5945 // scenario, we just return. 5946 if (CC.isInvalid()) 5947 return; 5948 5949 // Diagnose implicit casts to bool. 5950 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 5951 if (isa<StringLiteral>(E)) 5952 // Warn on string literal to bool. Checks for string literals in logical 5953 // and expressions, for instance, assert(0 && "error here"), are 5954 // prevented by a check in AnalyzeImplicitConversions(). 5955 return DiagnoseImpCast(S, E, T, CC, 5956 diag::warn_impcast_string_literal_to_bool); 5957 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 5958 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 5959 // This covers the literal expressions that evaluate to Objective-C 5960 // objects. 5961 return DiagnoseImpCast(S, E, T, CC, 5962 diag::warn_impcast_objective_c_literal_to_bool); 5963 } 5964 if (Source->isPointerType() || Source->canDecayToPointerType()) { 5965 // Warn on pointer to bool conversion that is always true. 5966 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 5967 SourceRange(CC)); 5968 } 5969 } 5970 5971 // Strip vector types. 5972 if (isa<VectorType>(Source)) { 5973 if (!isa<VectorType>(Target)) { 5974 if (S.SourceMgr.isInSystemMacro(CC)) 5975 return; 5976 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 5977 } 5978 5979 // If the vector cast is cast between two vectors of the same size, it is 5980 // a bitcast, not a conversion. 5981 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 5982 return; 5983 5984 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 5985 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 5986 } 5987 if (auto VecTy = dyn_cast<VectorType>(Target)) 5988 Target = VecTy->getElementType().getTypePtr(); 5989 5990 // Strip complex types. 5991 if (isa<ComplexType>(Source)) { 5992 if (!isa<ComplexType>(Target)) { 5993 if (S.SourceMgr.isInSystemMacro(CC)) 5994 return; 5995 5996 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 5997 } 5998 5999 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 6000 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 6001 } 6002 6003 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 6004 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 6005 6006 // If the source is floating point... 6007 if (SourceBT && SourceBT->isFloatingPoint()) { 6008 // ...and the target is floating point... 6009 if (TargetBT && TargetBT->isFloatingPoint()) { 6010 // ...then warn if we're dropping FP rank. 6011 6012 // Builtin FP kinds are ordered by increasing FP rank. 6013 if (SourceBT->getKind() > TargetBT->getKind()) { 6014 // Don't warn about float constants that are precisely 6015 // representable in the target type. 6016 Expr::EvalResult result; 6017 if (E->EvaluateAsRValue(result, S.Context)) { 6018 // Value might be a float, a float vector, or a float complex. 6019 if (IsSameFloatAfterCast(result.Val, 6020 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 6021 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 6022 return; 6023 } 6024 6025 if (S.SourceMgr.isInSystemMacro(CC)) 6026 return; 6027 6028 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 6029 } 6030 return; 6031 } 6032 6033 // If the target is integral, always warn. 6034 if (TargetBT && TargetBT->isInteger()) { 6035 if (S.SourceMgr.isInSystemMacro(CC)) 6036 return; 6037 6038 Expr *InnerE = E->IgnoreParenImpCasts(); 6039 // We also want to warn on, e.g., "int i = -1.234" 6040 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 6041 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 6042 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 6043 6044 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 6045 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 6046 } else { 6047 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 6048 } 6049 } 6050 6051 // If the target is bool, warn if expr is a function or method call. 6052 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 6053 isa<CallExpr>(E)) { 6054 // Check last argument of function call to see if it is an 6055 // implicit cast from a type matching the type the result 6056 // is being cast to. 6057 CallExpr *CEx = cast<CallExpr>(E); 6058 unsigned NumArgs = CEx->getNumArgs(); 6059 if (NumArgs > 0) { 6060 Expr *LastA = CEx->getArg(NumArgs - 1); 6061 Expr *InnerE = LastA->IgnoreParenImpCasts(); 6062 const Type *InnerType = 6063 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 6064 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 6065 // Warn on this floating-point to bool conversion 6066 DiagnoseImpCast(S, E, T, CC, 6067 diag::warn_impcast_floating_point_to_bool); 6068 } 6069 } 6070 } 6071 return; 6072 } 6073 6074 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 6075 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 6076 && !Target->isBlockPointerType() && !Target->isMemberPointerType() 6077 && Target->isScalarType() && !Target->isNullPtrType()) { 6078 SourceLocation Loc = E->getSourceRange().getBegin(); 6079 if (Loc.isMacroID()) 6080 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 6081 if (!Loc.isMacroID() || CC.isMacroID()) 6082 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 6083 << T << clang::SourceRange(CC) 6084 << FixItHint::CreateReplacement(Loc, 6085 S.getFixItZeroLiteralForType(T, Loc)); 6086 } 6087 6088 if (!Source->isIntegerType() || !Target->isIntegerType()) 6089 return; 6090 6091 // TODO: remove this early return once the false positives for constant->bool 6092 // in templates, macros, etc, are reduced or removed. 6093 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 6094 return; 6095 6096 IntRange SourceRange = GetExprRange(S.Context, E); 6097 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 6098 6099 if (SourceRange.Width > TargetRange.Width) { 6100 // If the source is a constant, use a default-on diagnostic. 6101 // TODO: this should happen for bitfield stores, too. 6102 llvm::APSInt Value(32); 6103 if (E->isIntegerConstantExpr(Value, S.Context)) { 6104 if (S.SourceMgr.isInSystemMacro(CC)) 6105 return; 6106 6107 std::string PrettySourceValue = Value.toString(10); 6108 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 6109 6110 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6111 S.PDiag(diag::warn_impcast_integer_precision_constant) 6112 << PrettySourceValue << PrettyTargetValue 6113 << E->getType() << T << E->getSourceRange() 6114 << clang::SourceRange(CC)); 6115 return; 6116 } 6117 6118 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 6119 if (S.SourceMgr.isInSystemMacro(CC)) 6120 return; 6121 6122 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 6123 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 6124 /* pruneControlFlow */ true); 6125 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 6126 } 6127 6128 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 6129 (!TargetRange.NonNegative && SourceRange.NonNegative && 6130 SourceRange.Width == TargetRange.Width)) { 6131 6132 if (S.SourceMgr.isInSystemMacro(CC)) 6133 return; 6134 6135 unsigned DiagID = diag::warn_impcast_integer_sign; 6136 6137 // Traditionally, gcc has warned about this under -Wsign-compare. 6138 // We also want to warn about it in -Wconversion. 6139 // So if -Wconversion is off, use a completely identical diagnostic 6140 // in the sign-compare group. 6141 // The conditional-checking code will 6142 if (ICContext) { 6143 DiagID = diag::warn_impcast_integer_sign_conditional; 6144 *ICContext = true; 6145 } 6146 6147 return DiagnoseImpCast(S, E, T, CC, DiagID); 6148 } 6149 6150 // Diagnose conversions between different enumeration types. 6151 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 6152 // type, to give us better diagnostics. 6153 QualType SourceType = E->getType(); 6154 if (!S.getLangOpts().CPlusPlus) { 6155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6156 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 6157 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 6158 SourceType = S.Context.getTypeDeclType(Enum); 6159 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 6160 } 6161 } 6162 6163 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 6164 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 6165 if (SourceEnum->getDecl()->hasNameForLinkage() && 6166 TargetEnum->getDecl()->hasNameForLinkage() && 6167 SourceEnum != TargetEnum) { 6168 if (S.SourceMgr.isInSystemMacro(CC)) 6169 return; 6170 6171 return DiagnoseImpCast(S, E, SourceType, T, CC, 6172 diag::warn_impcast_different_enum_types); 6173 } 6174 6175 return; 6176 } 6177 6178 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6179 SourceLocation CC, QualType T); 6180 6181 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 6182 SourceLocation CC, bool &ICContext) { 6183 E = E->IgnoreParenImpCasts(); 6184 6185 if (isa<ConditionalOperator>(E)) 6186 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 6187 6188 AnalyzeImplicitConversions(S, E, CC); 6189 if (E->getType() != T) 6190 return CheckImplicitConversion(S, E, T, CC, &ICContext); 6191 return; 6192 } 6193 6194 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6195 SourceLocation CC, QualType T) { 6196 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 6197 6198 bool Suspicious = false; 6199 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 6200 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 6201 6202 // If -Wconversion would have warned about either of the candidates 6203 // for a signedness conversion to the context type... 6204 if (!Suspicious) return; 6205 6206 // ...but it's currently ignored... 6207 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 6208 return; 6209 6210 // ...then check whether it would have warned about either of the 6211 // candidates for a signedness conversion to the condition type. 6212 if (E->getType() == T) return; 6213 6214 Suspicious = false; 6215 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 6216 E->getType(), CC, &Suspicious); 6217 if (!Suspicious) 6218 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 6219 E->getType(), CC, &Suspicious); 6220 } 6221 6222 /// AnalyzeImplicitConversions - Find and report any interesting 6223 /// implicit conversions in the given expression. There are a couple 6224 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 6225 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 6226 QualType T = OrigE->getType(); 6227 Expr *E = OrigE->IgnoreParenImpCasts(); 6228 6229 if (E->isTypeDependent() || E->isValueDependent()) 6230 return; 6231 6232 // For conditional operators, we analyze the arguments as if they 6233 // were being fed directly into the output. 6234 if (isa<ConditionalOperator>(E)) { 6235 ConditionalOperator *CO = cast<ConditionalOperator>(E); 6236 CheckConditionalOperator(S, CO, CC, T); 6237 return; 6238 } 6239 6240 // Check implicit argument conversions for function calls. 6241 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 6242 CheckImplicitArgumentConversions(S, Call, CC); 6243 6244 // Go ahead and check any implicit conversions we might have skipped. 6245 // The non-canonical typecheck is just an optimization; 6246 // CheckImplicitConversion will filter out dead implicit conversions. 6247 if (E->getType() != T) 6248 CheckImplicitConversion(S, E, T, CC); 6249 6250 // Now continue drilling into this expression. 6251 6252 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) { 6253 if (POE->getResultExpr()) 6254 E = POE->getResultExpr(); 6255 } 6256 6257 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 6258 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 6259 6260 // Skip past explicit casts. 6261 if (isa<ExplicitCastExpr>(E)) { 6262 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 6263 return AnalyzeImplicitConversions(S, E, CC); 6264 } 6265 6266 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6267 // Do a somewhat different check with comparison operators. 6268 if (BO->isComparisonOp()) 6269 return AnalyzeComparison(S, BO); 6270 6271 // And with simple assignments. 6272 if (BO->getOpcode() == BO_Assign) 6273 return AnalyzeAssignment(S, BO); 6274 } 6275 6276 // These break the otherwise-useful invariant below. Fortunately, 6277 // we don't really need to recurse into them, because any internal 6278 // expressions should have been analyzed already when they were 6279 // built into statements. 6280 if (isa<StmtExpr>(E)) return; 6281 6282 // Don't descend into unevaluated contexts. 6283 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 6284 6285 // Now just recurse over the expression's children. 6286 CC = E->getExprLoc(); 6287 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 6288 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 6289 for (Stmt::child_range I = E->children(); I; ++I) { 6290 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 6291 if (!ChildExpr) 6292 continue; 6293 6294 if (IsLogicalAndOperator && 6295 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 6296 // Ignore checking string literals that are in logical and operators. 6297 // This is a common pattern for asserts. 6298 continue; 6299 AnalyzeImplicitConversions(S, ChildExpr, CC); 6300 } 6301 } 6302 6303 } // end anonymous namespace 6304 6305 enum { 6306 AddressOf, 6307 FunctionPointer, 6308 ArrayPointer 6309 }; 6310 6311 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 6312 // Returns true when emitting a warning about taking the address of a reference. 6313 static bool CheckForReference(Sema &SemaRef, const Expr *E, 6314 PartialDiagnostic PD) { 6315 E = E->IgnoreParenImpCasts(); 6316 6317 const FunctionDecl *FD = nullptr; 6318 6319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6320 if (!DRE->getDecl()->getType()->isReferenceType()) 6321 return false; 6322 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6323 if (!M->getMemberDecl()->getType()->isReferenceType()) 6324 return false; 6325 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 6326 if (!Call->getCallReturnType()->isReferenceType()) 6327 return false; 6328 FD = Call->getDirectCallee(); 6329 } else { 6330 return false; 6331 } 6332 6333 SemaRef.Diag(E->getExprLoc(), PD); 6334 6335 // If possible, point to location of function. 6336 if (FD) { 6337 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 6338 } 6339 6340 return true; 6341 } 6342 6343 // Returns true if the SourceLocation is expanded from any macro body. 6344 // Returns false if the SourceLocation is invalid, is from not in a macro 6345 // expansion, or is from expanded from a top-level macro argument. 6346 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 6347 if (Loc.isInvalid()) 6348 return false; 6349 6350 while (Loc.isMacroID()) { 6351 if (SM.isMacroBodyExpansion(Loc)) 6352 return true; 6353 Loc = SM.getImmediateMacroCallerLoc(Loc); 6354 } 6355 6356 return false; 6357 } 6358 6359 /// \brief Diagnose pointers that are always non-null. 6360 /// \param E the expression containing the pointer 6361 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 6362 /// compared to a null pointer 6363 /// \param IsEqual True when the comparison is equal to a null pointer 6364 /// \param Range Extra SourceRange to highlight in the diagnostic 6365 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 6366 Expr::NullPointerConstantKind NullKind, 6367 bool IsEqual, SourceRange Range) { 6368 if (!E) 6369 return; 6370 6371 // Don't warn inside macros. 6372 if (E->getExprLoc().isMacroID()) { 6373 const SourceManager &SM = getSourceManager(); 6374 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 6375 IsInAnyMacroBody(SM, Range.getBegin())) 6376 return; 6377 } 6378 E = E->IgnoreImpCasts(); 6379 6380 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 6381 6382 if (isa<CXXThisExpr>(E)) { 6383 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 6384 : diag::warn_this_bool_conversion; 6385 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 6386 return; 6387 } 6388 6389 bool IsAddressOf = false; 6390 6391 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6392 if (UO->getOpcode() != UO_AddrOf) 6393 return; 6394 IsAddressOf = true; 6395 E = UO->getSubExpr(); 6396 } 6397 6398 if (IsAddressOf) { 6399 unsigned DiagID = IsCompare 6400 ? diag::warn_address_of_reference_null_compare 6401 : diag::warn_address_of_reference_bool_conversion; 6402 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 6403 << IsEqual; 6404 if (CheckForReference(*this, E, PD)) { 6405 return; 6406 } 6407 } 6408 6409 // Expect to find a single Decl. Skip anything more complicated. 6410 ValueDecl *D = nullptr; 6411 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 6412 D = R->getDecl(); 6413 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6414 D = M->getMemberDecl(); 6415 } 6416 6417 // Weak Decls can be null. 6418 if (!D || D->isWeak()) 6419 return; 6420 6421 QualType T = D->getType(); 6422 const bool IsArray = T->isArrayType(); 6423 const bool IsFunction = T->isFunctionType(); 6424 6425 // Address of function is used to silence the function warning. 6426 if (IsAddressOf && IsFunction) { 6427 return; 6428 } 6429 6430 // Found nothing. 6431 if (!IsAddressOf && !IsFunction && !IsArray) 6432 return; 6433 6434 // Pretty print the expression for the diagnostic. 6435 std::string Str; 6436 llvm::raw_string_ostream S(Str); 6437 E->printPretty(S, nullptr, getPrintingPolicy()); 6438 6439 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 6440 : diag::warn_impcast_pointer_to_bool; 6441 unsigned DiagType; 6442 if (IsAddressOf) 6443 DiagType = AddressOf; 6444 else if (IsFunction) 6445 DiagType = FunctionPointer; 6446 else if (IsArray) 6447 DiagType = ArrayPointer; 6448 else 6449 llvm_unreachable("Could not determine diagnostic."); 6450 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 6451 << Range << IsEqual; 6452 6453 if (!IsFunction) 6454 return; 6455 6456 // Suggest '&' to silence the function warning. 6457 Diag(E->getExprLoc(), diag::note_function_warning_silence) 6458 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 6459 6460 // Check to see if '()' fixit should be emitted. 6461 QualType ReturnType; 6462 UnresolvedSet<4> NonTemplateOverloads; 6463 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 6464 if (ReturnType.isNull()) 6465 return; 6466 6467 if (IsCompare) { 6468 // There are two cases here. If there is null constant, the only suggest 6469 // for a pointer return type. If the null is 0, then suggest if the return 6470 // type is a pointer or an integer type. 6471 if (!ReturnType->isPointerType()) { 6472 if (NullKind == Expr::NPCK_ZeroExpression || 6473 NullKind == Expr::NPCK_ZeroLiteral) { 6474 if (!ReturnType->isIntegerType()) 6475 return; 6476 } else { 6477 return; 6478 } 6479 } 6480 } else { // !IsCompare 6481 // For function to bool, only suggest if the function pointer has bool 6482 // return type. 6483 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 6484 return; 6485 } 6486 Diag(E->getExprLoc(), diag::note_function_to_function_call) 6487 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 6488 } 6489 6490 6491 /// Diagnoses "dangerous" implicit conversions within the given 6492 /// expression (which is a full expression). Implements -Wconversion 6493 /// and -Wsign-compare. 6494 /// 6495 /// \param CC the "context" location of the implicit conversion, i.e. 6496 /// the most location of the syntactic entity requiring the implicit 6497 /// conversion 6498 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 6499 // Don't diagnose in unevaluated contexts. 6500 if (isUnevaluatedContext()) 6501 return; 6502 6503 // Don't diagnose for value- or type-dependent expressions. 6504 if (E->isTypeDependent() || E->isValueDependent()) 6505 return; 6506 6507 // Check for array bounds violations in cases where the check isn't triggered 6508 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 6509 // ArraySubscriptExpr is on the RHS of a variable initialization. 6510 CheckArrayAccess(E); 6511 6512 // This is not the right CC for (e.g.) a variable initialization. 6513 AnalyzeImplicitConversions(*this, E, CC); 6514 } 6515 6516 /// Diagnose when expression is an integer constant expression and its evaluation 6517 /// results in integer overflow 6518 void Sema::CheckForIntOverflow (Expr *E) { 6519 if (isa<BinaryOperator>(E->IgnoreParens())) 6520 E->EvaluateForOverflow(Context); 6521 } 6522 6523 namespace { 6524 /// \brief Visitor for expressions which looks for unsequenced operations on the 6525 /// same object. 6526 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 6527 typedef EvaluatedExprVisitor<SequenceChecker> Base; 6528 6529 /// \brief A tree of sequenced regions within an expression. Two regions are 6530 /// unsequenced if one is an ancestor or a descendent of the other. When we 6531 /// finish processing an expression with sequencing, such as a comma 6532 /// expression, we fold its tree nodes into its parent, since they are 6533 /// unsequenced with respect to nodes we will visit later. 6534 class SequenceTree { 6535 struct Value { 6536 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 6537 unsigned Parent : 31; 6538 bool Merged : 1; 6539 }; 6540 SmallVector<Value, 8> Values; 6541 6542 public: 6543 /// \brief A region within an expression which may be sequenced with respect 6544 /// to some other region. 6545 class Seq { 6546 explicit Seq(unsigned N) : Index(N) {} 6547 unsigned Index; 6548 friend class SequenceTree; 6549 public: 6550 Seq() : Index(0) {} 6551 }; 6552 6553 SequenceTree() { Values.push_back(Value(0)); } 6554 Seq root() const { return Seq(0); } 6555 6556 /// \brief Create a new sequence of operations, which is an unsequenced 6557 /// subset of \p Parent. This sequence of operations is sequenced with 6558 /// respect to other children of \p Parent. 6559 Seq allocate(Seq Parent) { 6560 Values.push_back(Value(Parent.Index)); 6561 return Seq(Values.size() - 1); 6562 } 6563 6564 /// \brief Merge a sequence of operations into its parent. 6565 void merge(Seq S) { 6566 Values[S.Index].Merged = true; 6567 } 6568 6569 /// \brief Determine whether two operations are unsequenced. This operation 6570 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 6571 /// should have been merged into its parent as appropriate. 6572 bool isUnsequenced(Seq Cur, Seq Old) { 6573 unsigned C = representative(Cur.Index); 6574 unsigned Target = representative(Old.Index); 6575 while (C >= Target) { 6576 if (C == Target) 6577 return true; 6578 C = Values[C].Parent; 6579 } 6580 return false; 6581 } 6582 6583 private: 6584 /// \brief Pick a representative for a sequence. 6585 unsigned representative(unsigned K) { 6586 if (Values[K].Merged) 6587 // Perform path compression as we go. 6588 return Values[K].Parent = representative(Values[K].Parent); 6589 return K; 6590 } 6591 }; 6592 6593 /// An object for which we can track unsequenced uses. 6594 typedef NamedDecl *Object; 6595 6596 /// Different flavors of object usage which we track. We only track the 6597 /// least-sequenced usage of each kind. 6598 enum UsageKind { 6599 /// A read of an object. Multiple unsequenced reads are OK. 6600 UK_Use, 6601 /// A modification of an object which is sequenced before the value 6602 /// computation of the expression, such as ++n in C++. 6603 UK_ModAsValue, 6604 /// A modification of an object which is not sequenced before the value 6605 /// computation of the expression, such as n++. 6606 UK_ModAsSideEffect, 6607 6608 UK_Count = UK_ModAsSideEffect + 1 6609 }; 6610 6611 struct Usage { 6612 Usage() : Use(nullptr), Seq() {} 6613 Expr *Use; 6614 SequenceTree::Seq Seq; 6615 }; 6616 6617 struct UsageInfo { 6618 UsageInfo() : Diagnosed(false) {} 6619 Usage Uses[UK_Count]; 6620 /// Have we issued a diagnostic for this variable already? 6621 bool Diagnosed; 6622 }; 6623 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 6624 6625 Sema &SemaRef; 6626 /// Sequenced regions within the expression. 6627 SequenceTree Tree; 6628 /// Declaration modifications and references which we have seen. 6629 UsageInfoMap UsageMap; 6630 /// The region we are currently within. 6631 SequenceTree::Seq Region; 6632 /// Filled in with declarations which were modified as a side-effect 6633 /// (that is, post-increment operations). 6634 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 6635 /// Expressions to check later. We defer checking these to reduce 6636 /// stack usage. 6637 SmallVectorImpl<Expr *> &WorkList; 6638 6639 /// RAII object wrapping the visitation of a sequenced subexpression of an 6640 /// expression. At the end of this process, the side-effects of the evaluation 6641 /// become sequenced with respect to the value computation of the result, so 6642 /// we downgrade any UK_ModAsSideEffect within the evaluation to 6643 /// UK_ModAsValue. 6644 struct SequencedSubexpression { 6645 SequencedSubexpression(SequenceChecker &Self) 6646 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 6647 Self.ModAsSideEffect = &ModAsSideEffect; 6648 } 6649 ~SequencedSubexpression() { 6650 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) { 6651 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first]; 6652 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second; 6653 Self.addUsage(U, ModAsSideEffect[I].first, 6654 ModAsSideEffect[I].second.Use, UK_ModAsValue); 6655 } 6656 Self.ModAsSideEffect = OldModAsSideEffect; 6657 } 6658 6659 SequenceChecker &Self; 6660 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 6661 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 6662 }; 6663 6664 /// RAII object wrapping the visitation of a subexpression which we might 6665 /// choose to evaluate as a constant. If any subexpression is evaluated and 6666 /// found to be non-constant, this allows us to suppress the evaluation of 6667 /// the outer expression. 6668 class EvaluationTracker { 6669 public: 6670 EvaluationTracker(SequenceChecker &Self) 6671 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 6672 Self.EvalTracker = this; 6673 } 6674 ~EvaluationTracker() { 6675 Self.EvalTracker = Prev; 6676 if (Prev) 6677 Prev->EvalOK &= EvalOK; 6678 } 6679 6680 bool evaluate(const Expr *E, bool &Result) { 6681 if (!EvalOK || E->isValueDependent()) 6682 return false; 6683 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 6684 return EvalOK; 6685 } 6686 6687 private: 6688 SequenceChecker &Self; 6689 EvaluationTracker *Prev; 6690 bool EvalOK; 6691 } *EvalTracker; 6692 6693 /// \brief Find the object which is produced by the specified expression, 6694 /// if any. 6695 Object getObject(Expr *E, bool Mod) const { 6696 E = E->IgnoreParenCasts(); 6697 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6698 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 6699 return getObject(UO->getSubExpr(), Mod); 6700 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6701 if (BO->getOpcode() == BO_Comma) 6702 return getObject(BO->getRHS(), Mod); 6703 if (Mod && BO->isAssignmentOp()) 6704 return getObject(BO->getLHS(), Mod); 6705 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 6706 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 6707 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 6708 return ME->getMemberDecl(); 6709 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6710 // FIXME: If this is a reference, map through to its value. 6711 return DRE->getDecl(); 6712 return nullptr; 6713 } 6714 6715 /// \brief Note that an object was modified or used by an expression. 6716 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 6717 Usage &U = UI.Uses[UK]; 6718 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 6719 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 6720 ModAsSideEffect->push_back(std::make_pair(O, U)); 6721 U.Use = Ref; 6722 U.Seq = Region; 6723 } 6724 } 6725 /// \brief Check whether a modification or use conflicts with a prior usage. 6726 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 6727 bool IsModMod) { 6728 if (UI.Diagnosed) 6729 return; 6730 6731 const Usage &U = UI.Uses[OtherKind]; 6732 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 6733 return; 6734 6735 Expr *Mod = U.Use; 6736 Expr *ModOrUse = Ref; 6737 if (OtherKind == UK_Use) 6738 std::swap(Mod, ModOrUse); 6739 6740 SemaRef.Diag(Mod->getExprLoc(), 6741 IsModMod ? diag::warn_unsequenced_mod_mod 6742 : diag::warn_unsequenced_mod_use) 6743 << O << SourceRange(ModOrUse->getExprLoc()); 6744 UI.Diagnosed = true; 6745 } 6746 6747 void notePreUse(Object O, Expr *Use) { 6748 UsageInfo &U = UsageMap[O]; 6749 // Uses conflict with other modifications. 6750 checkUsage(O, U, Use, UK_ModAsValue, false); 6751 } 6752 void notePostUse(Object O, Expr *Use) { 6753 UsageInfo &U = UsageMap[O]; 6754 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 6755 addUsage(U, O, Use, UK_Use); 6756 } 6757 6758 void notePreMod(Object O, Expr *Mod) { 6759 UsageInfo &U = UsageMap[O]; 6760 // Modifications conflict with other modifications and with uses. 6761 checkUsage(O, U, Mod, UK_ModAsValue, true); 6762 checkUsage(O, U, Mod, UK_Use, false); 6763 } 6764 void notePostMod(Object O, Expr *Use, UsageKind UK) { 6765 UsageInfo &U = UsageMap[O]; 6766 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 6767 addUsage(U, O, Use, UK); 6768 } 6769 6770 public: 6771 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 6772 : Base(S.Context), SemaRef(S), Region(Tree.root()), 6773 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 6774 Visit(E); 6775 } 6776 6777 void VisitStmt(Stmt *S) { 6778 // Skip all statements which aren't expressions for now. 6779 } 6780 6781 void VisitExpr(Expr *E) { 6782 // By default, just recurse to evaluated subexpressions. 6783 Base::VisitStmt(E); 6784 } 6785 6786 void VisitCastExpr(CastExpr *E) { 6787 Object O = Object(); 6788 if (E->getCastKind() == CK_LValueToRValue) 6789 O = getObject(E->getSubExpr(), false); 6790 6791 if (O) 6792 notePreUse(O, E); 6793 VisitExpr(E); 6794 if (O) 6795 notePostUse(O, E); 6796 } 6797 6798 void VisitBinComma(BinaryOperator *BO) { 6799 // C++11 [expr.comma]p1: 6800 // Every value computation and side effect associated with the left 6801 // expression is sequenced before every value computation and side 6802 // effect associated with the right expression. 6803 SequenceTree::Seq LHS = Tree.allocate(Region); 6804 SequenceTree::Seq RHS = Tree.allocate(Region); 6805 SequenceTree::Seq OldRegion = Region; 6806 6807 { 6808 SequencedSubexpression SeqLHS(*this); 6809 Region = LHS; 6810 Visit(BO->getLHS()); 6811 } 6812 6813 Region = RHS; 6814 Visit(BO->getRHS()); 6815 6816 Region = OldRegion; 6817 6818 // Forget that LHS and RHS are sequenced. They are both unsequenced 6819 // with respect to other stuff. 6820 Tree.merge(LHS); 6821 Tree.merge(RHS); 6822 } 6823 6824 void VisitBinAssign(BinaryOperator *BO) { 6825 // The modification is sequenced after the value computation of the LHS 6826 // and RHS, so check it before inspecting the operands and update the 6827 // map afterwards. 6828 Object O = getObject(BO->getLHS(), true); 6829 if (!O) 6830 return VisitExpr(BO); 6831 6832 notePreMod(O, BO); 6833 6834 // C++11 [expr.ass]p7: 6835 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 6836 // only once. 6837 // 6838 // Therefore, for a compound assignment operator, O is considered used 6839 // everywhere except within the evaluation of E1 itself. 6840 if (isa<CompoundAssignOperator>(BO)) 6841 notePreUse(O, BO); 6842 6843 Visit(BO->getLHS()); 6844 6845 if (isa<CompoundAssignOperator>(BO)) 6846 notePostUse(O, BO); 6847 6848 Visit(BO->getRHS()); 6849 6850 // C++11 [expr.ass]p1: 6851 // the assignment is sequenced [...] before the value computation of the 6852 // assignment expression. 6853 // C11 6.5.16/3 has no such rule. 6854 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 6855 : UK_ModAsSideEffect); 6856 } 6857 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 6858 VisitBinAssign(CAO); 6859 } 6860 6861 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 6862 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 6863 void VisitUnaryPreIncDec(UnaryOperator *UO) { 6864 Object O = getObject(UO->getSubExpr(), true); 6865 if (!O) 6866 return VisitExpr(UO); 6867 6868 notePreMod(O, UO); 6869 Visit(UO->getSubExpr()); 6870 // C++11 [expr.pre.incr]p1: 6871 // the expression ++x is equivalent to x+=1 6872 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 6873 : UK_ModAsSideEffect); 6874 } 6875 6876 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 6877 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 6878 void VisitUnaryPostIncDec(UnaryOperator *UO) { 6879 Object O = getObject(UO->getSubExpr(), true); 6880 if (!O) 6881 return VisitExpr(UO); 6882 6883 notePreMod(O, UO); 6884 Visit(UO->getSubExpr()); 6885 notePostMod(O, UO, UK_ModAsSideEffect); 6886 } 6887 6888 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 6889 void VisitBinLOr(BinaryOperator *BO) { 6890 // The side-effects of the LHS of an '&&' are sequenced before the 6891 // value computation of the RHS, and hence before the value computation 6892 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 6893 // as if they were unconditionally sequenced. 6894 EvaluationTracker Eval(*this); 6895 { 6896 SequencedSubexpression Sequenced(*this); 6897 Visit(BO->getLHS()); 6898 } 6899 6900 bool Result; 6901 if (Eval.evaluate(BO->getLHS(), Result)) { 6902 if (!Result) 6903 Visit(BO->getRHS()); 6904 } else { 6905 // Check for unsequenced operations in the RHS, treating it as an 6906 // entirely separate evaluation. 6907 // 6908 // FIXME: If there are operations in the RHS which are unsequenced 6909 // with respect to operations outside the RHS, and those operations 6910 // are unconditionally evaluated, diagnose them. 6911 WorkList.push_back(BO->getRHS()); 6912 } 6913 } 6914 void VisitBinLAnd(BinaryOperator *BO) { 6915 EvaluationTracker Eval(*this); 6916 { 6917 SequencedSubexpression Sequenced(*this); 6918 Visit(BO->getLHS()); 6919 } 6920 6921 bool Result; 6922 if (Eval.evaluate(BO->getLHS(), Result)) { 6923 if (Result) 6924 Visit(BO->getRHS()); 6925 } else { 6926 WorkList.push_back(BO->getRHS()); 6927 } 6928 } 6929 6930 // Only visit the condition, unless we can be sure which subexpression will 6931 // be chosen. 6932 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 6933 EvaluationTracker Eval(*this); 6934 { 6935 SequencedSubexpression Sequenced(*this); 6936 Visit(CO->getCond()); 6937 } 6938 6939 bool Result; 6940 if (Eval.evaluate(CO->getCond(), Result)) 6941 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 6942 else { 6943 WorkList.push_back(CO->getTrueExpr()); 6944 WorkList.push_back(CO->getFalseExpr()); 6945 } 6946 } 6947 6948 void VisitCallExpr(CallExpr *CE) { 6949 // C++11 [intro.execution]p15: 6950 // When calling a function [...], every value computation and side effect 6951 // associated with any argument expression, or with the postfix expression 6952 // designating the called function, is sequenced before execution of every 6953 // expression or statement in the body of the function [and thus before 6954 // the value computation of its result]. 6955 SequencedSubexpression Sequenced(*this); 6956 Base::VisitCallExpr(CE); 6957 6958 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 6959 } 6960 6961 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 6962 // This is a call, so all subexpressions are sequenced before the result. 6963 SequencedSubexpression Sequenced(*this); 6964 6965 if (!CCE->isListInitialization()) 6966 return VisitExpr(CCE); 6967 6968 // In C++11, list initializations are sequenced. 6969 SmallVector<SequenceTree::Seq, 32> Elts; 6970 SequenceTree::Seq Parent = Region; 6971 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 6972 E = CCE->arg_end(); 6973 I != E; ++I) { 6974 Region = Tree.allocate(Parent); 6975 Elts.push_back(Region); 6976 Visit(*I); 6977 } 6978 6979 // Forget that the initializers are sequenced. 6980 Region = Parent; 6981 for (unsigned I = 0; I < Elts.size(); ++I) 6982 Tree.merge(Elts[I]); 6983 } 6984 6985 void VisitInitListExpr(InitListExpr *ILE) { 6986 if (!SemaRef.getLangOpts().CPlusPlus11) 6987 return VisitExpr(ILE); 6988 6989 // In C++11, list initializations are sequenced. 6990 SmallVector<SequenceTree::Seq, 32> Elts; 6991 SequenceTree::Seq Parent = Region; 6992 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 6993 Expr *E = ILE->getInit(I); 6994 if (!E) continue; 6995 Region = Tree.allocate(Parent); 6996 Elts.push_back(Region); 6997 Visit(E); 6998 } 6999 7000 // Forget that the initializers are sequenced. 7001 Region = Parent; 7002 for (unsigned I = 0; I < Elts.size(); ++I) 7003 Tree.merge(Elts[I]); 7004 } 7005 }; 7006 } 7007 7008 void Sema::CheckUnsequencedOperations(Expr *E) { 7009 SmallVector<Expr *, 8> WorkList; 7010 WorkList.push_back(E); 7011 while (!WorkList.empty()) { 7012 Expr *Item = WorkList.pop_back_val(); 7013 SequenceChecker(*this, Item, WorkList); 7014 } 7015 } 7016 7017 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 7018 bool IsConstexpr) { 7019 CheckImplicitConversions(E, CheckLoc); 7020 CheckUnsequencedOperations(E); 7021 if (!IsConstexpr && !E->isValueDependent()) 7022 CheckForIntOverflow(E); 7023 } 7024 7025 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 7026 FieldDecl *BitField, 7027 Expr *Init) { 7028 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 7029 } 7030 7031 /// CheckParmsForFunctionDef - Check that the parameters of the given 7032 /// function are appropriate for the definition of a function. This 7033 /// takes care of any checks that cannot be performed on the 7034 /// declaration itself, e.g., that the types of each of the function 7035 /// parameters are complete. 7036 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 7037 ParmVarDecl *const *PEnd, 7038 bool CheckParameterNames) { 7039 bool HasInvalidParm = false; 7040 for (; P != PEnd; ++P) { 7041 ParmVarDecl *Param = *P; 7042 7043 // C99 6.7.5.3p4: the parameters in a parameter type list in a 7044 // function declarator that is part of a function definition of 7045 // that function shall not have incomplete type. 7046 // 7047 // This is also C++ [dcl.fct]p6. 7048 if (!Param->isInvalidDecl() && 7049 RequireCompleteType(Param->getLocation(), Param->getType(), 7050 diag::err_typecheck_decl_incomplete_type)) { 7051 Param->setInvalidDecl(); 7052 HasInvalidParm = true; 7053 } 7054 7055 // C99 6.9.1p5: If the declarator includes a parameter type list, the 7056 // declaration of each parameter shall include an identifier. 7057 if (CheckParameterNames && 7058 Param->getIdentifier() == nullptr && 7059 !Param->isImplicit() && 7060 !getLangOpts().CPlusPlus) 7061 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 7062 7063 // C99 6.7.5.3p12: 7064 // If the function declarator is not part of a definition of that 7065 // function, parameters may have incomplete type and may use the [*] 7066 // notation in their sequences of declarator specifiers to specify 7067 // variable length array types. 7068 QualType PType = Param->getOriginalType(); 7069 while (const ArrayType *AT = Context.getAsArrayType(PType)) { 7070 if (AT->getSizeModifier() == ArrayType::Star) { 7071 // FIXME: This diagnostic should point the '[*]' if source-location 7072 // information is added for it. 7073 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 7074 break; 7075 } 7076 PType= AT->getElementType(); 7077 } 7078 7079 // MSVC destroys objects passed by value in the callee. Therefore a 7080 // function definition which takes such a parameter must be able to call the 7081 // object's destructor. However, we don't perform any direct access check 7082 // on the dtor. 7083 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 7084 .getCXXABI() 7085 .areArgsDestroyedLeftToRightInCallee()) { 7086 if (!Param->isInvalidDecl()) { 7087 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 7088 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 7089 if (!ClassDecl->isInvalidDecl() && 7090 !ClassDecl->hasIrrelevantDestructor() && 7091 !ClassDecl->isDependentContext()) { 7092 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 7093 MarkFunctionReferenced(Param->getLocation(), Destructor); 7094 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 7095 } 7096 } 7097 } 7098 } 7099 } 7100 7101 return HasInvalidParm; 7102 } 7103 7104 /// CheckCastAlign - Implements -Wcast-align, which warns when a 7105 /// pointer cast increases the alignment requirements. 7106 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 7107 // This is actually a lot of work to potentially be doing on every 7108 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 7109 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 7110 return; 7111 7112 // Ignore dependent types. 7113 if (T->isDependentType() || Op->getType()->isDependentType()) 7114 return; 7115 7116 // Require that the destination be a pointer type. 7117 const PointerType *DestPtr = T->getAs<PointerType>(); 7118 if (!DestPtr) return; 7119 7120 // If the destination has alignment 1, we're done. 7121 QualType DestPointee = DestPtr->getPointeeType(); 7122 if (DestPointee->isIncompleteType()) return; 7123 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 7124 if (DestAlign.isOne()) return; 7125 7126 // Require that the source be a pointer type. 7127 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 7128 if (!SrcPtr) return; 7129 QualType SrcPointee = SrcPtr->getPointeeType(); 7130 7131 // Whitelist casts from cv void*. We already implicitly 7132 // whitelisted casts to cv void*, since they have alignment 1. 7133 // Also whitelist casts involving incomplete types, which implicitly 7134 // includes 'void'. 7135 if (SrcPointee->isIncompleteType()) return; 7136 7137 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 7138 if (SrcAlign >= DestAlign) return; 7139 7140 Diag(TRange.getBegin(), diag::warn_cast_align) 7141 << Op->getType() << T 7142 << static_cast<unsigned>(SrcAlign.getQuantity()) 7143 << static_cast<unsigned>(DestAlign.getQuantity()) 7144 << TRange << Op->getSourceRange(); 7145 } 7146 7147 static const Type* getElementType(const Expr *BaseExpr) { 7148 const Type* EltType = BaseExpr->getType().getTypePtr(); 7149 if (EltType->isAnyPointerType()) 7150 return EltType->getPointeeType().getTypePtr(); 7151 else if (EltType->isArrayType()) 7152 return EltType->getBaseElementTypeUnsafe(); 7153 return EltType; 7154 } 7155 7156 /// \brief Check whether this array fits the idiom of a size-one tail padded 7157 /// array member of a struct. 7158 /// 7159 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 7160 /// commonly used to emulate flexible arrays in C89 code. 7161 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 7162 const NamedDecl *ND) { 7163 if (Size != 1 || !ND) return false; 7164 7165 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 7166 if (!FD) return false; 7167 7168 // Don't consider sizes resulting from macro expansions or template argument 7169 // substitution to form C89 tail-padded arrays. 7170 7171 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 7172 while (TInfo) { 7173 TypeLoc TL = TInfo->getTypeLoc(); 7174 // Look through typedefs. 7175 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 7176 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 7177 TInfo = TDL->getTypeSourceInfo(); 7178 continue; 7179 } 7180 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 7181 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 7182 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 7183 return false; 7184 } 7185 break; 7186 } 7187 7188 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 7189 if (!RD) return false; 7190 if (RD->isUnion()) return false; 7191 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 7192 if (!CRD->isStandardLayout()) return false; 7193 } 7194 7195 // See if this is the last field decl in the record. 7196 const Decl *D = FD; 7197 while ((D = D->getNextDeclInContext())) 7198 if (isa<FieldDecl>(D)) 7199 return false; 7200 return true; 7201 } 7202 7203 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7204 const ArraySubscriptExpr *ASE, 7205 bool AllowOnePastEnd, bool IndexNegated) { 7206 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 7207 if (IndexExpr->isValueDependent()) 7208 return; 7209 7210 const Type *EffectiveType = getElementType(BaseExpr); 7211 BaseExpr = BaseExpr->IgnoreParenCasts(); 7212 const ConstantArrayType *ArrayTy = 7213 Context.getAsConstantArrayType(BaseExpr->getType()); 7214 if (!ArrayTy) 7215 return; 7216 7217 llvm::APSInt index; 7218 if (!IndexExpr->EvaluateAsInt(index, Context)) 7219 return; 7220 if (IndexNegated) 7221 index = -index; 7222 7223 const NamedDecl *ND = nullptr; 7224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7225 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7226 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7227 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7228 7229 if (index.isUnsigned() || !index.isNegative()) { 7230 llvm::APInt size = ArrayTy->getSize(); 7231 if (!size.isStrictlyPositive()) 7232 return; 7233 7234 const Type* BaseType = getElementType(BaseExpr); 7235 if (BaseType != EffectiveType) { 7236 // Make sure we're comparing apples to apples when comparing index to size 7237 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 7238 uint64_t array_typesize = Context.getTypeSize(BaseType); 7239 // Handle ptrarith_typesize being zero, such as when casting to void* 7240 if (!ptrarith_typesize) ptrarith_typesize = 1; 7241 if (ptrarith_typesize != array_typesize) { 7242 // There's a cast to a different size type involved 7243 uint64_t ratio = array_typesize / ptrarith_typesize; 7244 // TODO: Be smarter about handling cases where array_typesize is not a 7245 // multiple of ptrarith_typesize 7246 if (ptrarith_typesize * ratio == array_typesize) 7247 size *= llvm::APInt(size.getBitWidth(), ratio); 7248 } 7249 } 7250 7251 if (size.getBitWidth() > index.getBitWidth()) 7252 index = index.zext(size.getBitWidth()); 7253 else if (size.getBitWidth() < index.getBitWidth()) 7254 size = size.zext(index.getBitWidth()); 7255 7256 // For array subscripting the index must be less than size, but for pointer 7257 // arithmetic also allow the index (offset) to be equal to size since 7258 // computing the next address after the end of the array is legal and 7259 // commonly done e.g. in C++ iterators and range-based for loops. 7260 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 7261 return; 7262 7263 // Also don't warn for arrays of size 1 which are members of some 7264 // structure. These are often used to approximate flexible arrays in C89 7265 // code. 7266 if (IsTailPaddedMemberArray(*this, size, ND)) 7267 return; 7268 7269 // Suppress the warning if the subscript expression (as identified by the 7270 // ']' location) and the index expression are both from macro expansions 7271 // within a system header. 7272 if (ASE) { 7273 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 7274 ASE->getRBracketLoc()); 7275 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 7276 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 7277 IndexExpr->getLocStart()); 7278 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 7279 return; 7280 } 7281 } 7282 7283 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 7284 if (ASE) 7285 DiagID = diag::warn_array_index_exceeds_bounds; 7286 7287 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7288 PDiag(DiagID) << index.toString(10, true) 7289 << size.toString(10, true) 7290 << (unsigned)size.getLimitedValue(~0U) 7291 << IndexExpr->getSourceRange()); 7292 } else { 7293 unsigned DiagID = diag::warn_array_index_precedes_bounds; 7294 if (!ASE) { 7295 DiagID = diag::warn_ptr_arith_precedes_bounds; 7296 if (index.isNegative()) index = -index; 7297 } 7298 7299 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7300 PDiag(DiagID) << index.toString(10, true) 7301 << IndexExpr->getSourceRange()); 7302 } 7303 7304 if (!ND) { 7305 // Try harder to find a NamedDecl to point at in the note. 7306 while (const ArraySubscriptExpr *ASE = 7307 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 7308 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 7309 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7310 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7311 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7312 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7313 } 7314 7315 if (ND) 7316 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 7317 PDiag(diag::note_array_index_out_of_bounds) 7318 << ND->getDeclName()); 7319 } 7320 7321 void Sema::CheckArrayAccess(const Expr *expr) { 7322 int AllowOnePastEnd = 0; 7323 while (expr) { 7324 expr = expr->IgnoreParenImpCasts(); 7325 switch (expr->getStmtClass()) { 7326 case Stmt::ArraySubscriptExprClass: { 7327 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 7328 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 7329 AllowOnePastEnd > 0); 7330 return; 7331 } 7332 case Stmt::UnaryOperatorClass: { 7333 // Only unwrap the * and & unary operators 7334 const UnaryOperator *UO = cast<UnaryOperator>(expr); 7335 expr = UO->getSubExpr(); 7336 switch (UO->getOpcode()) { 7337 case UO_AddrOf: 7338 AllowOnePastEnd++; 7339 break; 7340 case UO_Deref: 7341 AllowOnePastEnd--; 7342 break; 7343 default: 7344 return; 7345 } 7346 break; 7347 } 7348 case Stmt::ConditionalOperatorClass: { 7349 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 7350 if (const Expr *lhs = cond->getLHS()) 7351 CheckArrayAccess(lhs); 7352 if (const Expr *rhs = cond->getRHS()) 7353 CheckArrayAccess(rhs); 7354 return; 7355 } 7356 default: 7357 return; 7358 } 7359 } 7360 } 7361 7362 //===--- CHECK: Objective-C retain cycles ----------------------------------// 7363 7364 namespace { 7365 struct RetainCycleOwner { 7366 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 7367 VarDecl *Variable; 7368 SourceRange Range; 7369 SourceLocation Loc; 7370 bool Indirect; 7371 7372 void setLocsFrom(Expr *e) { 7373 Loc = e->getExprLoc(); 7374 Range = e->getSourceRange(); 7375 } 7376 }; 7377 } 7378 7379 /// Consider whether capturing the given variable can possibly lead to 7380 /// a retain cycle. 7381 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 7382 // In ARC, it's captured strongly iff the variable has __strong 7383 // lifetime. In MRR, it's captured strongly if the variable is 7384 // __block and has an appropriate type. 7385 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 7386 return false; 7387 7388 owner.Variable = var; 7389 if (ref) 7390 owner.setLocsFrom(ref); 7391 return true; 7392 } 7393 7394 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 7395 while (true) { 7396 e = e->IgnoreParens(); 7397 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 7398 switch (cast->getCastKind()) { 7399 case CK_BitCast: 7400 case CK_LValueBitCast: 7401 case CK_LValueToRValue: 7402 case CK_ARCReclaimReturnedObject: 7403 e = cast->getSubExpr(); 7404 continue; 7405 7406 default: 7407 return false; 7408 } 7409 } 7410 7411 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 7412 ObjCIvarDecl *ivar = ref->getDecl(); 7413 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 7414 return false; 7415 7416 // Try to find a retain cycle in the base. 7417 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 7418 return false; 7419 7420 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 7421 owner.Indirect = true; 7422 return true; 7423 } 7424 7425 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 7426 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 7427 if (!var) return false; 7428 return considerVariable(var, ref, owner); 7429 } 7430 7431 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 7432 if (member->isArrow()) return false; 7433 7434 // Don't count this as an indirect ownership. 7435 e = member->getBase(); 7436 continue; 7437 } 7438 7439 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 7440 // Only pay attention to pseudo-objects on property references. 7441 ObjCPropertyRefExpr *pre 7442 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 7443 ->IgnoreParens()); 7444 if (!pre) return false; 7445 if (pre->isImplicitProperty()) return false; 7446 ObjCPropertyDecl *property = pre->getExplicitProperty(); 7447 if (!property->isRetaining() && 7448 !(property->getPropertyIvarDecl() && 7449 property->getPropertyIvarDecl()->getType() 7450 .getObjCLifetime() == Qualifiers::OCL_Strong)) 7451 return false; 7452 7453 owner.Indirect = true; 7454 if (pre->isSuperReceiver()) { 7455 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 7456 if (!owner.Variable) 7457 return false; 7458 owner.Loc = pre->getLocation(); 7459 owner.Range = pre->getSourceRange(); 7460 return true; 7461 } 7462 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 7463 ->getSourceExpr()); 7464 continue; 7465 } 7466 7467 // Array ivars? 7468 7469 return false; 7470 } 7471 } 7472 7473 namespace { 7474 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 7475 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 7476 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 7477 Context(Context), Variable(variable), Capturer(nullptr), 7478 VarWillBeReased(false) {} 7479 ASTContext &Context; 7480 VarDecl *Variable; 7481 Expr *Capturer; 7482 bool VarWillBeReased; 7483 7484 void VisitDeclRefExpr(DeclRefExpr *ref) { 7485 if (ref->getDecl() == Variable && !Capturer) 7486 Capturer = ref; 7487 } 7488 7489 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 7490 if (Capturer) return; 7491 Visit(ref->getBase()); 7492 if (Capturer && ref->isFreeIvar()) 7493 Capturer = ref; 7494 } 7495 7496 void VisitBlockExpr(BlockExpr *block) { 7497 // Look inside nested blocks 7498 if (block->getBlockDecl()->capturesVariable(Variable)) 7499 Visit(block->getBlockDecl()->getBody()); 7500 } 7501 7502 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 7503 if (Capturer) return; 7504 if (OVE->getSourceExpr()) 7505 Visit(OVE->getSourceExpr()); 7506 } 7507 void VisitBinaryOperator(BinaryOperator *BinOp) { 7508 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 7509 return; 7510 Expr *LHS = BinOp->getLHS(); 7511 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 7512 if (DRE->getDecl() != Variable) 7513 return; 7514 if (Expr *RHS = BinOp->getRHS()) { 7515 RHS = RHS->IgnoreParenCasts(); 7516 llvm::APSInt Value; 7517 VarWillBeReased = 7518 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 7519 } 7520 } 7521 } 7522 }; 7523 } 7524 7525 /// Check whether the given argument is a block which captures a 7526 /// variable. 7527 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 7528 assert(owner.Variable && owner.Loc.isValid()); 7529 7530 e = e->IgnoreParenCasts(); 7531 7532 // Look through [^{...} copy] and Block_copy(^{...}). 7533 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 7534 Selector Cmd = ME->getSelector(); 7535 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 7536 e = ME->getInstanceReceiver(); 7537 if (!e) 7538 return nullptr; 7539 e = e->IgnoreParenCasts(); 7540 } 7541 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 7542 if (CE->getNumArgs() == 1) { 7543 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 7544 if (Fn) { 7545 const IdentifierInfo *FnI = Fn->getIdentifier(); 7546 if (FnI && FnI->isStr("_Block_copy")) { 7547 e = CE->getArg(0)->IgnoreParenCasts(); 7548 } 7549 } 7550 } 7551 } 7552 7553 BlockExpr *block = dyn_cast<BlockExpr>(e); 7554 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 7555 return nullptr; 7556 7557 FindCaptureVisitor visitor(S.Context, owner.Variable); 7558 visitor.Visit(block->getBlockDecl()->getBody()); 7559 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 7560 } 7561 7562 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 7563 RetainCycleOwner &owner) { 7564 assert(capturer); 7565 assert(owner.Variable && owner.Loc.isValid()); 7566 7567 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 7568 << owner.Variable << capturer->getSourceRange(); 7569 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 7570 << owner.Indirect << owner.Range; 7571 } 7572 7573 /// Check for a keyword selector that starts with the word 'add' or 7574 /// 'set'. 7575 static bool isSetterLikeSelector(Selector sel) { 7576 if (sel.isUnarySelector()) return false; 7577 7578 StringRef str = sel.getNameForSlot(0); 7579 while (!str.empty() && str.front() == '_') str = str.substr(1); 7580 if (str.startswith("set")) 7581 str = str.substr(3); 7582 else if (str.startswith("add")) { 7583 // Specially whitelist 'addOperationWithBlock:'. 7584 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 7585 return false; 7586 str = str.substr(3); 7587 } 7588 else 7589 return false; 7590 7591 if (str.empty()) return true; 7592 return !isLowercase(str.front()); 7593 } 7594 7595 /// Check a message send to see if it's likely to cause a retain cycle. 7596 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 7597 // Only check instance methods whose selector looks like a setter. 7598 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 7599 return; 7600 7601 // Try to find a variable that the receiver is strongly owned by. 7602 RetainCycleOwner owner; 7603 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 7604 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 7605 return; 7606 } else { 7607 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 7608 owner.Variable = getCurMethodDecl()->getSelfDecl(); 7609 owner.Loc = msg->getSuperLoc(); 7610 owner.Range = msg->getSuperLoc(); 7611 } 7612 7613 // Check whether the receiver is captured by any of the arguments. 7614 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 7615 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 7616 return diagnoseRetainCycle(*this, capturer, owner); 7617 } 7618 7619 /// Check a property assign to see if it's likely to cause a retain cycle. 7620 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 7621 RetainCycleOwner owner; 7622 if (!findRetainCycleOwner(*this, receiver, owner)) 7623 return; 7624 7625 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 7626 diagnoseRetainCycle(*this, capturer, owner); 7627 } 7628 7629 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 7630 RetainCycleOwner Owner; 7631 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 7632 return; 7633 7634 // Because we don't have an expression for the variable, we have to set the 7635 // location explicitly here. 7636 Owner.Loc = Var->getLocation(); 7637 Owner.Range = Var->getSourceRange(); 7638 7639 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 7640 diagnoseRetainCycle(*this, Capturer, Owner); 7641 } 7642 7643 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 7644 Expr *RHS, bool isProperty) { 7645 // Check if RHS is an Objective-C object literal, which also can get 7646 // immediately zapped in a weak reference. Note that we explicitly 7647 // allow ObjCStringLiterals, since those are designed to never really die. 7648 RHS = RHS->IgnoreParenImpCasts(); 7649 7650 // This enum needs to match with the 'select' in 7651 // warn_objc_arc_literal_assign (off-by-1). 7652 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 7653 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 7654 return false; 7655 7656 S.Diag(Loc, diag::warn_arc_literal_assign) 7657 << (unsigned) Kind 7658 << (isProperty ? 0 : 1) 7659 << RHS->getSourceRange(); 7660 7661 return true; 7662 } 7663 7664 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 7665 Qualifiers::ObjCLifetime LT, 7666 Expr *RHS, bool isProperty) { 7667 // Strip off any implicit cast added to get to the one ARC-specific. 7668 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 7669 if (cast->getCastKind() == CK_ARCConsumeObject) { 7670 S.Diag(Loc, diag::warn_arc_retained_assign) 7671 << (LT == Qualifiers::OCL_ExplicitNone) 7672 << (isProperty ? 0 : 1) 7673 << RHS->getSourceRange(); 7674 return true; 7675 } 7676 RHS = cast->getSubExpr(); 7677 } 7678 7679 if (LT == Qualifiers::OCL_Weak && 7680 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 7681 return true; 7682 7683 return false; 7684 } 7685 7686 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 7687 QualType LHS, Expr *RHS) { 7688 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 7689 7690 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 7691 return false; 7692 7693 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 7694 return true; 7695 7696 return false; 7697 } 7698 7699 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 7700 Expr *LHS, Expr *RHS) { 7701 QualType LHSType; 7702 // PropertyRef on LHS type need be directly obtained from 7703 // its declaration as it has a PseudoType. 7704 ObjCPropertyRefExpr *PRE 7705 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 7706 if (PRE && !PRE->isImplicitProperty()) { 7707 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 7708 if (PD) 7709 LHSType = PD->getType(); 7710 } 7711 7712 if (LHSType.isNull()) 7713 LHSType = LHS->getType(); 7714 7715 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 7716 7717 if (LT == Qualifiers::OCL_Weak) { 7718 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 7719 getCurFunction()->markSafeWeakUse(LHS); 7720 } 7721 7722 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 7723 return; 7724 7725 // FIXME. Check for other life times. 7726 if (LT != Qualifiers::OCL_None) 7727 return; 7728 7729 if (PRE) { 7730 if (PRE->isImplicitProperty()) 7731 return; 7732 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 7733 if (!PD) 7734 return; 7735 7736 unsigned Attributes = PD->getPropertyAttributes(); 7737 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 7738 // when 'assign' attribute was not explicitly specified 7739 // by user, ignore it and rely on property type itself 7740 // for lifetime info. 7741 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 7742 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 7743 LHSType->isObjCRetainableType()) 7744 return; 7745 7746 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 7747 if (cast->getCastKind() == CK_ARCConsumeObject) { 7748 Diag(Loc, diag::warn_arc_retained_property_assign) 7749 << RHS->getSourceRange(); 7750 return; 7751 } 7752 RHS = cast->getSubExpr(); 7753 } 7754 } 7755 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 7756 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 7757 return; 7758 } 7759 } 7760 } 7761 7762 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 7763 7764 namespace { 7765 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 7766 SourceLocation StmtLoc, 7767 const NullStmt *Body) { 7768 // Do not warn if the body is a macro that expands to nothing, e.g: 7769 // 7770 // #define CALL(x) 7771 // if (condition) 7772 // CALL(0); 7773 // 7774 if (Body->hasLeadingEmptyMacro()) 7775 return false; 7776 7777 // Get line numbers of statement and body. 7778 bool StmtLineInvalid; 7779 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 7780 &StmtLineInvalid); 7781 if (StmtLineInvalid) 7782 return false; 7783 7784 bool BodyLineInvalid; 7785 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 7786 &BodyLineInvalid); 7787 if (BodyLineInvalid) 7788 return false; 7789 7790 // Warn if null statement and body are on the same line. 7791 if (StmtLine != BodyLine) 7792 return false; 7793 7794 return true; 7795 } 7796 } // Unnamed namespace 7797 7798 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 7799 const Stmt *Body, 7800 unsigned DiagID) { 7801 // Since this is a syntactic check, don't emit diagnostic for template 7802 // instantiations, this just adds noise. 7803 if (CurrentInstantiationScope) 7804 return; 7805 7806 // The body should be a null statement. 7807 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 7808 if (!NBody) 7809 return; 7810 7811 // Do the usual checks. 7812 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 7813 return; 7814 7815 Diag(NBody->getSemiLoc(), DiagID); 7816 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 7817 } 7818 7819 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 7820 const Stmt *PossibleBody) { 7821 assert(!CurrentInstantiationScope); // Ensured by caller 7822 7823 SourceLocation StmtLoc; 7824 const Stmt *Body; 7825 unsigned DiagID; 7826 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 7827 StmtLoc = FS->getRParenLoc(); 7828 Body = FS->getBody(); 7829 DiagID = diag::warn_empty_for_body; 7830 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 7831 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 7832 Body = WS->getBody(); 7833 DiagID = diag::warn_empty_while_body; 7834 } else 7835 return; // Neither `for' nor `while'. 7836 7837 // The body should be a null statement. 7838 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 7839 if (!NBody) 7840 return; 7841 7842 // Skip expensive checks if diagnostic is disabled. 7843 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 7844 return; 7845 7846 // Do the usual checks. 7847 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 7848 return; 7849 7850 // `for(...);' and `while(...);' are popular idioms, so in order to keep 7851 // noise level low, emit diagnostics only if for/while is followed by a 7852 // CompoundStmt, e.g.: 7853 // for (int i = 0; i < n; i++); 7854 // { 7855 // a(i); 7856 // } 7857 // or if for/while is followed by a statement with more indentation 7858 // than for/while itself: 7859 // for (int i = 0; i < n; i++); 7860 // a(i); 7861 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 7862 if (!ProbableTypo) { 7863 bool BodyColInvalid; 7864 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 7865 PossibleBody->getLocStart(), 7866 &BodyColInvalid); 7867 if (BodyColInvalid) 7868 return; 7869 7870 bool StmtColInvalid; 7871 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 7872 S->getLocStart(), 7873 &StmtColInvalid); 7874 if (StmtColInvalid) 7875 return; 7876 7877 if (BodyCol > StmtCol) 7878 ProbableTypo = true; 7879 } 7880 7881 if (ProbableTypo) { 7882 Diag(NBody->getSemiLoc(), DiagID); 7883 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 7884 } 7885 } 7886 7887 //===--- Layout compatibility ----------------------------------------------// 7888 7889 namespace { 7890 7891 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 7892 7893 /// \brief Check if two enumeration types are layout-compatible. 7894 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 7895 // C++11 [dcl.enum] p8: 7896 // Two enumeration types are layout-compatible if they have the same 7897 // underlying type. 7898 return ED1->isComplete() && ED2->isComplete() && 7899 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 7900 } 7901 7902 /// \brief Check if two fields are layout-compatible. 7903 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 7904 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 7905 return false; 7906 7907 if (Field1->isBitField() != Field2->isBitField()) 7908 return false; 7909 7910 if (Field1->isBitField()) { 7911 // Make sure that the bit-fields are the same length. 7912 unsigned Bits1 = Field1->getBitWidthValue(C); 7913 unsigned Bits2 = Field2->getBitWidthValue(C); 7914 7915 if (Bits1 != Bits2) 7916 return false; 7917 } 7918 7919 return true; 7920 } 7921 7922 /// \brief Check if two standard-layout structs are layout-compatible. 7923 /// (C++11 [class.mem] p17) 7924 bool isLayoutCompatibleStruct(ASTContext &C, 7925 RecordDecl *RD1, 7926 RecordDecl *RD2) { 7927 // If both records are C++ classes, check that base classes match. 7928 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 7929 // If one of records is a CXXRecordDecl we are in C++ mode, 7930 // thus the other one is a CXXRecordDecl, too. 7931 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 7932 // Check number of base classes. 7933 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 7934 return false; 7935 7936 // Check the base classes. 7937 for (CXXRecordDecl::base_class_const_iterator 7938 Base1 = D1CXX->bases_begin(), 7939 BaseEnd1 = D1CXX->bases_end(), 7940 Base2 = D2CXX->bases_begin(); 7941 Base1 != BaseEnd1; 7942 ++Base1, ++Base2) { 7943 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 7944 return false; 7945 } 7946 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 7947 // If only RD2 is a C++ class, it should have zero base classes. 7948 if (D2CXX->getNumBases() > 0) 7949 return false; 7950 } 7951 7952 // Check the fields. 7953 RecordDecl::field_iterator Field2 = RD2->field_begin(), 7954 Field2End = RD2->field_end(), 7955 Field1 = RD1->field_begin(), 7956 Field1End = RD1->field_end(); 7957 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 7958 if (!isLayoutCompatible(C, *Field1, *Field2)) 7959 return false; 7960 } 7961 if (Field1 != Field1End || Field2 != Field2End) 7962 return false; 7963 7964 return true; 7965 } 7966 7967 /// \brief Check if two standard-layout unions are layout-compatible. 7968 /// (C++11 [class.mem] p18) 7969 bool isLayoutCompatibleUnion(ASTContext &C, 7970 RecordDecl *RD1, 7971 RecordDecl *RD2) { 7972 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 7973 for (auto *Field2 : RD2->fields()) 7974 UnmatchedFields.insert(Field2); 7975 7976 for (auto *Field1 : RD1->fields()) { 7977 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 7978 I = UnmatchedFields.begin(), 7979 E = UnmatchedFields.end(); 7980 7981 for ( ; I != E; ++I) { 7982 if (isLayoutCompatible(C, Field1, *I)) { 7983 bool Result = UnmatchedFields.erase(*I); 7984 (void) Result; 7985 assert(Result); 7986 break; 7987 } 7988 } 7989 if (I == E) 7990 return false; 7991 } 7992 7993 return UnmatchedFields.empty(); 7994 } 7995 7996 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 7997 if (RD1->isUnion() != RD2->isUnion()) 7998 return false; 7999 8000 if (RD1->isUnion()) 8001 return isLayoutCompatibleUnion(C, RD1, RD2); 8002 else 8003 return isLayoutCompatibleStruct(C, RD1, RD2); 8004 } 8005 8006 /// \brief Check if two types are layout-compatible in C++11 sense. 8007 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 8008 if (T1.isNull() || T2.isNull()) 8009 return false; 8010 8011 // C++11 [basic.types] p11: 8012 // If two types T1 and T2 are the same type, then T1 and T2 are 8013 // layout-compatible types. 8014 if (C.hasSameType(T1, T2)) 8015 return true; 8016 8017 T1 = T1.getCanonicalType().getUnqualifiedType(); 8018 T2 = T2.getCanonicalType().getUnqualifiedType(); 8019 8020 const Type::TypeClass TC1 = T1->getTypeClass(); 8021 const Type::TypeClass TC2 = T2->getTypeClass(); 8022 8023 if (TC1 != TC2) 8024 return false; 8025 8026 if (TC1 == Type::Enum) { 8027 return isLayoutCompatible(C, 8028 cast<EnumType>(T1)->getDecl(), 8029 cast<EnumType>(T2)->getDecl()); 8030 } else if (TC1 == Type::Record) { 8031 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 8032 return false; 8033 8034 return isLayoutCompatible(C, 8035 cast<RecordType>(T1)->getDecl(), 8036 cast<RecordType>(T2)->getDecl()); 8037 } 8038 8039 return false; 8040 } 8041 } 8042 8043 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 8044 8045 namespace { 8046 /// \brief Given a type tag expression find the type tag itself. 8047 /// 8048 /// \param TypeExpr Type tag expression, as it appears in user's code. 8049 /// 8050 /// \param VD Declaration of an identifier that appears in a type tag. 8051 /// 8052 /// \param MagicValue Type tag magic value. 8053 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 8054 const ValueDecl **VD, uint64_t *MagicValue) { 8055 while(true) { 8056 if (!TypeExpr) 8057 return false; 8058 8059 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 8060 8061 switch (TypeExpr->getStmtClass()) { 8062 case Stmt::UnaryOperatorClass: { 8063 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 8064 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 8065 TypeExpr = UO->getSubExpr(); 8066 continue; 8067 } 8068 return false; 8069 } 8070 8071 case Stmt::DeclRefExprClass: { 8072 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 8073 *VD = DRE->getDecl(); 8074 return true; 8075 } 8076 8077 case Stmt::IntegerLiteralClass: { 8078 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 8079 llvm::APInt MagicValueAPInt = IL->getValue(); 8080 if (MagicValueAPInt.getActiveBits() <= 64) { 8081 *MagicValue = MagicValueAPInt.getZExtValue(); 8082 return true; 8083 } else 8084 return false; 8085 } 8086 8087 case Stmt::BinaryConditionalOperatorClass: 8088 case Stmt::ConditionalOperatorClass: { 8089 const AbstractConditionalOperator *ACO = 8090 cast<AbstractConditionalOperator>(TypeExpr); 8091 bool Result; 8092 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 8093 if (Result) 8094 TypeExpr = ACO->getTrueExpr(); 8095 else 8096 TypeExpr = ACO->getFalseExpr(); 8097 continue; 8098 } 8099 return false; 8100 } 8101 8102 case Stmt::BinaryOperatorClass: { 8103 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 8104 if (BO->getOpcode() == BO_Comma) { 8105 TypeExpr = BO->getRHS(); 8106 continue; 8107 } 8108 return false; 8109 } 8110 8111 default: 8112 return false; 8113 } 8114 } 8115 } 8116 8117 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 8118 /// 8119 /// \param TypeExpr Expression that specifies a type tag. 8120 /// 8121 /// \param MagicValues Registered magic values. 8122 /// 8123 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 8124 /// kind. 8125 /// 8126 /// \param TypeInfo Information about the corresponding C type. 8127 /// 8128 /// \returns true if the corresponding C type was found. 8129 bool GetMatchingCType( 8130 const IdentifierInfo *ArgumentKind, 8131 const Expr *TypeExpr, const ASTContext &Ctx, 8132 const llvm::DenseMap<Sema::TypeTagMagicValue, 8133 Sema::TypeTagData> *MagicValues, 8134 bool &FoundWrongKind, 8135 Sema::TypeTagData &TypeInfo) { 8136 FoundWrongKind = false; 8137 8138 // Variable declaration that has type_tag_for_datatype attribute. 8139 const ValueDecl *VD = nullptr; 8140 8141 uint64_t MagicValue; 8142 8143 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 8144 return false; 8145 8146 if (VD) { 8147 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 8148 if (I->getArgumentKind() != ArgumentKind) { 8149 FoundWrongKind = true; 8150 return false; 8151 } 8152 TypeInfo.Type = I->getMatchingCType(); 8153 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 8154 TypeInfo.MustBeNull = I->getMustBeNull(); 8155 return true; 8156 } 8157 return false; 8158 } 8159 8160 if (!MagicValues) 8161 return false; 8162 8163 llvm::DenseMap<Sema::TypeTagMagicValue, 8164 Sema::TypeTagData>::const_iterator I = 8165 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 8166 if (I == MagicValues->end()) 8167 return false; 8168 8169 TypeInfo = I->second; 8170 return true; 8171 } 8172 } // unnamed namespace 8173 8174 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 8175 uint64_t MagicValue, QualType Type, 8176 bool LayoutCompatible, 8177 bool MustBeNull) { 8178 if (!TypeTagForDatatypeMagicValues) 8179 TypeTagForDatatypeMagicValues.reset( 8180 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 8181 8182 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 8183 (*TypeTagForDatatypeMagicValues)[Magic] = 8184 TypeTagData(Type, LayoutCompatible, MustBeNull); 8185 } 8186 8187 namespace { 8188 bool IsSameCharType(QualType T1, QualType T2) { 8189 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 8190 if (!BT1) 8191 return false; 8192 8193 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 8194 if (!BT2) 8195 return false; 8196 8197 BuiltinType::Kind T1Kind = BT1->getKind(); 8198 BuiltinType::Kind T2Kind = BT2->getKind(); 8199 8200 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 8201 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 8202 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 8203 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 8204 } 8205 } // unnamed namespace 8206 8207 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 8208 const Expr * const *ExprArgs) { 8209 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 8210 bool IsPointerAttr = Attr->getIsPointer(); 8211 8212 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 8213 bool FoundWrongKind; 8214 TypeTagData TypeInfo; 8215 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 8216 TypeTagForDatatypeMagicValues.get(), 8217 FoundWrongKind, TypeInfo)) { 8218 if (FoundWrongKind) 8219 Diag(TypeTagExpr->getExprLoc(), 8220 diag::warn_type_tag_for_datatype_wrong_kind) 8221 << TypeTagExpr->getSourceRange(); 8222 return; 8223 } 8224 8225 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 8226 if (IsPointerAttr) { 8227 // Skip implicit cast of pointer to `void *' (as a function argument). 8228 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 8229 if (ICE->getType()->isVoidPointerType() && 8230 ICE->getCastKind() == CK_BitCast) 8231 ArgumentExpr = ICE->getSubExpr(); 8232 } 8233 QualType ArgumentType = ArgumentExpr->getType(); 8234 8235 // Passing a `void*' pointer shouldn't trigger a warning. 8236 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 8237 return; 8238 8239 if (TypeInfo.MustBeNull) { 8240 // Type tag with matching void type requires a null pointer. 8241 if (!ArgumentExpr->isNullPointerConstant(Context, 8242 Expr::NPC_ValueDependentIsNotNull)) { 8243 Diag(ArgumentExpr->getExprLoc(), 8244 diag::warn_type_safety_null_pointer_required) 8245 << ArgumentKind->getName() 8246 << ArgumentExpr->getSourceRange() 8247 << TypeTagExpr->getSourceRange(); 8248 } 8249 return; 8250 } 8251 8252 QualType RequiredType = TypeInfo.Type; 8253 if (IsPointerAttr) 8254 RequiredType = Context.getPointerType(RequiredType); 8255 8256 bool mismatch = false; 8257 if (!TypeInfo.LayoutCompatible) { 8258 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 8259 8260 // C++11 [basic.fundamental] p1: 8261 // Plain char, signed char, and unsigned char are three distinct types. 8262 // 8263 // But we treat plain `char' as equivalent to `signed char' or `unsigned 8264 // char' depending on the current char signedness mode. 8265 if (mismatch) 8266 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 8267 RequiredType->getPointeeType())) || 8268 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 8269 mismatch = false; 8270 } else 8271 if (IsPointerAttr) 8272 mismatch = !isLayoutCompatible(Context, 8273 ArgumentType->getPointeeType(), 8274 RequiredType->getPointeeType()); 8275 else 8276 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 8277 8278 if (mismatch) 8279 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 8280 << ArgumentType << ArgumentKind 8281 << TypeInfo.LayoutCompatible << RequiredType 8282 << ArgumentExpr->getSourceRange() 8283 << TypeTagExpr->getSourceRange(); 8284 } 8285 8286