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