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.isValidNonNullAttrType(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 EmitFormatDiagnostic( 3573 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 3574 << S.getLangOpts().CPlusPlus11 3575 << ExprTy 3576 << CallType 3577 << AT.getRepresentativeTypeName(S.Context) 3578 << CSR 3579 << E->getSourceRange(), 3580 E->getLocStart(), /*IsStringLocation*/false, CSR); 3581 checkForCStrMembers(AT, E); 3582 break; 3583 3584 case Sema::VAK_Invalid: 3585 if (ExprTy->isObjCObjectType()) 3586 EmitFormatDiagnostic( 3587 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 3588 << S.getLangOpts().CPlusPlus11 3589 << ExprTy 3590 << CallType 3591 << AT.getRepresentativeTypeName(S.Context) 3592 << CSR 3593 << E->getSourceRange(), 3594 E->getLocStart(), /*IsStringLocation*/false, CSR); 3595 else 3596 // FIXME: If this is an initializer list, suggest removing the braces 3597 // or inserting a cast to the target type. 3598 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 3599 << isa<InitListExpr>(E) << ExprTy << CallType 3600 << AT.getRepresentativeTypeName(S.Context) 3601 << E->getSourceRange(); 3602 break; 3603 } 3604 3605 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 3606 "format string specifier index out of range"); 3607 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 3608 } 3609 3610 return true; 3611 } 3612 3613 //===--- CHECK: Scanf format string checking ------------------------------===// 3614 3615 namespace { 3616 class CheckScanfHandler : public CheckFormatHandler { 3617 public: 3618 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 3619 const Expr *origFormatExpr, unsigned firstDataArg, 3620 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3621 ArrayRef<const Expr *> Args, 3622 unsigned formatIdx, bool inFunctionCall, 3623 Sema::VariadicCallType CallType, 3624 llvm::SmallBitVector &CheckedVarArgs) 3625 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3626 numDataArgs, beg, hasVAListArg, 3627 Args, formatIdx, inFunctionCall, CallType, 3628 CheckedVarArgs) 3629 {} 3630 3631 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 3632 const char *startSpecifier, 3633 unsigned specifierLen) override; 3634 3635 bool HandleInvalidScanfConversionSpecifier( 3636 const analyze_scanf::ScanfSpecifier &FS, 3637 const char *startSpecifier, 3638 unsigned specifierLen) override; 3639 3640 void HandleIncompleteScanList(const char *start, const char *end) override; 3641 }; 3642 } 3643 3644 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 3645 const char *end) { 3646 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 3647 getLocationOfByte(end), /*IsStringLocation*/true, 3648 getSpecifierRange(start, end - start)); 3649 } 3650 3651 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 3652 const analyze_scanf::ScanfSpecifier &FS, 3653 const char *startSpecifier, 3654 unsigned specifierLen) { 3655 3656 const analyze_scanf::ScanfConversionSpecifier &CS = 3657 FS.getConversionSpecifier(); 3658 3659 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3660 getLocationOfByte(CS.getStart()), 3661 startSpecifier, specifierLen, 3662 CS.getStart(), CS.getLength()); 3663 } 3664 3665 bool CheckScanfHandler::HandleScanfSpecifier( 3666 const analyze_scanf::ScanfSpecifier &FS, 3667 const char *startSpecifier, 3668 unsigned specifierLen) { 3669 3670 using namespace analyze_scanf; 3671 using namespace analyze_format_string; 3672 3673 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 3674 3675 // Handle case where '%' and '*' don't consume an argument. These shouldn't 3676 // be used to decide if we are using positional arguments consistently. 3677 if (FS.consumesDataArgument()) { 3678 if (atFirstArg) { 3679 atFirstArg = false; 3680 usesPositionalArgs = FS.usesPositionalArg(); 3681 } 3682 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3683 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3684 startSpecifier, specifierLen); 3685 return false; 3686 } 3687 } 3688 3689 // Check if the field with is non-zero. 3690 const OptionalAmount &Amt = FS.getFieldWidth(); 3691 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 3692 if (Amt.getConstantAmount() == 0) { 3693 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 3694 Amt.getConstantLength()); 3695 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 3696 getLocationOfByte(Amt.getStart()), 3697 /*IsStringLocation*/true, R, 3698 FixItHint::CreateRemoval(R)); 3699 } 3700 } 3701 3702 if (!FS.consumesDataArgument()) { 3703 // FIXME: Technically specifying a precision or field width here 3704 // makes no sense. Worth issuing a warning at some point. 3705 return true; 3706 } 3707 3708 // Consume the argument. 3709 unsigned argIndex = FS.getArgIndex(); 3710 if (argIndex < NumDataArgs) { 3711 // The check to see if the argIndex is valid will come later. 3712 // We set the bit here because we may exit early from this 3713 // function if we encounter some other error. 3714 CoveredArgs.set(argIndex); 3715 } 3716 3717 // Check the length modifier is valid with the given conversion specifier. 3718 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3719 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3720 diag::warn_format_nonsensical_length); 3721 else if (!FS.hasStandardLengthModifier()) 3722 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3723 else if (!FS.hasStandardLengthConversionCombination()) 3724 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3725 diag::warn_format_non_standard_conversion_spec); 3726 3727 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3728 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3729 3730 // The remaining checks depend on the data arguments. 3731 if (HasVAListArg) 3732 return true; 3733 3734 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3735 return false; 3736 3737 // Check that the argument type matches the format specifier. 3738 const Expr *Ex = getDataArg(argIndex); 3739 if (!Ex) 3740 return true; 3741 3742 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 3743 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 3744 ScanfSpecifier fixedFS = FS; 3745 bool success = fixedFS.fixType(Ex->getType(), 3746 Ex->IgnoreImpCasts()->getType(), 3747 S.getLangOpts(), S.Context); 3748 3749 if (success) { 3750 // Get the fix string from the fixed format specifier. 3751 SmallString<128> buf; 3752 llvm::raw_svector_ostream os(buf); 3753 fixedFS.toString(os); 3754 3755 EmitFormatDiagnostic( 3756 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3757 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false 3758 << Ex->getSourceRange(), 3759 Ex->getLocStart(), 3760 /*IsStringLocation*/false, 3761 getSpecifierRange(startSpecifier, specifierLen), 3762 FixItHint::CreateReplacement( 3763 getSpecifierRange(startSpecifier, specifierLen), 3764 os.str())); 3765 } else { 3766 EmitFormatDiagnostic( 3767 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3768 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false 3769 << Ex->getSourceRange(), 3770 Ex->getLocStart(), 3771 /*IsStringLocation*/false, 3772 getSpecifierRange(startSpecifier, specifierLen)); 3773 } 3774 } 3775 3776 return true; 3777 } 3778 3779 void Sema::CheckFormatString(const StringLiteral *FExpr, 3780 const Expr *OrigFormatExpr, 3781 ArrayRef<const Expr *> Args, 3782 bool HasVAListArg, unsigned format_idx, 3783 unsigned firstDataArg, FormatStringType Type, 3784 bool inFunctionCall, VariadicCallType CallType, 3785 llvm::SmallBitVector &CheckedVarArgs) { 3786 3787 // CHECK: is the format string a wide literal? 3788 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 3789 CheckFormatHandler::EmitFormatDiagnostic( 3790 *this, inFunctionCall, Args[format_idx], 3791 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 3792 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3793 return; 3794 } 3795 3796 // Str - The format string. NOTE: this is NOT null-terminated! 3797 StringRef StrRef = FExpr->getString(); 3798 const char *Str = StrRef.data(); 3799 // Account for cases where the string literal is truncated in a declaration. 3800 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 3801 assert(T && "String literal not of constant array type!"); 3802 size_t TypeSize = T->getSize().getZExtValue(); 3803 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 3804 const unsigned numDataArgs = Args.size() - firstDataArg; 3805 3806 // Emit a warning if the string literal is truncated and does not contain an 3807 // embedded null character. 3808 if (TypeSize <= StrRef.size() && 3809 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 3810 CheckFormatHandler::EmitFormatDiagnostic( 3811 *this, inFunctionCall, Args[format_idx], 3812 PDiag(diag::warn_printf_format_string_not_null_terminated), 3813 FExpr->getLocStart(), 3814 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 3815 return; 3816 } 3817 3818 // CHECK: empty format string? 3819 if (StrLen == 0 && numDataArgs > 0) { 3820 CheckFormatHandler::EmitFormatDiagnostic( 3821 *this, inFunctionCall, Args[format_idx], 3822 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 3823 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3824 return; 3825 } 3826 3827 if (Type == FST_Printf || Type == FST_NSString) { 3828 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 3829 numDataArgs, (Type == FST_NSString), 3830 Str, HasVAListArg, Args, format_idx, 3831 inFunctionCall, CallType, CheckedVarArgs); 3832 3833 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 3834 getLangOpts(), 3835 Context.getTargetInfo())) 3836 H.DoneProcessing(); 3837 } else if (Type == FST_Scanf) { 3838 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 3839 Str, HasVAListArg, Args, format_idx, 3840 inFunctionCall, CallType, CheckedVarArgs); 3841 3842 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 3843 getLangOpts(), 3844 Context.getTargetInfo())) 3845 H.DoneProcessing(); 3846 } // TODO: handle other formats 3847 } 3848 3849 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 3850 // Str - The format string. NOTE: this is NOT null-terminated! 3851 StringRef StrRef = FExpr->getString(); 3852 const char *Str = StrRef.data(); 3853 // Account for cases where the string literal is truncated in a declaration. 3854 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 3855 assert(T && "String literal not of constant array type!"); 3856 size_t TypeSize = T->getSize().getZExtValue(); 3857 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 3858 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 3859 getLangOpts(), 3860 Context.getTargetInfo()); 3861 } 3862 3863 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 3864 3865 // Returns the related absolute value function that is larger, of 0 if one 3866 // does not exist. 3867 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 3868 switch (AbsFunction) { 3869 default: 3870 return 0; 3871 3872 case Builtin::BI__builtin_abs: 3873 return Builtin::BI__builtin_labs; 3874 case Builtin::BI__builtin_labs: 3875 return Builtin::BI__builtin_llabs; 3876 case Builtin::BI__builtin_llabs: 3877 return 0; 3878 3879 case Builtin::BI__builtin_fabsf: 3880 return Builtin::BI__builtin_fabs; 3881 case Builtin::BI__builtin_fabs: 3882 return Builtin::BI__builtin_fabsl; 3883 case Builtin::BI__builtin_fabsl: 3884 return 0; 3885 3886 case Builtin::BI__builtin_cabsf: 3887 return Builtin::BI__builtin_cabs; 3888 case Builtin::BI__builtin_cabs: 3889 return Builtin::BI__builtin_cabsl; 3890 case Builtin::BI__builtin_cabsl: 3891 return 0; 3892 3893 case Builtin::BIabs: 3894 return Builtin::BIlabs; 3895 case Builtin::BIlabs: 3896 return Builtin::BIllabs; 3897 case Builtin::BIllabs: 3898 return 0; 3899 3900 case Builtin::BIfabsf: 3901 return Builtin::BIfabs; 3902 case Builtin::BIfabs: 3903 return Builtin::BIfabsl; 3904 case Builtin::BIfabsl: 3905 return 0; 3906 3907 case Builtin::BIcabsf: 3908 return Builtin::BIcabs; 3909 case Builtin::BIcabs: 3910 return Builtin::BIcabsl; 3911 case Builtin::BIcabsl: 3912 return 0; 3913 } 3914 } 3915 3916 // Returns the argument type of the absolute value function. 3917 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 3918 unsigned AbsType) { 3919 if (AbsType == 0) 3920 return QualType(); 3921 3922 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3923 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 3924 if (Error != ASTContext::GE_None) 3925 return QualType(); 3926 3927 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 3928 if (!FT) 3929 return QualType(); 3930 3931 if (FT->getNumParams() != 1) 3932 return QualType(); 3933 3934 return FT->getParamType(0); 3935 } 3936 3937 // Returns the best absolute value function, or zero, based on type and 3938 // current absolute value function. 3939 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 3940 unsigned AbsFunctionKind) { 3941 unsigned BestKind = 0; 3942 uint64_t ArgSize = Context.getTypeSize(ArgType); 3943 for (unsigned Kind = AbsFunctionKind; Kind != 0; 3944 Kind = getLargerAbsoluteValueFunction(Kind)) { 3945 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 3946 if (Context.getTypeSize(ParamType) >= ArgSize) { 3947 if (BestKind == 0) 3948 BestKind = Kind; 3949 else if (Context.hasSameType(ParamType, ArgType)) { 3950 BestKind = Kind; 3951 break; 3952 } 3953 } 3954 } 3955 return BestKind; 3956 } 3957 3958 enum AbsoluteValueKind { 3959 AVK_Integer, 3960 AVK_Floating, 3961 AVK_Complex 3962 }; 3963 3964 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 3965 if (T->isIntegralOrEnumerationType()) 3966 return AVK_Integer; 3967 if (T->isRealFloatingType()) 3968 return AVK_Floating; 3969 if (T->isAnyComplexType()) 3970 return AVK_Complex; 3971 3972 llvm_unreachable("Type not integer, floating, or complex"); 3973 } 3974 3975 // Changes the absolute value function to a different type. Preserves whether 3976 // the function is a builtin. 3977 static unsigned changeAbsFunction(unsigned AbsKind, 3978 AbsoluteValueKind ValueKind) { 3979 switch (ValueKind) { 3980 case AVK_Integer: 3981 switch (AbsKind) { 3982 default: 3983 return 0; 3984 case Builtin::BI__builtin_fabsf: 3985 case Builtin::BI__builtin_fabs: 3986 case Builtin::BI__builtin_fabsl: 3987 case Builtin::BI__builtin_cabsf: 3988 case Builtin::BI__builtin_cabs: 3989 case Builtin::BI__builtin_cabsl: 3990 return Builtin::BI__builtin_abs; 3991 case Builtin::BIfabsf: 3992 case Builtin::BIfabs: 3993 case Builtin::BIfabsl: 3994 case Builtin::BIcabsf: 3995 case Builtin::BIcabs: 3996 case Builtin::BIcabsl: 3997 return Builtin::BIabs; 3998 } 3999 case AVK_Floating: 4000 switch (AbsKind) { 4001 default: 4002 return 0; 4003 case Builtin::BI__builtin_abs: 4004 case Builtin::BI__builtin_labs: 4005 case Builtin::BI__builtin_llabs: 4006 case Builtin::BI__builtin_cabsf: 4007 case Builtin::BI__builtin_cabs: 4008 case Builtin::BI__builtin_cabsl: 4009 return Builtin::BI__builtin_fabsf; 4010 case Builtin::BIabs: 4011 case Builtin::BIlabs: 4012 case Builtin::BIllabs: 4013 case Builtin::BIcabsf: 4014 case Builtin::BIcabs: 4015 case Builtin::BIcabsl: 4016 return Builtin::BIfabsf; 4017 } 4018 case AVK_Complex: 4019 switch (AbsKind) { 4020 default: 4021 return 0; 4022 case Builtin::BI__builtin_abs: 4023 case Builtin::BI__builtin_labs: 4024 case Builtin::BI__builtin_llabs: 4025 case Builtin::BI__builtin_fabsf: 4026 case Builtin::BI__builtin_fabs: 4027 case Builtin::BI__builtin_fabsl: 4028 return Builtin::BI__builtin_cabsf; 4029 case Builtin::BIabs: 4030 case Builtin::BIlabs: 4031 case Builtin::BIllabs: 4032 case Builtin::BIfabsf: 4033 case Builtin::BIfabs: 4034 case Builtin::BIfabsl: 4035 return Builtin::BIcabsf; 4036 } 4037 } 4038 llvm_unreachable("Unable to convert function"); 4039 } 4040 4041 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 4042 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4043 if (!FnInfo) 4044 return 0; 4045 4046 switch (FDecl->getBuiltinID()) { 4047 default: 4048 return 0; 4049 case Builtin::BI__builtin_abs: 4050 case Builtin::BI__builtin_fabs: 4051 case Builtin::BI__builtin_fabsf: 4052 case Builtin::BI__builtin_fabsl: 4053 case Builtin::BI__builtin_labs: 4054 case Builtin::BI__builtin_llabs: 4055 case Builtin::BI__builtin_cabs: 4056 case Builtin::BI__builtin_cabsf: 4057 case Builtin::BI__builtin_cabsl: 4058 case Builtin::BIabs: 4059 case Builtin::BIlabs: 4060 case Builtin::BIllabs: 4061 case Builtin::BIfabs: 4062 case Builtin::BIfabsf: 4063 case Builtin::BIfabsl: 4064 case Builtin::BIcabs: 4065 case Builtin::BIcabsf: 4066 case Builtin::BIcabsl: 4067 return FDecl->getBuiltinID(); 4068 } 4069 llvm_unreachable("Unknown Builtin type"); 4070 } 4071 4072 // If the replacement is valid, emit a note with replacement function. 4073 // Additionally, suggest including the proper header if not already included. 4074 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 4075 unsigned AbsKind, QualType ArgType) { 4076 bool EmitHeaderHint = true; 4077 const char *HeaderName = nullptr; 4078 const char *FunctionName = nullptr; 4079 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 4080 FunctionName = "std::abs"; 4081 if (ArgType->isIntegralOrEnumerationType()) { 4082 HeaderName = "cstdlib"; 4083 } else if (ArgType->isRealFloatingType()) { 4084 HeaderName = "cmath"; 4085 } else { 4086 llvm_unreachable("Invalid Type"); 4087 } 4088 4089 // Lookup all std::abs 4090 if (NamespaceDecl *Std = S.getStdNamespace()) { 4091 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 4092 R.suppressDiagnostics(); 4093 S.LookupQualifiedName(R, Std); 4094 4095 for (const auto *I : R) { 4096 const FunctionDecl *FDecl = nullptr; 4097 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 4098 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 4099 } else { 4100 FDecl = dyn_cast<FunctionDecl>(I); 4101 } 4102 if (!FDecl) 4103 continue; 4104 4105 // Found std::abs(), check that they are the right ones. 4106 if (FDecl->getNumParams() != 1) 4107 continue; 4108 4109 // Check that the parameter type can handle the argument. 4110 QualType ParamType = FDecl->getParamDecl(0)->getType(); 4111 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 4112 S.Context.getTypeSize(ArgType) <= 4113 S.Context.getTypeSize(ParamType)) { 4114 // Found a function, don't need the header hint. 4115 EmitHeaderHint = false; 4116 break; 4117 } 4118 } 4119 } 4120 } else { 4121 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind); 4122 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 4123 4124 if (HeaderName) { 4125 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 4126 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 4127 R.suppressDiagnostics(); 4128 S.LookupName(R, S.getCurScope()); 4129 4130 if (R.isSingleResult()) { 4131 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 4132 if (FD && FD->getBuiltinID() == AbsKind) { 4133 EmitHeaderHint = false; 4134 } else { 4135 return; 4136 } 4137 } else if (!R.empty()) { 4138 return; 4139 } 4140 } 4141 } 4142 4143 S.Diag(Loc, diag::note_replace_abs_function) 4144 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 4145 4146 if (!HeaderName) 4147 return; 4148 4149 if (!EmitHeaderHint) 4150 return; 4151 4152 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 4153 << FunctionName; 4154 } 4155 4156 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 4157 if (!FDecl) 4158 return false; 4159 4160 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 4161 return false; 4162 4163 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 4164 4165 while (ND && ND->isInlineNamespace()) { 4166 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 4167 } 4168 4169 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 4170 return false; 4171 4172 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 4173 return false; 4174 4175 return true; 4176 } 4177 4178 // Warn when using the wrong abs() function. 4179 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 4180 const FunctionDecl *FDecl, 4181 IdentifierInfo *FnInfo) { 4182 if (Call->getNumArgs() != 1) 4183 return; 4184 4185 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 4186 bool IsStdAbs = IsFunctionStdAbs(FDecl); 4187 if (AbsKind == 0 && !IsStdAbs) 4188 return; 4189 4190 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 4191 QualType ParamType = Call->getArg(0)->getType(); 4192 4193 // Unsigned types cannot be negative. Suggest removing the absolute value 4194 // function call. 4195 if (ArgType->isUnsignedIntegerType()) { 4196 const char *FunctionName = 4197 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind); 4198 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 4199 Diag(Call->getExprLoc(), diag::note_remove_abs) 4200 << FunctionName 4201 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 4202 return; 4203 } 4204 4205 // std::abs has overloads which prevent most of the absolute value problems 4206 // from occurring. 4207 if (IsStdAbs) 4208 return; 4209 4210 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 4211 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 4212 4213 // The argument and parameter are the same kind. Check if they are the right 4214 // size. 4215 if (ArgValueKind == ParamValueKind) { 4216 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 4217 return; 4218 4219 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 4220 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 4221 << FDecl << ArgType << ParamType; 4222 4223 if (NewAbsKind == 0) 4224 return; 4225 4226 emitReplacement(*this, Call->getExprLoc(), 4227 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4228 return; 4229 } 4230 4231 // ArgValueKind != ParamValueKind 4232 // The wrong type of absolute value function was used. Attempt to find the 4233 // proper one. 4234 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 4235 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 4236 if (NewAbsKind == 0) 4237 return; 4238 4239 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 4240 << FDecl << ParamValueKind << ArgValueKind; 4241 4242 emitReplacement(*this, Call->getExprLoc(), 4243 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4244 return; 4245 } 4246 4247 //===--- CHECK: Standard memory functions ---------------------------------===// 4248 4249 /// \brief Takes the expression passed to the size_t parameter of functions 4250 /// such as memcmp, strncat, etc and warns if it's a comparison. 4251 /// 4252 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 4253 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 4254 IdentifierInfo *FnName, 4255 SourceLocation FnLoc, 4256 SourceLocation RParenLoc) { 4257 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 4258 if (!Size) 4259 return false; 4260 4261 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 4262 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 4263 return false; 4264 4265 SourceRange SizeRange = Size->getSourceRange(); 4266 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 4267 << SizeRange << FnName; 4268 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 4269 << FnName << FixItHint::CreateInsertion( 4270 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 4271 << FixItHint::CreateRemoval(RParenLoc); 4272 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 4273 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 4274 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 4275 ")"); 4276 4277 return true; 4278 } 4279 4280 /// \brief Determine whether the given type is or contains a dynamic class type 4281 /// (e.g., whether it has a vtable). 4282 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 4283 bool &IsContained) { 4284 // Look through array types while ignoring qualifiers. 4285 const Type *Ty = T->getBaseElementTypeUnsafe(); 4286 IsContained = false; 4287 4288 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 4289 RD = RD ? RD->getDefinition() : nullptr; 4290 if (!RD) 4291 return nullptr; 4292 4293 if (RD->isDynamicClass()) 4294 return RD; 4295 4296 // Check all the fields. If any bases were dynamic, the class is dynamic. 4297 // It's impossible for a class to transitively contain itself by value, so 4298 // infinite recursion is impossible. 4299 for (auto *FD : RD->fields()) { 4300 bool SubContained; 4301 if (const CXXRecordDecl *ContainedRD = 4302 getContainedDynamicClass(FD->getType(), SubContained)) { 4303 IsContained = true; 4304 return ContainedRD; 4305 } 4306 } 4307 4308 return nullptr; 4309 } 4310 4311 /// \brief If E is a sizeof expression, returns its argument expression, 4312 /// otherwise returns NULL. 4313 static const Expr *getSizeOfExprArg(const Expr* E) { 4314 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4315 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4316 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 4317 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 4318 4319 return nullptr; 4320 } 4321 4322 /// \brief If E is a sizeof expression, returns its argument type. 4323 static QualType getSizeOfArgType(const Expr* E) { 4324 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4325 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4326 if (SizeOf->getKind() == clang::UETT_SizeOf) 4327 return SizeOf->getTypeOfArgument(); 4328 4329 return QualType(); 4330 } 4331 4332 /// \brief Check for dangerous or invalid arguments to memset(). 4333 /// 4334 /// This issues warnings on known problematic, dangerous or unspecified 4335 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 4336 /// function calls. 4337 /// 4338 /// \param Call The call expression to diagnose. 4339 void Sema::CheckMemaccessArguments(const CallExpr *Call, 4340 unsigned BId, 4341 IdentifierInfo *FnName) { 4342 assert(BId != 0); 4343 4344 // It is possible to have a non-standard definition of memset. Validate 4345 // we have enough arguments, and if not, abort further checking. 4346 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 4347 if (Call->getNumArgs() < ExpectedNumArgs) 4348 return; 4349 4350 unsigned LastArg = (BId == Builtin::BImemset || 4351 BId == Builtin::BIstrndup ? 1 : 2); 4352 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 4353 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 4354 4355 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 4356 Call->getLocStart(), Call->getRParenLoc())) 4357 return; 4358 4359 // We have special checking when the length is a sizeof expression. 4360 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 4361 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 4362 llvm::FoldingSetNodeID SizeOfArgID; 4363 4364 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 4365 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 4366 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 4367 4368 QualType DestTy = Dest->getType(); 4369 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 4370 QualType PointeeTy = DestPtrTy->getPointeeType(); 4371 4372 // Never warn about void type pointers. This can be used to suppress 4373 // false positives. 4374 if (PointeeTy->isVoidType()) 4375 continue; 4376 4377 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 4378 // actually comparing the expressions for equality. Because computing the 4379 // expression IDs can be expensive, we only do this if the diagnostic is 4380 // enabled. 4381 if (SizeOfArg && 4382 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 4383 SizeOfArg->getExprLoc())) { 4384 // We only compute IDs for expressions if the warning is enabled, and 4385 // cache the sizeof arg's ID. 4386 if (SizeOfArgID == llvm::FoldingSetNodeID()) 4387 SizeOfArg->Profile(SizeOfArgID, Context, true); 4388 llvm::FoldingSetNodeID DestID; 4389 Dest->Profile(DestID, Context, true); 4390 if (DestID == SizeOfArgID) { 4391 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 4392 // over sizeof(src) as well. 4393 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 4394 StringRef ReadableName = FnName->getName(); 4395 4396 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 4397 if (UnaryOp->getOpcode() == UO_AddrOf) 4398 ActionIdx = 1; // If its an address-of operator, just remove it. 4399 if (!PointeeTy->isIncompleteType() && 4400 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 4401 ActionIdx = 2; // If the pointee's size is sizeof(char), 4402 // suggest an explicit length. 4403 4404 // If the function is defined as a builtin macro, do not show macro 4405 // expansion. 4406 SourceLocation SL = SizeOfArg->getExprLoc(); 4407 SourceRange DSR = Dest->getSourceRange(); 4408 SourceRange SSR = SizeOfArg->getSourceRange(); 4409 SourceManager &SM = getSourceManager(); 4410 4411 if (SM.isMacroArgExpansion(SL)) { 4412 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 4413 SL = SM.getSpellingLoc(SL); 4414 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 4415 SM.getSpellingLoc(DSR.getEnd())); 4416 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 4417 SM.getSpellingLoc(SSR.getEnd())); 4418 } 4419 4420 DiagRuntimeBehavior(SL, SizeOfArg, 4421 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 4422 << ReadableName 4423 << PointeeTy 4424 << DestTy 4425 << DSR 4426 << SSR); 4427 DiagRuntimeBehavior(SL, SizeOfArg, 4428 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 4429 << ActionIdx 4430 << SSR); 4431 4432 break; 4433 } 4434 } 4435 4436 // Also check for cases where the sizeof argument is the exact same 4437 // type as the memory argument, and where it points to a user-defined 4438 // record type. 4439 if (SizeOfArgTy != QualType()) { 4440 if (PointeeTy->isRecordType() && 4441 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 4442 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 4443 PDiag(diag::warn_sizeof_pointer_type_memaccess) 4444 << FnName << SizeOfArgTy << ArgIdx 4445 << PointeeTy << Dest->getSourceRange() 4446 << LenExpr->getSourceRange()); 4447 break; 4448 } 4449 } 4450 4451 // Always complain about dynamic classes. 4452 bool IsContained; 4453 if (const CXXRecordDecl *ContainedRD = 4454 getContainedDynamicClass(PointeeTy, IsContained)) { 4455 4456 unsigned OperationType = 0; 4457 // "overwritten" if we're warning about the destination for any call 4458 // but memcmp; otherwise a verb appropriate to the call. 4459 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 4460 if (BId == Builtin::BImemcpy) 4461 OperationType = 1; 4462 else if(BId == Builtin::BImemmove) 4463 OperationType = 2; 4464 else if (BId == Builtin::BImemcmp) 4465 OperationType = 3; 4466 } 4467 4468 DiagRuntimeBehavior( 4469 Dest->getExprLoc(), Dest, 4470 PDiag(diag::warn_dyn_class_memaccess) 4471 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 4472 << FnName << IsContained << ContainedRD << OperationType 4473 << Call->getCallee()->getSourceRange()); 4474 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 4475 BId != Builtin::BImemset) 4476 DiagRuntimeBehavior( 4477 Dest->getExprLoc(), Dest, 4478 PDiag(diag::warn_arc_object_memaccess) 4479 << ArgIdx << FnName << PointeeTy 4480 << Call->getCallee()->getSourceRange()); 4481 else 4482 continue; 4483 4484 DiagRuntimeBehavior( 4485 Dest->getExprLoc(), Dest, 4486 PDiag(diag::note_bad_memaccess_silence) 4487 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 4488 break; 4489 } 4490 } 4491 } 4492 4493 // A little helper routine: ignore addition and subtraction of integer literals. 4494 // This intentionally does not ignore all integer constant expressions because 4495 // we don't want to remove sizeof(). 4496 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 4497 Ex = Ex->IgnoreParenCasts(); 4498 4499 for (;;) { 4500 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 4501 if (!BO || !BO->isAdditiveOp()) 4502 break; 4503 4504 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 4505 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 4506 4507 if (isa<IntegerLiteral>(RHS)) 4508 Ex = LHS; 4509 else if (isa<IntegerLiteral>(LHS)) 4510 Ex = RHS; 4511 else 4512 break; 4513 } 4514 4515 return Ex; 4516 } 4517 4518 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 4519 ASTContext &Context) { 4520 // Only handle constant-sized or VLAs, but not flexible members. 4521 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 4522 // Only issue the FIXIT for arrays of size > 1. 4523 if (CAT->getSize().getSExtValue() <= 1) 4524 return false; 4525 } else if (!Ty->isVariableArrayType()) { 4526 return false; 4527 } 4528 return true; 4529 } 4530 4531 // Warn if the user has made the 'size' argument to strlcpy or strlcat 4532 // be the size of the source, instead of the destination. 4533 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 4534 IdentifierInfo *FnName) { 4535 4536 // Don't crash if the user has the wrong number of arguments 4537 unsigned NumArgs = Call->getNumArgs(); 4538 if ((NumArgs != 3) && (NumArgs != 4)) 4539 return; 4540 4541 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 4542 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 4543 const Expr *CompareWithSrc = nullptr; 4544 4545 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 4546 Call->getLocStart(), Call->getRParenLoc())) 4547 return; 4548 4549 // Look for 'strlcpy(dst, x, sizeof(x))' 4550 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 4551 CompareWithSrc = Ex; 4552 else { 4553 // Look for 'strlcpy(dst, x, strlen(x))' 4554 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 4555 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 4556 SizeCall->getNumArgs() == 1) 4557 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 4558 } 4559 } 4560 4561 if (!CompareWithSrc) 4562 return; 4563 4564 // Determine if the argument to sizeof/strlen is equal to the source 4565 // argument. In principle there's all kinds of things you could do 4566 // here, for instance creating an == expression and evaluating it with 4567 // EvaluateAsBooleanCondition, but this uses a more direct technique: 4568 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 4569 if (!SrcArgDRE) 4570 return; 4571 4572 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 4573 if (!CompareWithSrcDRE || 4574 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 4575 return; 4576 4577 const Expr *OriginalSizeArg = Call->getArg(2); 4578 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 4579 << OriginalSizeArg->getSourceRange() << FnName; 4580 4581 // Output a FIXIT hint if the destination is an array (rather than a 4582 // pointer to an array). This could be enhanced to handle some 4583 // pointers if we know the actual size, like if DstArg is 'array+2' 4584 // we could say 'sizeof(array)-2'. 4585 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 4586 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 4587 return; 4588 4589 SmallString<128> sizeString; 4590 llvm::raw_svector_ostream OS(sizeString); 4591 OS << "sizeof("; 4592 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4593 OS << ")"; 4594 4595 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 4596 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 4597 OS.str()); 4598 } 4599 4600 /// Check if two expressions refer to the same declaration. 4601 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 4602 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 4603 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 4604 return D1->getDecl() == D2->getDecl(); 4605 return false; 4606 } 4607 4608 static const Expr *getStrlenExprArg(const Expr *E) { 4609 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 4610 const FunctionDecl *FD = CE->getDirectCallee(); 4611 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 4612 return nullptr; 4613 return CE->getArg(0)->IgnoreParenCasts(); 4614 } 4615 return nullptr; 4616 } 4617 4618 // Warn on anti-patterns as the 'size' argument to strncat. 4619 // The correct size argument should look like following: 4620 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 4621 void Sema::CheckStrncatArguments(const CallExpr *CE, 4622 IdentifierInfo *FnName) { 4623 // Don't crash if the user has the wrong number of arguments. 4624 if (CE->getNumArgs() < 3) 4625 return; 4626 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 4627 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 4628 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 4629 4630 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 4631 CE->getRParenLoc())) 4632 return; 4633 4634 // Identify common expressions, which are wrongly used as the size argument 4635 // to strncat and may lead to buffer overflows. 4636 unsigned PatternType = 0; 4637 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 4638 // - sizeof(dst) 4639 if (referToTheSameDecl(SizeOfArg, DstArg)) 4640 PatternType = 1; 4641 // - sizeof(src) 4642 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 4643 PatternType = 2; 4644 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 4645 if (BE->getOpcode() == BO_Sub) { 4646 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 4647 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 4648 // - sizeof(dst) - strlen(dst) 4649 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 4650 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 4651 PatternType = 1; 4652 // - sizeof(src) - (anything) 4653 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 4654 PatternType = 2; 4655 } 4656 } 4657 4658 if (PatternType == 0) 4659 return; 4660 4661 // Generate the diagnostic. 4662 SourceLocation SL = LenArg->getLocStart(); 4663 SourceRange SR = LenArg->getSourceRange(); 4664 SourceManager &SM = getSourceManager(); 4665 4666 // If the function is defined as a builtin macro, do not show macro expansion. 4667 if (SM.isMacroArgExpansion(SL)) { 4668 SL = SM.getSpellingLoc(SL); 4669 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 4670 SM.getSpellingLoc(SR.getEnd())); 4671 } 4672 4673 // Check if the destination is an array (rather than a pointer to an array). 4674 QualType DstTy = DstArg->getType(); 4675 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 4676 Context); 4677 if (!isKnownSizeArray) { 4678 if (PatternType == 1) 4679 Diag(SL, diag::warn_strncat_wrong_size) << SR; 4680 else 4681 Diag(SL, diag::warn_strncat_src_size) << SR; 4682 return; 4683 } 4684 4685 if (PatternType == 1) 4686 Diag(SL, diag::warn_strncat_large_size) << SR; 4687 else 4688 Diag(SL, diag::warn_strncat_src_size) << SR; 4689 4690 SmallString<128> sizeString; 4691 llvm::raw_svector_ostream OS(sizeString); 4692 OS << "sizeof("; 4693 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4694 OS << ") - "; 4695 OS << "strlen("; 4696 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4697 OS << ") - 1"; 4698 4699 Diag(SL, diag::note_strncat_wrong_size) 4700 << FixItHint::CreateReplacement(SR, OS.str()); 4701 } 4702 4703 //===--- CHECK: Return Address of Stack Variable --------------------------===// 4704 4705 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4706 Decl *ParentDecl); 4707 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 4708 Decl *ParentDecl); 4709 4710 /// CheckReturnStackAddr - Check if a return statement returns the address 4711 /// of a stack variable. 4712 static void 4713 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 4714 SourceLocation ReturnLoc) { 4715 4716 Expr *stackE = nullptr; 4717 SmallVector<DeclRefExpr *, 8> refVars; 4718 4719 // Perform checking for returned stack addresses, local blocks, 4720 // label addresses or references to temporaries. 4721 if (lhsType->isPointerType() || 4722 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 4723 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 4724 } else if (lhsType->isReferenceType()) { 4725 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 4726 } 4727 4728 if (!stackE) 4729 return; // Nothing suspicious was found. 4730 4731 SourceLocation diagLoc; 4732 SourceRange diagRange; 4733 if (refVars.empty()) { 4734 diagLoc = stackE->getLocStart(); 4735 diagRange = stackE->getSourceRange(); 4736 } else { 4737 // We followed through a reference variable. 'stackE' contains the 4738 // problematic expression but we will warn at the return statement pointing 4739 // at the reference variable. We will later display the "trail" of 4740 // reference variables using notes. 4741 diagLoc = refVars[0]->getLocStart(); 4742 diagRange = refVars[0]->getSourceRange(); 4743 } 4744 4745 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 4746 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 4747 : diag::warn_ret_stack_addr) 4748 << DR->getDecl()->getDeclName() << diagRange; 4749 } else if (isa<BlockExpr>(stackE)) { // local block. 4750 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 4751 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 4752 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 4753 } else { // local temporary. 4754 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 4755 : diag::warn_ret_local_temp_addr) 4756 << diagRange; 4757 } 4758 4759 // Display the "trail" of reference variables that we followed until we 4760 // found the problematic expression using notes. 4761 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 4762 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 4763 // If this var binds to another reference var, show the range of the next 4764 // var, otherwise the var binds to the problematic expression, in which case 4765 // show the range of the expression. 4766 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 4767 : stackE->getSourceRange(); 4768 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 4769 << VD->getDeclName() << range; 4770 } 4771 } 4772 4773 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 4774 /// check if the expression in a return statement evaluates to an address 4775 /// to a location on the stack, a local block, an address of a label, or a 4776 /// reference to local temporary. The recursion is used to traverse the 4777 /// AST of the return expression, with recursion backtracking when we 4778 /// encounter a subexpression that (1) clearly does not lead to one of the 4779 /// above problematic expressions (2) is something we cannot determine leads to 4780 /// a problematic expression based on such local checking. 4781 /// 4782 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 4783 /// the expression that they point to. Such variables are added to the 4784 /// 'refVars' vector so that we know what the reference variable "trail" was. 4785 /// 4786 /// EvalAddr processes expressions that are pointers that are used as 4787 /// references (and not L-values). EvalVal handles all other values. 4788 /// At the base case of the recursion is a check for the above problematic 4789 /// expressions. 4790 /// 4791 /// This implementation handles: 4792 /// 4793 /// * pointer-to-pointer casts 4794 /// * implicit conversions from array references to pointers 4795 /// * taking the address of fields 4796 /// * arbitrary interplay between "&" and "*" operators 4797 /// * pointer arithmetic from an address of a stack variable 4798 /// * taking the address of an array element where the array is on the stack 4799 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4800 Decl *ParentDecl) { 4801 if (E->isTypeDependent()) 4802 return nullptr; 4803 4804 // We should only be called for evaluating pointer expressions. 4805 assert((E->getType()->isAnyPointerType() || 4806 E->getType()->isBlockPointerType() || 4807 E->getType()->isObjCQualifiedIdType()) && 4808 "EvalAddr only works on pointers"); 4809 4810 E = E->IgnoreParens(); 4811 4812 // Our "symbolic interpreter" is just a dispatch off the currently 4813 // viewed AST node. We then recursively traverse the AST by calling 4814 // EvalAddr and EvalVal appropriately. 4815 switch (E->getStmtClass()) { 4816 case Stmt::DeclRefExprClass: { 4817 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4818 4819 // If we leave the immediate function, the lifetime isn't about to end. 4820 if (DR->refersToEnclosingLocal()) 4821 return nullptr; 4822 4823 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 4824 // If this is a reference variable, follow through to the expression that 4825 // it points to. 4826 if (V->hasLocalStorage() && 4827 V->getType()->isReferenceType() && V->hasInit()) { 4828 // Add the reference variable to the "trail". 4829 refVars.push_back(DR); 4830 return EvalAddr(V->getInit(), refVars, ParentDecl); 4831 } 4832 4833 return nullptr; 4834 } 4835 4836 case Stmt::UnaryOperatorClass: { 4837 // The only unary operator that make sense to handle here 4838 // is AddrOf. All others don't make sense as pointers. 4839 UnaryOperator *U = cast<UnaryOperator>(E); 4840 4841 if (U->getOpcode() == UO_AddrOf) 4842 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 4843 else 4844 return nullptr; 4845 } 4846 4847 case Stmt::BinaryOperatorClass: { 4848 // Handle pointer arithmetic. All other binary operators are not valid 4849 // in this context. 4850 BinaryOperator *B = cast<BinaryOperator>(E); 4851 BinaryOperatorKind op = B->getOpcode(); 4852 4853 if (op != BO_Add && op != BO_Sub) 4854 return nullptr; 4855 4856 Expr *Base = B->getLHS(); 4857 4858 // Determine which argument is the real pointer base. It could be 4859 // the RHS argument instead of the LHS. 4860 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 4861 4862 assert (Base->getType()->isPointerType()); 4863 return EvalAddr(Base, refVars, ParentDecl); 4864 } 4865 4866 // For conditional operators we need to see if either the LHS or RHS are 4867 // valid DeclRefExpr*s. If one of them is valid, we return it. 4868 case Stmt::ConditionalOperatorClass: { 4869 ConditionalOperator *C = cast<ConditionalOperator>(E); 4870 4871 // Handle the GNU extension for missing LHS. 4872 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 4873 if (Expr *LHSExpr = C->getLHS()) { 4874 // In C++, we can have a throw-expression, which has 'void' type. 4875 if (!LHSExpr->getType()->isVoidType()) 4876 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 4877 return LHS; 4878 } 4879 4880 // In C++, we can have a throw-expression, which has 'void' type. 4881 if (C->getRHS()->getType()->isVoidType()) 4882 return nullptr; 4883 4884 return EvalAddr(C->getRHS(), refVars, ParentDecl); 4885 } 4886 4887 case Stmt::BlockExprClass: 4888 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 4889 return E; // local block. 4890 return nullptr; 4891 4892 case Stmt::AddrLabelExprClass: 4893 return E; // address of label. 4894 4895 case Stmt::ExprWithCleanupsClass: 4896 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 4897 ParentDecl); 4898 4899 // For casts, we need to handle conversions from arrays to 4900 // pointer values, and pointer-to-pointer conversions. 4901 case Stmt::ImplicitCastExprClass: 4902 case Stmt::CStyleCastExprClass: 4903 case Stmt::CXXFunctionalCastExprClass: 4904 case Stmt::ObjCBridgedCastExprClass: 4905 case Stmt::CXXStaticCastExprClass: 4906 case Stmt::CXXDynamicCastExprClass: 4907 case Stmt::CXXConstCastExprClass: 4908 case Stmt::CXXReinterpretCastExprClass: { 4909 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 4910 switch (cast<CastExpr>(E)->getCastKind()) { 4911 case CK_LValueToRValue: 4912 case CK_NoOp: 4913 case CK_BaseToDerived: 4914 case CK_DerivedToBase: 4915 case CK_UncheckedDerivedToBase: 4916 case CK_Dynamic: 4917 case CK_CPointerToObjCPointerCast: 4918 case CK_BlockPointerToObjCPointerCast: 4919 case CK_AnyPointerToBlockPointerCast: 4920 return EvalAddr(SubExpr, refVars, ParentDecl); 4921 4922 case CK_ArrayToPointerDecay: 4923 return EvalVal(SubExpr, refVars, ParentDecl); 4924 4925 case CK_BitCast: 4926 if (SubExpr->getType()->isAnyPointerType() || 4927 SubExpr->getType()->isBlockPointerType() || 4928 SubExpr->getType()->isObjCQualifiedIdType()) 4929 return EvalAddr(SubExpr, refVars, ParentDecl); 4930 else 4931 return nullptr; 4932 4933 default: 4934 return nullptr; 4935 } 4936 } 4937 4938 case Stmt::MaterializeTemporaryExprClass: 4939 if (Expr *Result = EvalAddr( 4940 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 4941 refVars, ParentDecl)) 4942 return Result; 4943 4944 return E; 4945 4946 // Everything else: we simply don't reason about them. 4947 default: 4948 return nullptr; 4949 } 4950 } 4951 4952 4953 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 4954 /// See the comments for EvalAddr for more details. 4955 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 4956 Decl *ParentDecl) { 4957 do { 4958 // We should only be called for evaluating non-pointer expressions, or 4959 // expressions with a pointer type that are not used as references but instead 4960 // are l-values (e.g., DeclRefExpr with a pointer type). 4961 4962 // Our "symbolic interpreter" is just a dispatch off the currently 4963 // viewed AST node. We then recursively traverse the AST by calling 4964 // EvalAddr and EvalVal appropriately. 4965 4966 E = E->IgnoreParens(); 4967 switch (E->getStmtClass()) { 4968 case Stmt::ImplicitCastExprClass: { 4969 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 4970 if (IE->getValueKind() == VK_LValue) { 4971 E = IE->getSubExpr(); 4972 continue; 4973 } 4974 return nullptr; 4975 } 4976 4977 case Stmt::ExprWithCleanupsClass: 4978 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 4979 4980 case Stmt::DeclRefExprClass: { 4981 // When we hit a DeclRefExpr we are looking at code that refers to a 4982 // variable's name. If it's not a reference variable we check if it has 4983 // local storage within the function, and if so, return the expression. 4984 DeclRefExpr *DR = cast<DeclRefExpr>(E); 4985 4986 // If we leave the immediate function, the lifetime isn't about to end. 4987 if (DR->refersToEnclosingLocal()) 4988 return nullptr; 4989 4990 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 4991 // Check if it refers to itself, e.g. "int& i = i;". 4992 if (V == ParentDecl) 4993 return DR; 4994 4995 if (V->hasLocalStorage()) { 4996 if (!V->getType()->isReferenceType()) 4997 return DR; 4998 4999 // Reference variable, follow through to the expression that 5000 // it points to. 5001 if (V->hasInit()) { 5002 // Add the reference variable to the "trail". 5003 refVars.push_back(DR); 5004 return EvalVal(V->getInit(), refVars, V); 5005 } 5006 } 5007 } 5008 5009 return nullptr; 5010 } 5011 5012 case Stmt::UnaryOperatorClass: { 5013 // The only unary operator that make sense to handle here 5014 // is Deref. All others don't resolve to a "name." This includes 5015 // handling all sorts of rvalues passed to a unary operator. 5016 UnaryOperator *U = cast<UnaryOperator>(E); 5017 5018 if (U->getOpcode() == UO_Deref) 5019 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 5020 5021 return nullptr; 5022 } 5023 5024 case Stmt::ArraySubscriptExprClass: { 5025 // Array subscripts are potential references to data on the stack. We 5026 // retrieve the DeclRefExpr* for the array variable if it indeed 5027 // has local storage. 5028 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 5029 } 5030 5031 case Stmt::ConditionalOperatorClass: { 5032 // For conditional operators we need to see if either the LHS or RHS are 5033 // non-NULL Expr's. If one is non-NULL, we return it. 5034 ConditionalOperator *C = cast<ConditionalOperator>(E); 5035 5036 // Handle the GNU extension for missing LHS. 5037 if (Expr *LHSExpr = C->getLHS()) { 5038 // In C++, we can have a throw-expression, which has 'void' type. 5039 if (!LHSExpr->getType()->isVoidType()) 5040 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 5041 return LHS; 5042 } 5043 5044 // In C++, we can have a throw-expression, which has 'void' type. 5045 if (C->getRHS()->getType()->isVoidType()) 5046 return nullptr; 5047 5048 return EvalVal(C->getRHS(), refVars, ParentDecl); 5049 } 5050 5051 // Accesses to members are potential references to data on the stack. 5052 case Stmt::MemberExprClass: { 5053 MemberExpr *M = cast<MemberExpr>(E); 5054 5055 // Check for indirect access. We only want direct field accesses. 5056 if (M->isArrow()) 5057 return nullptr; 5058 5059 // Check whether the member type is itself a reference, in which case 5060 // we're not going to refer to the member, but to what the member refers to. 5061 if (M->getMemberDecl()->getType()->isReferenceType()) 5062 return nullptr; 5063 5064 return EvalVal(M->getBase(), refVars, ParentDecl); 5065 } 5066 5067 case Stmt::MaterializeTemporaryExprClass: 5068 if (Expr *Result = EvalVal( 5069 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 5070 refVars, ParentDecl)) 5071 return Result; 5072 5073 return E; 5074 5075 default: 5076 // Check that we don't return or take the address of a reference to a 5077 // temporary. This is only useful in C++. 5078 if (!E->isTypeDependent() && E->isRValue()) 5079 return E; 5080 5081 // Everything else: we simply don't reason about them. 5082 return nullptr; 5083 } 5084 } while (true); 5085 } 5086 5087 void 5088 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 5089 SourceLocation ReturnLoc, 5090 bool isObjCMethod, 5091 const AttrVec *Attrs, 5092 const FunctionDecl *FD) { 5093 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 5094 5095 // Check if the return value is null but should not be. 5096 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) && 5097 CheckNonNullExpr(*this, RetValExp)) 5098 Diag(ReturnLoc, diag::warn_null_ret) 5099 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 5100 5101 // C++11 [basic.stc.dynamic.allocation]p4: 5102 // If an allocation function declared with a non-throwing 5103 // exception-specification fails to allocate storage, it shall return 5104 // a null pointer. Any other allocation function that fails to allocate 5105 // storage shall indicate failure only by throwing an exception [...] 5106 if (FD) { 5107 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 5108 if (Op == OO_New || Op == OO_Array_New) { 5109 const FunctionProtoType *Proto 5110 = FD->getType()->castAs<FunctionProtoType>(); 5111 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 5112 CheckNonNullExpr(*this, RetValExp)) 5113 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 5114 << FD << getLangOpts().CPlusPlus11; 5115 } 5116 } 5117 } 5118 5119 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 5120 5121 /// Check for comparisons of floating point operands using != and ==. 5122 /// Issue a warning if these are no self-comparisons, as they are not likely 5123 /// to do what the programmer intended. 5124 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 5125 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 5126 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 5127 5128 // Special case: check for x == x (which is OK). 5129 // Do not emit warnings for such cases. 5130 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 5131 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 5132 if (DRL->getDecl() == DRR->getDecl()) 5133 return; 5134 5135 5136 // Special case: check for comparisons against literals that can be exactly 5137 // represented by APFloat. In such cases, do not emit a warning. This 5138 // is a heuristic: often comparison against such literals are used to 5139 // detect if a value in a variable has not changed. This clearly can 5140 // lead to false negatives. 5141 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 5142 if (FLL->isExact()) 5143 return; 5144 } else 5145 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 5146 if (FLR->isExact()) 5147 return; 5148 5149 // Check for comparisons with builtin types. 5150 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 5151 if (CL->getBuiltinCallee()) 5152 return; 5153 5154 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 5155 if (CR->getBuiltinCallee()) 5156 return; 5157 5158 // Emit the diagnostic. 5159 Diag(Loc, diag::warn_floatingpoint_eq) 5160 << LHS->getSourceRange() << RHS->getSourceRange(); 5161 } 5162 5163 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 5164 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 5165 5166 namespace { 5167 5168 /// Structure recording the 'active' range of an integer-valued 5169 /// expression. 5170 struct IntRange { 5171 /// The number of bits active in the int. 5172 unsigned Width; 5173 5174 /// True if the int is known not to have negative values. 5175 bool NonNegative; 5176 5177 IntRange(unsigned Width, bool NonNegative) 5178 : Width(Width), NonNegative(NonNegative) 5179 {} 5180 5181 /// Returns the range of the bool type. 5182 static IntRange forBoolType() { 5183 return IntRange(1, true); 5184 } 5185 5186 /// Returns the range of an opaque value of the given integral type. 5187 static IntRange forValueOfType(ASTContext &C, QualType T) { 5188 return forValueOfCanonicalType(C, 5189 T->getCanonicalTypeInternal().getTypePtr()); 5190 } 5191 5192 /// Returns the range of an opaque value of a canonical integral type. 5193 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 5194 assert(T->isCanonicalUnqualified()); 5195 5196 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5197 T = VT->getElementType().getTypePtr(); 5198 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5199 T = CT->getElementType().getTypePtr(); 5200 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5201 T = AT->getValueType().getTypePtr(); 5202 5203 // For enum types, use the known bit width of the enumerators. 5204 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 5205 EnumDecl *Enum = ET->getDecl(); 5206 if (!Enum->isCompleteDefinition()) 5207 return IntRange(C.getIntWidth(QualType(T, 0)), false); 5208 5209 unsigned NumPositive = Enum->getNumPositiveBits(); 5210 unsigned NumNegative = Enum->getNumNegativeBits(); 5211 5212 if (NumNegative == 0) 5213 return IntRange(NumPositive, true/*NonNegative*/); 5214 else 5215 return IntRange(std::max(NumPositive + 1, NumNegative), 5216 false/*NonNegative*/); 5217 } 5218 5219 const BuiltinType *BT = cast<BuiltinType>(T); 5220 assert(BT->isInteger()); 5221 5222 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5223 } 5224 5225 /// Returns the "target" range of a canonical integral type, i.e. 5226 /// the range of values expressible in the type. 5227 /// 5228 /// This matches forValueOfCanonicalType except that enums have the 5229 /// full range of their type, not the range of their enumerators. 5230 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 5231 assert(T->isCanonicalUnqualified()); 5232 5233 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5234 T = VT->getElementType().getTypePtr(); 5235 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5236 T = CT->getElementType().getTypePtr(); 5237 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5238 T = AT->getValueType().getTypePtr(); 5239 if (const EnumType *ET = dyn_cast<EnumType>(T)) 5240 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 5241 5242 const BuiltinType *BT = cast<BuiltinType>(T); 5243 assert(BT->isInteger()); 5244 5245 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5246 } 5247 5248 /// Returns the supremum of two ranges: i.e. their conservative merge. 5249 static IntRange join(IntRange L, IntRange R) { 5250 return IntRange(std::max(L.Width, R.Width), 5251 L.NonNegative && R.NonNegative); 5252 } 5253 5254 /// Returns the infinum of two ranges: i.e. their aggressive merge. 5255 static IntRange meet(IntRange L, IntRange R) { 5256 return IntRange(std::min(L.Width, R.Width), 5257 L.NonNegative || R.NonNegative); 5258 } 5259 }; 5260 5261 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 5262 unsigned MaxWidth) { 5263 if (value.isSigned() && value.isNegative()) 5264 return IntRange(value.getMinSignedBits(), false); 5265 5266 if (value.getBitWidth() > MaxWidth) 5267 value = value.trunc(MaxWidth); 5268 5269 // isNonNegative() just checks the sign bit without considering 5270 // signedness. 5271 return IntRange(value.getActiveBits(), true); 5272 } 5273 5274 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 5275 unsigned MaxWidth) { 5276 if (result.isInt()) 5277 return GetValueRange(C, result.getInt(), MaxWidth); 5278 5279 if (result.isVector()) { 5280 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 5281 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 5282 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 5283 R = IntRange::join(R, El); 5284 } 5285 return R; 5286 } 5287 5288 if (result.isComplexInt()) { 5289 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 5290 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 5291 return IntRange::join(R, I); 5292 } 5293 5294 // This can happen with lossless casts to intptr_t of "based" lvalues. 5295 // Assume it might use arbitrary bits. 5296 // FIXME: The only reason we need to pass the type in here is to get 5297 // the sign right on this one case. It would be nice if APValue 5298 // preserved this. 5299 assert(result.isLValue() || result.isAddrLabelDiff()); 5300 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 5301 } 5302 5303 static QualType GetExprType(Expr *E) { 5304 QualType Ty = E->getType(); 5305 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 5306 Ty = AtomicRHS->getValueType(); 5307 return Ty; 5308 } 5309 5310 /// Pseudo-evaluate the given integer expression, estimating the 5311 /// range of values it might take. 5312 /// 5313 /// \param MaxWidth - the width to which the value will be truncated 5314 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 5315 E = E->IgnoreParens(); 5316 5317 // Try a full evaluation first. 5318 Expr::EvalResult result; 5319 if (E->EvaluateAsRValue(result, C)) 5320 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 5321 5322 // I think we only want to look through implicit casts here; if the 5323 // user has an explicit widening cast, we should treat the value as 5324 // being of the new, wider type. 5325 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 5326 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 5327 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 5328 5329 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 5330 5331 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 5332 5333 // Assume that non-integer casts can span the full range of the type. 5334 if (!isIntegerCast) 5335 return OutputTypeRange; 5336 5337 IntRange SubRange 5338 = GetExprRange(C, CE->getSubExpr(), 5339 std::min(MaxWidth, OutputTypeRange.Width)); 5340 5341 // Bail out if the subexpr's range is as wide as the cast type. 5342 if (SubRange.Width >= OutputTypeRange.Width) 5343 return OutputTypeRange; 5344 5345 // Otherwise, we take the smaller width, and we're non-negative if 5346 // either the output type or the subexpr is. 5347 return IntRange(SubRange.Width, 5348 SubRange.NonNegative || OutputTypeRange.NonNegative); 5349 } 5350 5351 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5352 // If we can fold the condition, just take that operand. 5353 bool CondResult; 5354 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 5355 return GetExprRange(C, CondResult ? CO->getTrueExpr() 5356 : CO->getFalseExpr(), 5357 MaxWidth); 5358 5359 // Otherwise, conservatively merge. 5360 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 5361 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 5362 return IntRange::join(L, R); 5363 } 5364 5365 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5366 switch (BO->getOpcode()) { 5367 5368 // Boolean-valued operations are single-bit and positive. 5369 case BO_LAnd: 5370 case BO_LOr: 5371 case BO_LT: 5372 case BO_GT: 5373 case BO_LE: 5374 case BO_GE: 5375 case BO_EQ: 5376 case BO_NE: 5377 return IntRange::forBoolType(); 5378 5379 // The type of the assignments is the type of the LHS, so the RHS 5380 // is not necessarily the same type. 5381 case BO_MulAssign: 5382 case BO_DivAssign: 5383 case BO_RemAssign: 5384 case BO_AddAssign: 5385 case BO_SubAssign: 5386 case BO_XorAssign: 5387 case BO_OrAssign: 5388 // TODO: bitfields? 5389 return IntRange::forValueOfType(C, GetExprType(E)); 5390 5391 // Simple assignments just pass through the RHS, which will have 5392 // been coerced to the LHS type. 5393 case BO_Assign: 5394 // TODO: bitfields? 5395 return GetExprRange(C, BO->getRHS(), MaxWidth); 5396 5397 // Operations with opaque sources are black-listed. 5398 case BO_PtrMemD: 5399 case BO_PtrMemI: 5400 return IntRange::forValueOfType(C, GetExprType(E)); 5401 5402 // Bitwise-and uses the *infinum* of the two source ranges. 5403 case BO_And: 5404 case BO_AndAssign: 5405 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 5406 GetExprRange(C, BO->getRHS(), MaxWidth)); 5407 5408 // Left shift gets black-listed based on a judgement call. 5409 case BO_Shl: 5410 // ...except that we want to treat '1 << (blah)' as logically 5411 // positive. It's an important idiom. 5412 if (IntegerLiteral *I 5413 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 5414 if (I->getValue() == 1) { 5415 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 5416 return IntRange(R.Width, /*NonNegative*/ true); 5417 } 5418 } 5419 // fallthrough 5420 5421 case BO_ShlAssign: 5422 return IntRange::forValueOfType(C, GetExprType(E)); 5423 5424 // Right shift by a constant can narrow its left argument. 5425 case BO_Shr: 5426 case BO_ShrAssign: { 5427 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5428 5429 // If the shift amount is a positive constant, drop the width by 5430 // that much. 5431 llvm::APSInt shift; 5432 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 5433 shift.isNonNegative()) { 5434 unsigned zext = shift.getZExtValue(); 5435 if (zext >= L.Width) 5436 L.Width = (L.NonNegative ? 0 : 1); 5437 else 5438 L.Width -= zext; 5439 } 5440 5441 return L; 5442 } 5443 5444 // Comma acts as its right operand. 5445 case BO_Comma: 5446 return GetExprRange(C, BO->getRHS(), MaxWidth); 5447 5448 // Black-list pointer subtractions. 5449 case BO_Sub: 5450 if (BO->getLHS()->getType()->isPointerType()) 5451 return IntRange::forValueOfType(C, GetExprType(E)); 5452 break; 5453 5454 // The width of a division result is mostly determined by the size 5455 // of the LHS. 5456 case BO_Div: { 5457 // Don't 'pre-truncate' the operands. 5458 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5459 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5460 5461 // If the divisor is constant, use that. 5462 llvm::APSInt divisor; 5463 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 5464 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 5465 if (log2 >= L.Width) 5466 L.Width = (L.NonNegative ? 0 : 1); 5467 else 5468 L.Width = std::min(L.Width - log2, MaxWidth); 5469 return L; 5470 } 5471 5472 // Otherwise, just use the LHS's width. 5473 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5474 return IntRange(L.Width, L.NonNegative && R.NonNegative); 5475 } 5476 5477 // The result of a remainder can't be larger than the result of 5478 // either side. 5479 case BO_Rem: { 5480 // Don't 'pre-truncate' the operands. 5481 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5482 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5483 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5484 5485 IntRange meet = IntRange::meet(L, R); 5486 meet.Width = std::min(meet.Width, MaxWidth); 5487 return meet; 5488 } 5489 5490 // The default behavior is okay for these. 5491 case BO_Mul: 5492 case BO_Add: 5493 case BO_Xor: 5494 case BO_Or: 5495 break; 5496 } 5497 5498 // The default case is to treat the operation as if it were closed 5499 // on the narrowest type that encompasses both operands. 5500 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5501 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 5502 return IntRange::join(L, R); 5503 } 5504 5505 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 5506 switch (UO->getOpcode()) { 5507 // Boolean-valued operations are white-listed. 5508 case UO_LNot: 5509 return IntRange::forBoolType(); 5510 5511 // Operations with opaque sources are black-listed. 5512 case UO_Deref: 5513 case UO_AddrOf: // should be impossible 5514 return IntRange::forValueOfType(C, GetExprType(E)); 5515 5516 default: 5517 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 5518 } 5519 } 5520 5521 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 5522 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 5523 5524 if (FieldDecl *BitField = E->getSourceBitField()) 5525 return IntRange(BitField->getBitWidthValue(C), 5526 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 5527 5528 return IntRange::forValueOfType(C, GetExprType(E)); 5529 } 5530 5531 static IntRange GetExprRange(ASTContext &C, Expr *E) { 5532 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 5533 } 5534 5535 /// Checks whether the given value, which currently has the given 5536 /// source semantics, has the same value when coerced through the 5537 /// target semantics. 5538 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 5539 const llvm::fltSemantics &Src, 5540 const llvm::fltSemantics &Tgt) { 5541 llvm::APFloat truncated = value; 5542 5543 bool ignored; 5544 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 5545 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 5546 5547 return truncated.bitwiseIsEqual(value); 5548 } 5549 5550 /// Checks whether the given value, which currently has the given 5551 /// source semantics, has the same value when coerced through the 5552 /// target semantics. 5553 /// 5554 /// The value might be a vector of floats (or a complex number). 5555 static bool IsSameFloatAfterCast(const APValue &value, 5556 const llvm::fltSemantics &Src, 5557 const llvm::fltSemantics &Tgt) { 5558 if (value.isFloat()) 5559 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 5560 5561 if (value.isVector()) { 5562 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 5563 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 5564 return false; 5565 return true; 5566 } 5567 5568 assert(value.isComplexFloat()); 5569 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 5570 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 5571 } 5572 5573 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 5574 5575 static bool IsZero(Sema &S, Expr *E) { 5576 // Suppress cases where we are comparing against an enum constant. 5577 if (const DeclRefExpr *DR = 5578 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 5579 if (isa<EnumConstantDecl>(DR->getDecl())) 5580 return false; 5581 5582 // Suppress cases where the '0' value is expanded from a macro. 5583 if (E->getLocStart().isMacroID()) 5584 return false; 5585 5586 llvm::APSInt Value; 5587 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 5588 } 5589 5590 static bool HasEnumType(Expr *E) { 5591 // Strip off implicit integral promotions. 5592 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5593 if (ICE->getCastKind() != CK_IntegralCast && 5594 ICE->getCastKind() != CK_NoOp) 5595 break; 5596 E = ICE->getSubExpr(); 5597 } 5598 5599 return E->getType()->isEnumeralType(); 5600 } 5601 5602 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 5603 // Disable warning in template instantiations. 5604 if (!S.ActiveTemplateInstantiations.empty()) 5605 return; 5606 5607 BinaryOperatorKind op = E->getOpcode(); 5608 if (E->isValueDependent()) 5609 return; 5610 5611 if (op == BO_LT && IsZero(S, E->getRHS())) { 5612 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5613 << "< 0" << "false" << HasEnumType(E->getLHS()) 5614 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5615 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 5616 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5617 << ">= 0" << "true" << HasEnumType(E->getLHS()) 5618 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5619 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 5620 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5621 << "0 >" << "false" << HasEnumType(E->getRHS()) 5622 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5623 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 5624 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5625 << "0 <=" << "true" << HasEnumType(E->getRHS()) 5626 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5627 } 5628 } 5629 5630 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 5631 Expr *Constant, Expr *Other, 5632 llvm::APSInt Value, 5633 bool RhsConstant) { 5634 // Disable warning in template instantiations. 5635 if (!S.ActiveTemplateInstantiations.empty()) 5636 return; 5637 5638 // TODO: Investigate using GetExprRange() to get tighter bounds 5639 // on the bit ranges. 5640 QualType OtherT = Other->getType(); 5641 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT)) 5642 OtherT = AT->getValueType(); 5643 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 5644 unsigned OtherWidth = OtherRange.Width; 5645 5646 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 5647 5648 // 0 values are handled later by CheckTrivialUnsignedComparison(). 5649 if ((Value == 0) && (!OtherIsBooleanType)) 5650 return; 5651 5652 BinaryOperatorKind op = E->getOpcode(); 5653 bool IsTrue = true; 5654 5655 // Used for diagnostic printout. 5656 enum { 5657 LiteralConstant = 0, 5658 CXXBoolLiteralTrue, 5659 CXXBoolLiteralFalse 5660 } LiteralOrBoolConstant = LiteralConstant; 5661 5662 if (!OtherIsBooleanType) { 5663 QualType ConstantT = Constant->getType(); 5664 QualType CommonT = E->getLHS()->getType(); 5665 5666 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 5667 return; 5668 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 5669 "comparison with non-integer type"); 5670 5671 bool ConstantSigned = ConstantT->isSignedIntegerType(); 5672 bool CommonSigned = CommonT->isSignedIntegerType(); 5673 5674 bool EqualityOnly = false; 5675 5676 if (CommonSigned) { 5677 // The common type is signed, therefore no signed to unsigned conversion. 5678 if (!OtherRange.NonNegative) { 5679 // Check that the constant is representable in type OtherT. 5680 if (ConstantSigned) { 5681 if (OtherWidth >= Value.getMinSignedBits()) 5682 return; 5683 } else { // !ConstantSigned 5684 if (OtherWidth >= Value.getActiveBits() + 1) 5685 return; 5686 } 5687 } else { // !OtherSigned 5688 // Check that the constant is representable in type OtherT. 5689 // Negative values are out of range. 5690 if (ConstantSigned) { 5691 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 5692 return; 5693 } else { // !ConstantSigned 5694 if (OtherWidth >= Value.getActiveBits()) 5695 return; 5696 } 5697 } 5698 } else { // !CommonSigned 5699 if (OtherRange.NonNegative) { 5700 if (OtherWidth >= Value.getActiveBits()) 5701 return; 5702 } else { // OtherSigned 5703 assert(!ConstantSigned && 5704 "Two signed types converted to unsigned types."); 5705 // Check to see if the constant is representable in OtherT. 5706 if (OtherWidth > Value.getActiveBits()) 5707 return; 5708 // Check to see if the constant is equivalent to a negative value 5709 // cast to CommonT. 5710 if (S.Context.getIntWidth(ConstantT) == 5711 S.Context.getIntWidth(CommonT) && 5712 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 5713 return; 5714 // The constant value rests between values that OtherT can represent 5715 // after conversion. Relational comparison still works, but equality 5716 // comparisons will be tautological. 5717 EqualityOnly = true; 5718 } 5719 } 5720 5721 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 5722 5723 if (op == BO_EQ || op == BO_NE) { 5724 IsTrue = op == BO_NE; 5725 } else if (EqualityOnly) { 5726 return; 5727 } else if (RhsConstant) { 5728 if (op == BO_GT || op == BO_GE) 5729 IsTrue = !PositiveConstant; 5730 else // op == BO_LT || op == BO_LE 5731 IsTrue = PositiveConstant; 5732 } else { 5733 if (op == BO_LT || op == BO_LE) 5734 IsTrue = !PositiveConstant; 5735 else // op == BO_GT || op == BO_GE 5736 IsTrue = PositiveConstant; 5737 } 5738 } else { 5739 // Other isKnownToHaveBooleanValue 5740 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 5741 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 5742 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 5743 5744 static const struct LinkedConditions { 5745 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 5746 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 5747 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 5748 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 5749 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 5750 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 5751 5752 } TruthTable = { 5753 // Constant on LHS. | Constant on RHS. | 5754 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 5755 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 5756 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 5757 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 5758 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 5759 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 5760 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 5761 }; 5762 5763 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 5764 5765 enum ConstantValue ConstVal = Zero; 5766 if (Value.isUnsigned() || Value.isNonNegative()) { 5767 if (Value == 0) { 5768 LiteralOrBoolConstant = 5769 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 5770 ConstVal = Zero; 5771 } else if (Value == 1) { 5772 LiteralOrBoolConstant = 5773 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 5774 ConstVal = One; 5775 } else { 5776 LiteralOrBoolConstant = LiteralConstant; 5777 ConstVal = GT_One; 5778 } 5779 } else { 5780 ConstVal = LT_Zero; 5781 } 5782 5783 CompareBoolWithConstantResult CmpRes; 5784 5785 switch (op) { 5786 case BO_LT: 5787 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 5788 break; 5789 case BO_GT: 5790 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 5791 break; 5792 case BO_LE: 5793 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 5794 break; 5795 case BO_GE: 5796 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 5797 break; 5798 case BO_EQ: 5799 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 5800 break; 5801 case BO_NE: 5802 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 5803 break; 5804 default: 5805 CmpRes = Unkwn; 5806 break; 5807 } 5808 5809 if (CmpRes == AFals) { 5810 IsTrue = false; 5811 } else if (CmpRes == ATrue) { 5812 IsTrue = true; 5813 } else { 5814 return; 5815 } 5816 } 5817 5818 // If this is a comparison to an enum constant, include that 5819 // constant in the diagnostic. 5820 const EnumConstantDecl *ED = nullptr; 5821 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 5822 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 5823 5824 SmallString<64> PrettySourceValue; 5825 llvm::raw_svector_ostream OS(PrettySourceValue); 5826 if (ED) 5827 OS << '\'' << *ED << "' (" << Value << ")"; 5828 else 5829 OS << Value; 5830 5831 S.DiagRuntimeBehavior( 5832 E->getOperatorLoc(), E, 5833 S.PDiag(diag::warn_out_of_range_compare) 5834 << OS.str() << LiteralOrBoolConstant 5835 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 5836 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 5837 } 5838 5839 /// Analyze the operands of the given comparison. Implements the 5840 /// fallback case from AnalyzeComparison. 5841 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 5842 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 5843 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 5844 } 5845 5846 /// \brief Implements -Wsign-compare. 5847 /// 5848 /// \param E the binary operator to check for warnings 5849 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 5850 // The type the comparison is being performed in. 5851 QualType T = E->getLHS()->getType(); 5852 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 5853 && "comparison with mismatched types"); 5854 if (E->isValueDependent()) 5855 return AnalyzeImpConvsInComparison(S, E); 5856 5857 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 5858 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 5859 5860 bool IsComparisonConstant = false; 5861 5862 // Check whether an integer constant comparison results in a value 5863 // of 'true' or 'false'. 5864 if (T->isIntegralType(S.Context)) { 5865 llvm::APSInt RHSValue; 5866 bool IsRHSIntegralLiteral = 5867 RHS->isIntegerConstantExpr(RHSValue, S.Context); 5868 llvm::APSInt LHSValue; 5869 bool IsLHSIntegralLiteral = 5870 LHS->isIntegerConstantExpr(LHSValue, S.Context); 5871 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 5872 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 5873 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 5874 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 5875 else 5876 IsComparisonConstant = 5877 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 5878 } else if (!T->hasUnsignedIntegerRepresentation()) 5879 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 5880 5881 // We don't do anything special if this isn't an unsigned integral 5882 // comparison: we're only interested in integral comparisons, and 5883 // signed comparisons only happen in cases we don't care to warn about. 5884 // 5885 // We also don't care about value-dependent expressions or expressions 5886 // whose result is a constant. 5887 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 5888 return AnalyzeImpConvsInComparison(S, E); 5889 5890 // Check to see if one of the (unmodified) operands is of different 5891 // signedness. 5892 Expr *signedOperand, *unsignedOperand; 5893 if (LHS->getType()->hasSignedIntegerRepresentation()) { 5894 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 5895 "unsigned comparison between two signed integer expressions?"); 5896 signedOperand = LHS; 5897 unsignedOperand = RHS; 5898 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 5899 signedOperand = RHS; 5900 unsignedOperand = LHS; 5901 } else { 5902 CheckTrivialUnsignedComparison(S, E); 5903 return AnalyzeImpConvsInComparison(S, E); 5904 } 5905 5906 // Otherwise, calculate the effective range of the signed operand. 5907 IntRange signedRange = GetExprRange(S.Context, signedOperand); 5908 5909 // Go ahead and analyze implicit conversions in the operands. Note 5910 // that we skip the implicit conversions on both sides. 5911 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 5912 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 5913 5914 // If the signed range is non-negative, -Wsign-compare won't fire, 5915 // but we should still check for comparisons which are always true 5916 // or false. 5917 if (signedRange.NonNegative) 5918 return CheckTrivialUnsignedComparison(S, E); 5919 5920 // For (in)equality comparisons, if the unsigned operand is a 5921 // constant which cannot collide with a overflowed signed operand, 5922 // then reinterpreting the signed operand as unsigned will not 5923 // change the result of the comparison. 5924 if (E->isEqualityOp()) { 5925 unsigned comparisonWidth = S.Context.getIntWidth(T); 5926 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 5927 5928 // We should never be unable to prove that the unsigned operand is 5929 // non-negative. 5930 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 5931 5932 if (unsignedRange.Width < comparisonWidth) 5933 return; 5934 } 5935 5936 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 5937 S.PDiag(diag::warn_mixed_sign_comparison) 5938 << LHS->getType() << RHS->getType() 5939 << LHS->getSourceRange() << RHS->getSourceRange()); 5940 } 5941 5942 /// Analyzes an attempt to assign the given value to a bitfield. 5943 /// 5944 /// Returns true if there was something fishy about the attempt. 5945 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 5946 SourceLocation InitLoc) { 5947 assert(Bitfield->isBitField()); 5948 if (Bitfield->isInvalidDecl()) 5949 return false; 5950 5951 // White-list bool bitfields. 5952 if (Bitfield->getType()->isBooleanType()) 5953 return false; 5954 5955 // Ignore value- or type-dependent expressions. 5956 if (Bitfield->getBitWidth()->isValueDependent() || 5957 Bitfield->getBitWidth()->isTypeDependent() || 5958 Init->isValueDependent() || 5959 Init->isTypeDependent()) 5960 return false; 5961 5962 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 5963 5964 llvm::APSInt Value; 5965 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 5966 return false; 5967 5968 unsigned OriginalWidth = Value.getBitWidth(); 5969 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 5970 5971 if (OriginalWidth <= FieldWidth) 5972 return false; 5973 5974 // Compute the value which the bitfield will contain. 5975 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 5976 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 5977 5978 // Check whether the stored value is equal to the original value. 5979 TruncatedValue = TruncatedValue.extend(OriginalWidth); 5980 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 5981 return false; 5982 5983 // Special-case bitfields of width 1: booleans are naturally 0/1, and 5984 // therefore don't strictly fit into a signed bitfield of width 1. 5985 if (FieldWidth == 1 && Value == 1) 5986 return false; 5987 5988 std::string PrettyValue = Value.toString(10); 5989 std::string PrettyTrunc = TruncatedValue.toString(10); 5990 5991 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 5992 << PrettyValue << PrettyTrunc << OriginalInit->getType() 5993 << Init->getSourceRange(); 5994 5995 return true; 5996 } 5997 5998 /// Analyze the given simple or compound assignment for warning-worthy 5999 /// operations. 6000 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 6001 // Just recurse on the LHS. 6002 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 6003 6004 // We want to recurse on the RHS as normal unless we're assigning to 6005 // a bitfield. 6006 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 6007 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 6008 E->getOperatorLoc())) { 6009 // Recurse, ignoring any implicit conversions on the RHS. 6010 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 6011 E->getOperatorLoc()); 6012 } 6013 } 6014 6015 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 6016 } 6017 6018 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6019 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 6020 SourceLocation CContext, unsigned diag, 6021 bool pruneControlFlow = false) { 6022 if (pruneControlFlow) { 6023 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6024 S.PDiag(diag) 6025 << SourceType << T << E->getSourceRange() 6026 << SourceRange(CContext)); 6027 return; 6028 } 6029 S.Diag(E->getExprLoc(), diag) 6030 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 6031 } 6032 6033 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6034 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 6035 SourceLocation CContext, unsigned diag, 6036 bool pruneControlFlow = false) { 6037 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 6038 } 6039 6040 /// Diagnose an implicit cast from a literal expression. Does not warn when the 6041 /// cast wouldn't lose information. 6042 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 6043 SourceLocation CContext) { 6044 // Try to convert the literal exactly to an integer. If we can, don't warn. 6045 bool isExact = false; 6046 const llvm::APFloat &Value = FL->getValue(); 6047 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 6048 T->hasUnsignedIntegerRepresentation()); 6049 if (Value.convertToInteger(IntegerValue, 6050 llvm::APFloat::rmTowardZero, &isExact) 6051 == llvm::APFloat::opOK && isExact) 6052 return; 6053 6054 // FIXME: Force the precision of the source value down so we don't print 6055 // digits which are usually useless (we don't really care here if we 6056 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 6057 // would automatically print the shortest representation, but it's a bit 6058 // tricky to implement. 6059 SmallString<16> PrettySourceValue; 6060 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 6061 precision = (precision * 59 + 195) / 196; 6062 Value.toString(PrettySourceValue, precision); 6063 6064 SmallString<16> PrettyTargetValue; 6065 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 6066 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 6067 else 6068 IntegerValue.toString(PrettyTargetValue); 6069 6070 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 6071 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 6072 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 6073 } 6074 6075 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 6076 if (!Range.Width) return "0"; 6077 6078 llvm::APSInt ValueInRange = Value; 6079 ValueInRange.setIsSigned(!Range.NonNegative); 6080 ValueInRange = ValueInRange.trunc(Range.Width); 6081 return ValueInRange.toString(10); 6082 } 6083 6084 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 6085 if (!isa<ImplicitCastExpr>(Ex)) 6086 return false; 6087 6088 Expr *InnerE = Ex->IgnoreParenImpCasts(); 6089 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 6090 const Type *Source = 6091 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 6092 if (Target->isDependentType()) 6093 return false; 6094 6095 const BuiltinType *FloatCandidateBT = 6096 dyn_cast<BuiltinType>(ToBool ? Source : Target); 6097 const Type *BoolCandidateType = ToBool ? Target : Source; 6098 6099 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 6100 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 6101 } 6102 6103 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 6104 SourceLocation CC) { 6105 unsigned NumArgs = TheCall->getNumArgs(); 6106 for (unsigned i = 0; i < NumArgs; ++i) { 6107 Expr *CurrA = TheCall->getArg(i); 6108 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 6109 continue; 6110 6111 bool IsSwapped = ((i > 0) && 6112 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 6113 IsSwapped |= ((i < (NumArgs - 1)) && 6114 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 6115 if (IsSwapped) { 6116 // Warn on this floating-point to bool conversion. 6117 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 6118 CurrA->getType(), CC, 6119 diag::warn_impcast_floating_point_to_bool); 6120 } 6121 } 6122 } 6123 6124 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 6125 SourceLocation CC, bool *ICContext = nullptr) { 6126 if (E->isTypeDependent() || E->isValueDependent()) return; 6127 6128 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 6129 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 6130 if (Source == Target) return; 6131 if (Target->isDependentType()) return; 6132 6133 // If the conversion context location is invalid don't complain. We also 6134 // don't want to emit a warning if the issue occurs from the expansion of 6135 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 6136 // delay this check as long as possible. Once we detect we are in that 6137 // scenario, we just return. 6138 if (CC.isInvalid()) 6139 return; 6140 6141 // Diagnose implicit casts to bool. 6142 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 6143 if (isa<StringLiteral>(E)) 6144 // Warn on string literal to bool. Checks for string literals in logical 6145 // and expressions, for instance, assert(0 && "error here"), are 6146 // prevented by a check in AnalyzeImplicitConversions(). 6147 return DiagnoseImpCast(S, E, T, CC, 6148 diag::warn_impcast_string_literal_to_bool); 6149 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 6150 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 6151 // This covers the literal expressions that evaluate to Objective-C 6152 // objects. 6153 return DiagnoseImpCast(S, E, T, CC, 6154 diag::warn_impcast_objective_c_literal_to_bool); 6155 } 6156 if (Source->isPointerType() || Source->canDecayToPointerType()) { 6157 // Warn on pointer to bool conversion that is always true. 6158 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 6159 SourceRange(CC)); 6160 } 6161 } 6162 6163 // Strip vector types. 6164 if (isa<VectorType>(Source)) { 6165 if (!isa<VectorType>(Target)) { 6166 if (S.SourceMgr.isInSystemMacro(CC)) 6167 return; 6168 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 6169 } 6170 6171 // If the vector cast is cast between two vectors of the same size, it is 6172 // a bitcast, not a conversion. 6173 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 6174 return; 6175 6176 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 6177 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 6178 } 6179 if (auto VecTy = dyn_cast<VectorType>(Target)) 6180 Target = VecTy->getElementType().getTypePtr(); 6181 6182 // Strip complex types. 6183 if (isa<ComplexType>(Source)) { 6184 if (!isa<ComplexType>(Target)) { 6185 if (S.SourceMgr.isInSystemMacro(CC)) 6186 return; 6187 6188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 6189 } 6190 6191 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 6192 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 6193 } 6194 6195 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 6196 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 6197 6198 // If the source is floating point... 6199 if (SourceBT && SourceBT->isFloatingPoint()) { 6200 // ...and the target is floating point... 6201 if (TargetBT && TargetBT->isFloatingPoint()) { 6202 // ...then warn if we're dropping FP rank. 6203 6204 // Builtin FP kinds are ordered by increasing FP rank. 6205 if (SourceBT->getKind() > TargetBT->getKind()) { 6206 // Don't warn about float constants that are precisely 6207 // representable in the target type. 6208 Expr::EvalResult result; 6209 if (E->EvaluateAsRValue(result, S.Context)) { 6210 // Value might be a float, a float vector, or a float complex. 6211 if (IsSameFloatAfterCast(result.Val, 6212 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 6213 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 6214 return; 6215 } 6216 6217 if (S.SourceMgr.isInSystemMacro(CC)) 6218 return; 6219 6220 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 6221 } 6222 return; 6223 } 6224 6225 // If the target is integral, always warn. 6226 if (TargetBT && TargetBT->isInteger()) { 6227 if (S.SourceMgr.isInSystemMacro(CC)) 6228 return; 6229 6230 Expr *InnerE = E->IgnoreParenImpCasts(); 6231 // We also want to warn on, e.g., "int i = -1.234" 6232 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 6233 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 6234 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 6235 6236 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 6237 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 6238 } else { 6239 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 6240 } 6241 } 6242 6243 // If the target is bool, warn if expr is a function or method call. 6244 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 6245 isa<CallExpr>(E)) { 6246 // Check last argument of function call to see if it is an 6247 // implicit cast from a type matching the type the result 6248 // is being cast to. 6249 CallExpr *CEx = cast<CallExpr>(E); 6250 unsigned NumArgs = CEx->getNumArgs(); 6251 if (NumArgs > 0) { 6252 Expr *LastA = CEx->getArg(NumArgs - 1); 6253 Expr *InnerE = LastA->IgnoreParenImpCasts(); 6254 const Type *InnerType = 6255 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 6256 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 6257 // Warn on this floating-point to bool conversion 6258 DiagnoseImpCast(S, E, T, CC, 6259 diag::warn_impcast_floating_point_to_bool); 6260 } 6261 } 6262 } 6263 return; 6264 } 6265 6266 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 6267 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 6268 && !Target->isBlockPointerType() && !Target->isMemberPointerType() 6269 && Target->isScalarType() && !Target->isNullPtrType()) { 6270 SourceLocation Loc = E->getSourceRange().getBegin(); 6271 if (Loc.isMacroID()) 6272 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 6273 if (!Loc.isMacroID() || CC.isMacroID()) 6274 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 6275 << T << clang::SourceRange(CC) 6276 << FixItHint::CreateReplacement(Loc, 6277 S.getFixItZeroLiteralForType(T, Loc)); 6278 } 6279 6280 if (!Source->isIntegerType() || !Target->isIntegerType()) 6281 return; 6282 6283 // TODO: remove this early return once the false positives for constant->bool 6284 // in templates, macros, etc, are reduced or removed. 6285 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 6286 return; 6287 6288 IntRange SourceRange = GetExprRange(S.Context, E); 6289 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 6290 6291 if (SourceRange.Width > TargetRange.Width) { 6292 // If the source is a constant, use a default-on diagnostic. 6293 // TODO: this should happen for bitfield stores, too. 6294 llvm::APSInt Value(32); 6295 if (E->isIntegerConstantExpr(Value, S.Context)) { 6296 if (S.SourceMgr.isInSystemMacro(CC)) 6297 return; 6298 6299 std::string PrettySourceValue = Value.toString(10); 6300 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 6301 6302 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6303 S.PDiag(diag::warn_impcast_integer_precision_constant) 6304 << PrettySourceValue << PrettyTargetValue 6305 << E->getType() << T << E->getSourceRange() 6306 << clang::SourceRange(CC)); 6307 return; 6308 } 6309 6310 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 6311 if (S.SourceMgr.isInSystemMacro(CC)) 6312 return; 6313 6314 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 6315 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 6316 /* pruneControlFlow */ true); 6317 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 6318 } 6319 6320 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 6321 (!TargetRange.NonNegative && SourceRange.NonNegative && 6322 SourceRange.Width == TargetRange.Width)) { 6323 6324 if (S.SourceMgr.isInSystemMacro(CC)) 6325 return; 6326 6327 unsigned DiagID = diag::warn_impcast_integer_sign; 6328 6329 // Traditionally, gcc has warned about this under -Wsign-compare. 6330 // We also want to warn about it in -Wconversion. 6331 // So if -Wconversion is off, use a completely identical diagnostic 6332 // in the sign-compare group. 6333 // The conditional-checking code will 6334 if (ICContext) { 6335 DiagID = diag::warn_impcast_integer_sign_conditional; 6336 *ICContext = true; 6337 } 6338 6339 return DiagnoseImpCast(S, E, T, CC, DiagID); 6340 } 6341 6342 // Diagnose conversions between different enumeration types. 6343 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 6344 // type, to give us better diagnostics. 6345 QualType SourceType = E->getType(); 6346 if (!S.getLangOpts().CPlusPlus) { 6347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6348 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 6349 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 6350 SourceType = S.Context.getTypeDeclType(Enum); 6351 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 6352 } 6353 } 6354 6355 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 6356 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 6357 if (SourceEnum->getDecl()->hasNameForLinkage() && 6358 TargetEnum->getDecl()->hasNameForLinkage() && 6359 SourceEnum != TargetEnum) { 6360 if (S.SourceMgr.isInSystemMacro(CC)) 6361 return; 6362 6363 return DiagnoseImpCast(S, E, SourceType, T, CC, 6364 diag::warn_impcast_different_enum_types); 6365 } 6366 6367 return; 6368 } 6369 6370 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6371 SourceLocation CC, QualType T); 6372 6373 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 6374 SourceLocation CC, bool &ICContext) { 6375 E = E->IgnoreParenImpCasts(); 6376 6377 if (isa<ConditionalOperator>(E)) 6378 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 6379 6380 AnalyzeImplicitConversions(S, E, CC); 6381 if (E->getType() != T) 6382 return CheckImplicitConversion(S, E, T, CC, &ICContext); 6383 return; 6384 } 6385 6386 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6387 SourceLocation CC, QualType T) { 6388 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 6389 6390 bool Suspicious = false; 6391 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 6392 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 6393 6394 // If -Wconversion would have warned about either of the candidates 6395 // for a signedness conversion to the context type... 6396 if (!Suspicious) return; 6397 6398 // ...but it's currently ignored... 6399 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 6400 return; 6401 6402 // ...then check whether it would have warned about either of the 6403 // candidates for a signedness conversion to the condition type. 6404 if (E->getType() == T) return; 6405 6406 Suspicious = false; 6407 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 6408 E->getType(), CC, &Suspicious); 6409 if (!Suspicious) 6410 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 6411 E->getType(), CC, &Suspicious); 6412 } 6413 6414 /// AnalyzeImplicitConversions - Find and report any interesting 6415 /// implicit conversions in the given expression. There are a couple 6416 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 6417 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 6418 QualType T = OrigE->getType(); 6419 Expr *E = OrigE->IgnoreParenImpCasts(); 6420 6421 if (E->isTypeDependent() || E->isValueDependent()) 6422 return; 6423 6424 // For conditional operators, we analyze the arguments as if they 6425 // were being fed directly into the output. 6426 if (isa<ConditionalOperator>(E)) { 6427 ConditionalOperator *CO = cast<ConditionalOperator>(E); 6428 CheckConditionalOperator(S, CO, CC, T); 6429 return; 6430 } 6431 6432 // Check implicit argument conversions for function calls. 6433 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 6434 CheckImplicitArgumentConversions(S, Call, CC); 6435 6436 // Go ahead and check any implicit conversions we might have skipped. 6437 // The non-canonical typecheck is just an optimization; 6438 // CheckImplicitConversion will filter out dead implicit conversions. 6439 if (E->getType() != T) 6440 CheckImplicitConversion(S, E, T, CC); 6441 6442 // Now continue drilling into this expression. 6443 6444 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) { 6445 if (POE->getResultExpr()) 6446 E = POE->getResultExpr(); 6447 } 6448 6449 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 6450 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 6451 6452 // Skip past explicit casts. 6453 if (isa<ExplicitCastExpr>(E)) { 6454 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 6455 return AnalyzeImplicitConversions(S, E, CC); 6456 } 6457 6458 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6459 // Do a somewhat different check with comparison operators. 6460 if (BO->isComparisonOp()) 6461 return AnalyzeComparison(S, BO); 6462 6463 // And with simple assignments. 6464 if (BO->getOpcode() == BO_Assign) 6465 return AnalyzeAssignment(S, BO); 6466 } 6467 6468 // These break the otherwise-useful invariant below. Fortunately, 6469 // we don't really need to recurse into them, because any internal 6470 // expressions should have been analyzed already when they were 6471 // built into statements. 6472 if (isa<StmtExpr>(E)) return; 6473 6474 // Don't descend into unevaluated contexts. 6475 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 6476 6477 // Now just recurse over the expression's children. 6478 CC = E->getExprLoc(); 6479 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 6480 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 6481 for (Stmt::child_range I = E->children(); I; ++I) { 6482 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 6483 if (!ChildExpr) 6484 continue; 6485 6486 if (IsLogicalAndOperator && 6487 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 6488 // Ignore checking string literals that are in logical and operators. 6489 // This is a common pattern for asserts. 6490 continue; 6491 AnalyzeImplicitConversions(S, ChildExpr, CC); 6492 } 6493 } 6494 6495 } // end anonymous namespace 6496 6497 enum { 6498 AddressOf, 6499 FunctionPointer, 6500 ArrayPointer 6501 }; 6502 6503 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 6504 // Returns true when emitting a warning about taking the address of a reference. 6505 static bool CheckForReference(Sema &SemaRef, const Expr *E, 6506 PartialDiagnostic PD) { 6507 E = E->IgnoreParenImpCasts(); 6508 6509 const FunctionDecl *FD = nullptr; 6510 6511 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6512 if (!DRE->getDecl()->getType()->isReferenceType()) 6513 return false; 6514 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6515 if (!M->getMemberDecl()->getType()->isReferenceType()) 6516 return false; 6517 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 6518 if (!Call->getCallReturnType()->isReferenceType()) 6519 return false; 6520 FD = Call->getDirectCallee(); 6521 } else { 6522 return false; 6523 } 6524 6525 SemaRef.Diag(E->getExprLoc(), PD); 6526 6527 // If possible, point to location of function. 6528 if (FD) { 6529 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 6530 } 6531 6532 return true; 6533 } 6534 6535 // Returns true if the SourceLocation is expanded from any macro body. 6536 // Returns false if the SourceLocation is invalid, is from not in a macro 6537 // expansion, or is from expanded from a top-level macro argument. 6538 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 6539 if (Loc.isInvalid()) 6540 return false; 6541 6542 while (Loc.isMacroID()) { 6543 if (SM.isMacroBodyExpansion(Loc)) 6544 return true; 6545 Loc = SM.getImmediateMacroCallerLoc(Loc); 6546 } 6547 6548 return false; 6549 } 6550 6551 /// \brief Diagnose pointers that are always non-null. 6552 /// \param E the expression containing the pointer 6553 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 6554 /// compared to a null pointer 6555 /// \param IsEqual True when the comparison is equal to a null pointer 6556 /// \param Range Extra SourceRange to highlight in the diagnostic 6557 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 6558 Expr::NullPointerConstantKind NullKind, 6559 bool IsEqual, SourceRange Range) { 6560 if (!E) 6561 return; 6562 6563 // Don't warn inside macros. 6564 if (E->getExprLoc().isMacroID()) { 6565 const SourceManager &SM = getSourceManager(); 6566 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 6567 IsInAnyMacroBody(SM, Range.getBegin())) 6568 return; 6569 } 6570 E = E->IgnoreImpCasts(); 6571 6572 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 6573 6574 if (isa<CXXThisExpr>(E)) { 6575 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 6576 : diag::warn_this_bool_conversion; 6577 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 6578 return; 6579 } 6580 6581 bool IsAddressOf = false; 6582 6583 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6584 if (UO->getOpcode() != UO_AddrOf) 6585 return; 6586 IsAddressOf = true; 6587 E = UO->getSubExpr(); 6588 } 6589 6590 if (IsAddressOf) { 6591 unsigned DiagID = IsCompare 6592 ? diag::warn_address_of_reference_null_compare 6593 : diag::warn_address_of_reference_bool_conversion; 6594 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 6595 << IsEqual; 6596 if (CheckForReference(*this, E, PD)) { 6597 return; 6598 } 6599 } 6600 6601 // Expect to find a single Decl. Skip anything more complicated. 6602 ValueDecl *D = nullptr; 6603 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 6604 D = R->getDecl(); 6605 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6606 D = M->getMemberDecl(); 6607 } 6608 6609 // Weak Decls can be null. 6610 if (!D || D->isWeak()) 6611 return; 6612 6613 QualType T = D->getType(); 6614 const bool IsArray = T->isArrayType(); 6615 const bool IsFunction = T->isFunctionType(); 6616 6617 // Address of function is used to silence the function warning. 6618 if (IsAddressOf && IsFunction) { 6619 return; 6620 } 6621 6622 // Found nothing. 6623 if (!IsAddressOf && !IsFunction && !IsArray) 6624 return; 6625 6626 // Pretty print the expression for the diagnostic. 6627 std::string Str; 6628 llvm::raw_string_ostream S(Str); 6629 E->printPretty(S, nullptr, getPrintingPolicy()); 6630 6631 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 6632 : diag::warn_impcast_pointer_to_bool; 6633 unsigned DiagType; 6634 if (IsAddressOf) 6635 DiagType = AddressOf; 6636 else if (IsFunction) 6637 DiagType = FunctionPointer; 6638 else if (IsArray) 6639 DiagType = ArrayPointer; 6640 else 6641 llvm_unreachable("Could not determine diagnostic."); 6642 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 6643 << Range << IsEqual; 6644 6645 if (!IsFunction) 6646 return; 6647 6648 // Suggest '&' to silence the function warning. 6649 Diag(E->getExprLoc(), diag::note_function_warning_silence) 6650 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 6651 6652 // Check to see if '()' fixit should be emitted. 6653 QualType ReturnType; 6654 UnresolvedSet<4> NonTemplateOverloads; 6655 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 6656 if (ReturnType.isNull()) 6657 return; 6658 6659 if (IsCompare) { 6660 // There are two cases here. If there is null constant, the only suggest 6661 // for a pointer return type. If the null is 0, then suggest if the return 6662 // type is a pointer or an integer type. 6663 if (!ReturnType->isPointerType()) { 6664 if (NullKind == Expr::NPCK_ZeroExpression || 6665 NullKind == Expr::NPCK_ZeroLiteral) { 6666 if (!ReturnType->isIntegerType()) 6667 return; 6668 } else { 6669 return; 6670 } 6671 } 6672 } else { // !IsCompare 6673 // For function to bool, only suggest if the function pointer has bool 6674 // return type. 6675 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 6676 return; 6677 } 6678 Diag(E->getExprLoc(), diag::note_function_to_function_call) 6679 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 6680 } 6681 6682 6683 /// Diagnoses "dangerous" implicit conversions within the given 6684 /// expression (which is a full expression). Implements -Wconversion 6685 /// and -Wsign-compare. 6686 /// 6687 /// \param CC the "context" location of the implicit conversion, i.e. 6688 /// the most location of the syntactic entity requiring the implicit 6689 /// conversion 6690 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 6691 // Don't diagnose in unevaluated contexts. 6692 if (isUnevaluatedContext()) 6693 return; 6694 6695 // Don't diagnose for value- or type-dependent expressions. 6696 if (E->isTypeDependent() || E->isValueDependent()) 6697 return; 6698 6699 // Check for array bounds violations in cases where the check isn't triggered 6700 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 6701 // ArraySubscriptExpr is on the RHS of a variable initialization. 6702 CheckArrayAccess(E); 6703 6704 // This is not the right CC for (e.g.) a variable initialization. 6705 AnalyzeImplicitConversions(*this, E, CC); 6706 } 6707 6708 /// Diagnose when expression is an integer constant expression and its evaluation 6709 /// results in integer overflow 6710 void Sema::CheckForIntOverflow (Expr *E) { 6711 if (isa<BinaryOperator>(E->IgnoreParens())) 6712 E->EvaluateForOverflow(Context); 6713 } 6714 6715 namespace { 6716 /// \brief Visitor for expressions which looks for unsequenced operations on the 6717 /// same object. 6718 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 6719 typedef EvaluatedExprVisitor<SequenceChecker> Base; 6720 6721 /// \brief A tree of sequenced regions within an expression. Two regions are 6722 /// unsequenced if one is an ancestor or a descendent of the other. When we 6723 /// finish processing an expression with sequencing, such as a comma 6724 /// expression, we fold its tree nodes into its parent, since they are 6725 /// unsequenced with respect to nodes we will visit later. 6726 class SequenceTree { 6727 struct Value { 6728 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 6729 unsigned Parent : 31; 6730 bool Merged : 1; 6731 }; 6732 SmallVector<Value, 8> Values; 6733 6734 public: 6735 /// \brief A region within an expression which may be sequenced with respect 6736 /// to some other region. 6737 class Seq { 6738 explicit Seq(unsigned N) : Index(N) {} 6739 unsigned Index; 6740 friend class SequenceTree; 6741 public: 6742 Seq() : Index(0) {} 6743 }; 6744 6745 SequenceTree() { Values.push_back(Value(0)); } 6746 Seq root() const { return Seq(0); } 6747 6748 /// \brief Create a new sequence of operations, which is an unsequenced 6749 /// subset of \p Parent. This sequence of operations is sequenced with 6750 /// respect to other children of \p Parent. 6751 Seq allocate(Seq Parent) { 6752 Values.push_back(Value(Parent.Index)); 6753 return Seq(Values.size() - 1); 6754 } 6755 6756 /// \brief Merge a sequence of operations into its parent. 6757 void merge(Seq S) { 6758 Values[S.Index].Merged = true; 6759 } 6760 6761 /// \brief Determine whether two operations are unsequenced. This operation 6762 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 6763 /// should have been merged into its parent as appropriate. 6764 bool isUnsequenced(Seq Cur, Seq Old) { 6765 unsigned C = representative(Cur.Index); 6766 unsigned Target = representative(Old.Index); 6767 while (C >= Target) { 6768 if (C == Target) 6769 return true; 6770 C = Values[C].Parent; 6771 } 6772 return false; 6773 } 6774 6775 private: 6776 /// \brief Pick a representative for a sequence. 6777 unsigned representative(unsigned K) { 6778 if (Values[K].Merged) 6779 // Perform path compression as we go. 6780 return Values[K].Parent = representative(Values[K].Parent); 6781 return K; 6782 } 6783 }; 6784 6785 /// An object for which we can track unsequenced uses. 6786 typedef NamedDecl *Object; 6787 6788 /// Different flavors of object usage which we track. We only track the 6789 /// least-sequenced usage of each kind. 6790 enum UsageKind { 6791 /// A read of an object. Multiple unsequenced reads are OK. 6792 UK_Use, 6793 /// A modification of an object which is sequenced before the value 6794 /// computation of the expression, such as ++n in C++. 6795 UK_ModAsValue, 6796 /// A modification of an object which is not sequenced before the value 6797 /// computation of the expression, such as n++. 6798 UK_ModAsSideEffect, 6799 6800 UK_Count = UK_ModAsSideEffect + 1 6801 }; 6802 6803 struct Usage { 6804 Usage() : Use(nullptr), Seq() {} 6805 Expr *Use; 6806 SequenceTree::Seq Seq; 6807 }; 6808 6809 struct UsageInfo { 6810 UsageInfo() : Diagnosed(false) {} 6811 Usage Uses[UK_Count]; 6812 /// Have we issued a diagnostic for this variable already? 6813 bool Diagnosed; 6814 }; 6815 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 6816 6817 Sema &SemaRef; 6818 /// Sequenced regions within the expression. 6819 SequenceTree Tree; 6820 /// Declaration modifications and references which we have seen. 6821 UsageInfoMap UsageMap; 6822 /// The region we are currently within. 6823 SequenceTree::Seq Region; 6824 /// Filled in with declarations which were modified as a side-effect 6825 /// (that is, post-increment operations). 6826 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 6827 /// Expressions to check later. We defer checking these to reduce 6828 /// stack usage. 6829 SmallVectorImpl<Expr *> &WorkList; 6830 6831 /// RAII object wrapping the visitation of a sequenced subexpression of an 6832 /// expression. At the end of this process, the side-effects of the evaluation 6833 /// become sequenced with respect to the value computation of the result, so 6834 /// we downgrade any UK_ModAsSideEffect within the evaluation to 6835 /// UK_ModAsValue. 6836 struct SequencedSubexpression { 6837 SequencedSubexpression(SequenceChecker &Self) 6838 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 6839 Self.ModAsSideEffect = &ModAsSideEffect; 6840 } 6841 ~SequencedSubexpression() { 6842 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) { 6843 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first]; 6844 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second; 6845 Self.addUsage(U, ModAsSideEffect[I].first, 6846 ModAsSideEffect[I].second.Use, UK_ModAsValue); 6847 } 6848 Self.ModAsSideEffect = OldModAsSideEffect; 6849 } 6850 6851 SequenceChecker &Self; 6852 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 6853 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 6854 }; 6855 6856 /// RAII object wrapping the visitation of a subexpression which we might 6857 /// choose to evaluate as a constant. If any subexpression is evaluated and 6858 /// found to be non-constant, this allows us to suppress the evaluation of 6859 /// the outer expression. 6860 class EvaluationTracker { 6861 public: 6862 EvaluationTracker(SequenceChecker &Self) 6863 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 6864 Self.EvalTracker = this; 6865 } 6866 ~EvaluationTracker() { 6867 Self.EvalTracker = Prev; 6868 if (Prev) 6869 Prev->EvalOK &= EvalOK; 6870 } 6871 6872 bool evaluate(const Expr *E, bool &Result) { 6873 if (!EvalOK || E->isValueDependent()) 6874 return false; 6875 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 6876 return EvalOK; 6877 } 6878 6879 private: 6880 SequenceChecker &Self; 6881 EvaluationTracker *Prev; 6882 bool EvalOK; 6883 } *EvalTracker; 6884 6885 /// \brief Find the object which is produced by the specified expression, 6886 /// if any. 6887 Object getObject(Expr *E, bool Mod) const { 6888 E = E->IgnoreParenCasts(); 6889 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6890 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 6891 return getObject(UO->getSubExpr(), Mod); 6892 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6893 if (BO->getOpcode() == BO_Comma) 6894 return getObject(BO->getRHS(), Mod); 6895 if (Mod && BO->isAssignmentOp()) 6896 return getObject(BO->getLHS(), Mod); 6897 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 6898 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 6899 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 6900 return ME->getMemberDecl(); 6901 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6902 // FIXME: If this is a reference, map through to its value. 6903 return DRE->getDecl(); 6904 return nullptr; 6905 } 6906 6907 /// \brief Note that an object was modified or used by an expression. 6908 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 6909 Usage &U = UI.Uses[UK]; 6910 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 6911 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 6912 ModAsSideEffect->push_back(std::make_pair(O, U)); 6913 U.Use = Ref; 6914 U.Seq = Region; 6915 } 6916 } 6917 /// \brief Check whether a modification or use conflicts with a prior usage. 6918 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 6919 bool IsModMod) { 6920 if (UI.Diagnosed) 6921 return; 6922 6923 const Usage &U = UI.Uses[OtherKind]; 6924 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 6925 return; 6926 6927 Expr *Mod = U.Use; 6928 Expr *ModOrUse = Ref; 6929 if (OtherKind == UK_Use) 6930 std::swap(Mod, ModOrUse); 6931 6932 SemaRef.Diag(Mod->getExprLoc(), 6933 IsModMod ? diag::warn_unsequenced_mod_mod 6934 : diag::warn_unsequenced_mod_use) 6935 << O << SourceRange(ModOrUse->getExprLoc()); 6936 UI.Diagnosed = true; 6937 } 6938 6939 void notePreUse(Object O, Expr *Use) { 6940 UsageInfo &U = UsageMap[O]; 6941 // Uses conflict with other modifications. 6942 checkUsage(O, U, Use, UK_ModAsValue, false); 6943 } 6944 void notePostUse(Object O, Expr *Use) { 6945 UsageInfo &U = UsageMap[O]; 6946 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 6947 addUsage(U, O, Use, UK_Use); 6948 } 6949 6950 void notePreMod(Object O, Expr *Mod) { 6951 UsageInfo &U = UsageMap[O]; 6952 // Modifications conflict with other modifications and with uses. 6953 checkUsage(O, U, Mod, UK_ModAsValue, true); 6954 checkUsage(O, U, Mod, UK_Use, false); 6955 } 6956 void notePostMod(Object O, Expr *Use, UsageKind UK) { 6957 UsageInfo &U = UsageMap[O]; 6958 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 6959 addUsage(U, O, Use, UK); 6960 } 6961 6962 public: 6963 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 6964 : Base(S.Context), SemaRef(S), Region(Tree.root()), 6965 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 6966 Visit(E); 6967 } 6968 6969 void VisitStmt(Stmt *S) { 6970 // Skip all statements which aren't expressions for now. 6971 } 6972 6973 void VisitExpr(Expr *E) { 6974 // By default, just recurse to evaluated subexpressions. 6975 Base::VisitStmt(E); 6976 } 6977 6978 void VisitCastExpr(CastExpr *E) { 6979 Object O = Object(); 6980 if (E->getCastKind() == CK_LValueToRValue) 6981 O = getObject(E->getSubExpr(), false); 6982 6983 if (O) 6984 notePreUse(O, E); 6985 VisitExpr(E); 6986 if (O) 6987 notePostUse(O, E); 6988 } 6989 6990 void VisitBinComma(BinaryOperator *BO) { 6991 // C++11 [expr.comma]p1: 6992 // Every value computation and side effect associated with the left 6993 // expression is sequenced before every value computation and side 6994 // effect associated with the right expression. 6995 SequenceTree::Seq LHS = Tree.allocate(Region); 6996 SequenceTree::Seq RHS = Tree.allocate(Region); 6997 SequenceTree::Seq OldRegion = Region; 6998 6999 { 7000 SequencedSubexpression SeqLHS(*this); 7001 Region = LHS; 7002 Visit(BO->getLHS()); 7003 } 7004 7005 Region = RHS; 7006 Visit(BO->getRHS()); 7007 7008 Region = OldRegion; 7009 7010 // Forget that LHS and RHS are sequenced. They are both unsequenced 7011 // with respect to other stuff. 7012 Tree.merge(LHS); 7013 Tree.merge(RHS); 7014 } 7015 7016 void VisitBinAssign(BinaryOperator *BO) { 7017 // The modification is sequenced after the value computation of the LHS 7018 // and RHS, so check it before inspecting the operands and update the 7019 // map afterwards. 7020 Object O = getObject(BO->getLHS(), true); 7021 if (!O) 7022 return VisitExpr(BO); 7023 7024 notePreMod(O, BO); 7025 7026 // C++11 [expr.ass]p7: 7027 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 7028 // only once. 7029 // 7030 // Therefore, for a compound assignment operator, O is considered used 7031 // everywhere except within the evaluation of E1 itself. 7032 if (isa<CompoundAssignOperator>(BO)) 7033 notePreUse(O, BO); 7034 7035 Visit(BO->getLHS()); 7036 7037 if (isa<CompoundAssignOperator>(BO)) 7038 notePostUse(O, BO); 7039 7040 Visit(BO->getRHS()); 7041 7042 // C++11 [expr.ass]p1: 7043 // the assignment is sequenced [...] before the value computation of the 7044 // assignment expression. 7045 // C11 6.5.16/3 has no such rule. 7046 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 7047 : UK_ModAsSideEffect); 7048 } 7049 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 7050 VisitBinAssign(CAO); 7051 } 7052 7053 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 7054 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 7055 void VisitUnaryPreIncDec(UnaryOperator *UO) { 7056 Object O = getObject(UO->getSubExpr(), true); 7057 if (!O) 7058 return VisitExpr(UO); 7059 7060 notePreMod(O, UO); 7061 Visit(UO->getSubExpr()); 7062 // C++11 [expr.pre.incr]p1: 7063 // the expression ++x is equivalent to x+=1 7064 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 7065 : UK_ModAsSideEffect); 7066 } 7067 7068 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 7069 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 7070 void VisitUnaryPostIncDec(UnaryOperator *UO) { 7071 Object O = getObject(UO->getSubExpr(), true); 7072 if (!O) 7073 return VisitExpr(UO); 7074 7075 notePreMod(O, UO); 7076 Visit(UO->getSubExpr()); 7077 notePostMod(O, UO, UK_ModAsSideEffect); 7078 } 7079 7080 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 7081 void VisitBinLOr(BinaryOperator *BO) { 7082 // The side-effects of the LHS of an '&&' are sequenced before the 7083 // value computation of the RHS, and hence before the value computation 7084 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 7085 // as if they were unconditionally sequenced. 7086 EvaluationTracker Eval(*this); 7087 { 7088 SequencedSubexpression Sequenced(*this); 7089 Visit(BO->getLHS()); 7090 } 7091 7092 bool Result; 7093 if (Eval.evaluate(BO->getLHS(), Result)) { 7094 if (!Result) 7095 Visit(BO->getRHS()); 7096 } else { 7097 // Check for unsequenced operations in the RHS, treating it as an 7098 // entirely separate evaluation. 7099 // 7100 // FIXME: If there are operations in the RHS which are unsequenced 7101 // with respect to operations outside the RHS, and those operations 7102 // are unconditionally evaluated, diagnose them. 7103 WorkList.push_back(BO->getRHS()); 7104 } 7105 } 7106 void VisitBinLAnd(BinaryOperator *BO) { 7107 EvaluationTracker Eval(*this); 7108 { 7109 SequencedSubexpression Sequenced(*this); 7110 Visit(BO->getLHS()); 7111 } 7112 7113 bool Result; 7114 if (Eval.evaluate(BO->getLHS(), Result)) { 7115 if (Result) 7116 Visit(BO->getRHS()); 7117 } else { 7118 WorkList.push_back(BO->getRHS()); 7119 } 7120 } 7121 7122 // Only visit the condition, unless we can be sure which subexpression will 7123 // be chosen. 7124 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 7125 EvaluationTracker Eval(*this); 7126 { 7127 SequencedSubexpression Sequenced(*this); 7128 Visit(CO->getCond()); 7129 } 7130 7131 bool Result; 7132 if (Eval.evaluate(CO->getCond(), Result)) 7133 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 7134 else { 7135 WorkList.push_back(CO->getTrueExpr()); 7136 WorkList.push_back(CO->getFalseExpr()); 7137 } 7138 } 7139 7140 void VisitCallExpr(CallExpr *CE) { 7141 // C++11 [intro.execution]p15: 7142 // When calling a function [...], every value computation and side effect 7143 // associated with any argument expression, or with the postfix expression 7144 // designating the called function, is sequenced before execution of every 7145 // expression or statement in the body of the function [and thus before 7146 // the value computation of its result]. 7147 SequencedSubexpression Sequenced(*this); 7148 Base::VisitCallExpr(CE); 7149 7150 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 7151 } 7152 7153 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 7154 // This is a call, so all subexpressions are sequenced before the result. 7155 SequencedSubexpression Sequenced(*this); 7156 7157 if (!CCE->isListInitialization()) 7158 return VisitExpr(CCE); 7159 7160 // In C++11, list initializations are sequenced. 7161 SmallVector<SequenceTree::Seq, 32> Elts; 7162 SequenceTree::Seq Parent = Region; 7163 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 7164 E = CCE->arg_end(); 7165 I != E; ++I) { 7166 Region = Tree.allocate(Parent); 7167 Elts.push_back(Region); 7168 Visit(*I); 7169 } 7170 7171 // Forget that the initializers are sequenced. 7172 Region = Parent; 7173 for (unsigned I = 0; I < Elts.size(); ++I) 7174 Tree.merge(Elts[I]); 7175 } 7176 7177 void VisitInitListExpr(InitListExpr *ILE) { 7178 if (!SemaRef.getLangOpts().CPlusPlus11) 7179 return VisitExpr(ILE); 7180 7181 // In C++11, list initializations are sequenced. 7182 SmallVector<SequenceTree::Seq, 32> Elts; 7183 SequenceTree::Seq Parent = Region; 7184 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 7185 Expr *E = ILE->getInit(I); 7186 if (!E) continue; 7187 Region = Tree.allocate(Parent); 7188 Elts.push_back(Region); 7189 Visit(E); 7190 } 7191 7192 // Forget that the initializers are sequenced. 7193 Region = Parent; 7194 for (unsigned I = 0; I < Elts.size(); ++I) 7195 Tree.merge(Elts[I]); 7196 } 7197 }; 7198 } 7199 7200 void Sema::CheckUnsequencedOperations(Expr *E) { 7201 SmallVector<Expr *, 8> WorkList; 7202 WorkList.push_back(E); 7203 while (!WorkList.empty()) { 7204 Expr *Item = WorkList.pop_back_val(); 7205 SequenceChecker(*this, Item, WorkList); 7206 } 7207 } 7208 7209 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 7210 bool IsConstexpr) { 7211 CheckImplicitConversions(E, CheckLoc); 7212 CheckUnsequencedOperations(E); 7213 if (!IsConstexpr && !E->isValueDependent()) 7214 CheckForIntOverflow(E); 7215 } 7216 7217 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 7218 FieldDecl *BitField, 7219 Expr *Init) { 7220 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 7221 } 7222 7223 /// CheckParmsForFunctionDef - Check that the parameters of the given 7224 /// function are appropriate for the definition of a function. This 7225 /// takes care of any checks that cannot be performed on the 7226 /// declaration itself, e.g., that the types of each of the function 7227 /// parameters are complete. 7228 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 7229 ParmVarDecl *const *PEnd, 7230 bool CheckParameterNames) { 7231 bool HasInvalidParm = false; 7232 for (; P != PEnd; ++P) { 7233 ParmVarDecl *Param = *P; 7234 7235 // C99 6.7.5.3p4: the parameters in a parameter type list in a 7236 // function declarator that is part of a function definition of 7237 // that function shall not have incomplete type. 7238 // 7239 // This is also C++ [dcl.fct]p6. 7240 if (!Param->isInvalidDecl() && 7241 RequireCompleteType(Param->getLocation(), Param->getType(), 7242 diag::err_typecheck_decl_incomplete_type)) { 7243 Param->setInvalidDecl(); 7244 HasInvalidParm = true; 7245 } 7246 7247 // C99 6.9.1p5: If the declarator includes a parameter type list, the 7248 // declaration of each parameter shall include an identifier. 7249 if (CheckParameterNames && 7250 Param->getIdentifier() == nullptr && 7251 !Param->isImplicit() && 7252 !getLangOpts().CPlusPlus) 7253 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 7254 7255 // C99 6.7.5.3p12: 7256 // If the function declarator is not part of a definition of that 7257 // function, parameters may have incomplete type and may use the [*] 7258 // notation in their sequences of declarator specifiers to specify 7259 // variable length array types. 7260 QualType PType = Param->getOriginalType(); 7261 while (const ArrayType *AT = Context.getAsArrayType(PType)) { 7262 if (AT->getSizeModifier() == ArrayType::Star) { 7263 // FIXME: This diagnostic should point the '[*]' if source-location 7264 // information is added for it. 7265 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 7266 break; 7267 } 7268 PType= AT->getElementType(); 7269 } 7270 7271 // MSVC destroys objects passed by value in the callee. Therefore a 7272 // function definition which takes such a parameter must be able to call the 7273 // object's destructor. However, we don't perform any direct access check 7274 // on the dtor. 7275 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 7276 .getCXXABI() 7277 .areArgsDestroyedLeftToRightInCallee()) { 7278 if (!Param->isInvalidDecl()) { 7279 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 7280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 7281 if (!ClassDecl->isInvalidDecl() && 7282 !ClassDecl->hasIrrelevantDestructor() && 7283 !ClassDecl->isDependentContext()) { 7284 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 7285 MarkFunctionReferenced(Param->getLocation(), Destructor); 7286 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 7287 } 7288 } 7289 } 7290 } 7291 } 7292 7293 return HasInvalidParm; 7294 } 7295 7296 /// CheckCastAlign - Implements -Wcast-align, which warns when a 7297 /// pointer cast increases the alignment requirements. 7298 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 7299 // This is actually a lot of work to potentially be doing on every 7300 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 7301 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 7302 return; 7303 7304 // Ignore dependent types. 7305 if (T->isDependentType() || Op->getType()->isDependentType()) 7306 return; 7307 7308 // Require that the destination be a pointer type. 7309 const PointerType *DestPtr = T->getAs<PointerType>(); 7310 if (!DestPtr) return; 7311 7312 // If the destination has alignment 1, we're done. 7313 QualType DestPointee = DestPtr->getPointeeType(); 7314 if (DestPointee->isIncompleteType()) return; 7315 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 7316 if (DestAlign.isOne()) return; 7317 7318 // Require that the source be a pointer type. 7319 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 7320 if (!SrcPtr) return; 7321 QualType SrcPointee = SrcPtr->getPointeeType(); 7322 7323 // Whitelist casts from cv void*. We already implicitly 7324 // whitelisted casts to cv void*, since they have alignment 1. 7325 // Also whitelist casts involving incomplete types, which implicitly 7326 // includes 'void'. 7327 if (SrcPointee->isIncompleteType()) return; 7328 7329 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 7330 if (SrcAlign >= DestAlign) return; 7331 7332 Diag(TRange.getBegin(), diag::warn_cast_align) 7333 << Op->getType() << T 7334 << static_cast<unsigned>(SrcAlign.getQuantity()) 7335 << static_cast<unsigned>(DestAlign.getQuantity()) 7336 << TRange << Op->getSourceRange(); 7337 } 7338 7339 static const Type* getElementType(const Expr *BaseExpr) { 7340 const Type* EltType = BaseExpr->getType().getTypePtr(); 7341 if (EltType->isAnyPointerType()) 7342 return EltType->getPointeeType().getTypePtr(); 7343 else if (EltType->isArrayType()) 7344 return EltType->getBaseElementTypeUnsafe(); 7345 return EltType; 7346 } 7347 7348 /// \brief Check whether this array fits the idiom of a size-one tail padded 7349 /// array member of a struct. 7350 /// 7351 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 7352 /// commonly used to emulate flexible arrays in C89 code. 7353 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 7354 const NamedDecl *ND) { 7355 if (Size != 1 || !ND) return false; 7356 7357 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 7358 if (!FD) return false; 7359 7360 // Don't consider sizes resulting from macro expansions or template argument 7361 // substitution to form C89 tail-padded arrays. 7362 7363 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 7364 while (TInfo) { 7365 TypeLoc TL = TInfo->getTypeLoc(); 7366 // Look through typedefs. 7367 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 7368 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 7369 TInfo = TDL->getTypeSourceInfo(); 7370 continue; 7371 } 7372 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 7373 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 7374 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 7375 return false; 7376 } 7377 break; 7378 } 7379 7380 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 7381 if (!RD) return false; 7382 if (RD->isUnion()) return false; 7383 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 7384 if (!CRD->isStandardLayout()) return false; 7385 } 7386 7387 // See if this is the last field decl in the record. 7388 const Decl *D = FD; 7389 while ((D = D->getNextDeclInContext())) 7390 if (isa<FieldDecl>(D)) 7391 return false; 7392 return true; 7393 } 7394 7395 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7396 const ArraySubscriptExpr *ASE, 7397 bool AllowOnePastEnd, bool IndexNegated) { 7398 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 7399 if (IndexExpr->isValueDependent()) 7400 return; 7401 7402 const Type *EffectiveType = getElementType(BaseExpr); 7403 BaseExpr = BaseExpr->IgnoreParenCasts(); 7404 const ConstantArrayType *ArrayTy = 7405 Context.getAsConstantArrayType(BaseExpr->getType()); 7406 if (!ArrayTy) 7407 return; 7408 7409 llvm::APSInt index; 7410 if (!IndexExpr->EvaluateAsInt(index, Context)) 7411 return; 7412 if (IndexNegated) 7413 index = -index; 7414 7415 const NamedDecl *ND = nullptr; 7416 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7417 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7418 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7419 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7420 7421 if (index.isUnsigned() || !index.isNegative()) { 7422 llvm::APInt size = ArrayTy->getSize(); 7423 if (!size.isStrictlyPositive()) 7424 return; 7425 7426 const Type* BaseType = getElementType(BaseExpr); 7427 if (BaseType != EffectiveType) { 7428 // Make sure we're comparing apples to apples when comparing index to size 7429 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 7430 uint64_t array_typesize = Context.getTypeSize(BaseType); 7431 // Handle ptrarith_typesize being zero, such as when casting to void* 7432 if (!ptrarith_typesize) ptrarith_typesize = 1; 7433 if (ptrarith_typesize != array_typesize) { 7434 // There's a cast to a different size type involved 7435 uint64_t ratio = array_typesize / ptrarith_typesize; 7436 // TODO: Be smarter about handling cases where array_typesize is not a 7437 // multiple of ptrarith_typesize 7438 if (ptrarith_typesize * ratio == array_typesize) 7439 size *= llvm::APInt(size.getBitWidth(), ratio); 7440 } 7441 } 7442 7443 if (size.getBitWidth() > index.getBitWidth()) 7444 index = index.zext(size.getBitWidth()); 7445 else if (size.getBitWidth() < index.getBitWidth()) 7446 size = size.zext(index.getBitWidth()); 7447 7448 // For array subscripting the index must be less than size, but for pointer 7449 // arithmetic also allow the index (offset) to be equal to size since 7450 // computing the next address after the end of the array is legal and 7451 // commonly done e.g. in C++ iterators and range-based for loops. 7452 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 7453 return; 7454 7455 // Also don't warn for arrays of size 1 which are members of some 7456 // structure. These are often used to approximate flexible arrays in C89 7457 // code. 7458 if (IsTailPaddedMemberArray(*this, size, ND)) 7459 return; 7460 7461 // Suppress the warning if the subscript expression (as identified by the 7462 // ']' location) and the index expression are both from macro expansions 7463 // within a system header. 7464 if (ASE) { 7465 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 7466 ASE->getRBracketLoc()); 7467 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 7468 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 7469 IndexExpr->getLocStart()); 7470 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 7471 return; 7472 } 7473 } 7474 7475 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 7476 if (ASE) 7477 DiagID = diag::warn_array_index_exceeds_bounds; 7478 7479 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7480 PDiag(DiagID) << index.toString(10, true) 7481 << size.toString(10, true) 7482 << (unsigned)size.getLimitedValue(~0U) 7483 << IndexExpr->getSourceRange()); 7484 } else { 7485 unsigned DiagID = diag::warn_array_index_precedes_bounds; 7486 if (!ASE) { 7487 DiagID = diag::warn_ptr_arith_precedes_bounds; 7488 if (index.isNegative()) index = -index; 7489 } 7490 7491 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7492 PDiag(DiagID) << index.toString(10, true) 7493 << IndexExpr->getSourceRange()); 7494 } 7495 7496 if (!ND) { 7497 // Try harder to find a NamedDecl to point at in the note. 7498 while (const ArraySubscriptExpr *ASE = 7499 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 7500 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 7501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7502 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7504 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7505 } 7506 7507 if (ND) 7508 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 7509 PDiag(diag::note_array_index_out_of_bounds) 7510 << ND->getDeclName()); 7511 } 7512 7513 void Sema::CheckArrayAccess(const Expr *expr) { 7514 int AllowOnePastEnd = 0; 7515 while (expr) { 7516 expr = expr->IgnoreParenImpCasts(); 7517 switch (expr->getStmtClass()) { 7518 case Stmt::ArraySubscriptExprClass: { 7519 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 7520 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 7521 AllowOnePastEnd > 0); 7522 return; 7523 } 7524 case Stmt::UnaryOperatorClass: { 7525 // Only unwrap the * and & unary operators 7526 const UnaryOperator *UO = cast<UnaryOperator>(expr); 7527 expr = UO->getSubExpr(); 7528 switch (UO->getOpcode()) { 7529 case UO_AddrOf: 7530 AllowOnePastEnd++; 7531 break; 7532 case UO_Deref: 7533 AllowOnePastEnd--; 7534 break; 7535 default: 7536 return; 7537 } 7538 break; 7539 } 7540 case Stmt::ConditionalOperatorClass: { 7541 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 7542 if (const Expr *lhs = cond->getLHS()) 7543 CheckArrayAccess(lhs); 7544 if (const Expr *rhs = cond->getRHS()) 7545 CheckArrayAccess(rhs); 7546 return; 7547 } 7548 default: 7549 return; 7550 } 7551 } 7552 } 7553 7554 //===--- CHECK: Objective-C retain cycles ----------------------------------// 7555 7556 namespace { 7557 struct RetainCycleOwner { 7558 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 7559 VarDecl *Variable; 7560 SourceRange Range; 7561 SourceLocation Loc; 7562 bool Indirect; 7563 7564 void setLocsFrom(Expr *e) { 7565 Loc = e->getExprLoc(); 7566 Range = e->getSourceRange(); 7567 } 7568 }; 7569 } 7570 7571 /// Consider whether capturing the given variable can possibly lead to 7572 /// a retain cycle. 7573 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 7574 // In ARC, it's captured strongly iff the variable has __strong 7575 // lifetime. In MRR, it's captured strongly if the variable is 7576 // __block and has an appropriate type. 7577 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 7578 return false; 7579 7580 owner.Variable = var; 7581 if (ref) 7582 owner.setLocsFrom(ref); 7583 return true; 7584 } 7585 7586 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 7587 while (true) { 7588 e = e->IgnoreParens(); 7589 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 7590 switch (cast->getCastKind()) { 7591 case CK_BitCast: 7592 case CK_LValueBitCast: 7593 case CK_LValueToRValue: 7594 case CK_ARCReclaimReturnedObject: 7595 e = cast->getSubExpr(); 7596 continue; 7597 7598 default: 7599 return false; 7600 } 7601 } 7602 7603 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 7604 ObjCIvarDecl *ivar = ref->getDecl(); 7605 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 7606 return false; 7607 7608 // Try to find a retain cycle in the base. 7609 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 7610 return false; 7611 7612 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 7613 owner.Indirect = true; 7614 return true; 7615 } 7616 7617 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 7618 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 7619 if (!var) return false; 7620 return considerVariable(var, ref, owner); 7621 } 7622 7623 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 7624 if (member->isArrow()) return false; 7625 7626 // Don't count this as an indirect ownership. 7627 e = member->getBase(); 7628 continue; 7629 } 7630 7631 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 7632 // Only pay attention to pseudo-objects on property references. 7633 ObjCPropertyRefExpr *pre 7634 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 7635 ->IgnoreParens()); 7636 if (!pre) return false; 7637 if (pre->isImplicitProperty()) return false; 7638 ObjCPropertyDecl *property = pre->getExplicitProperty(); 7639 if (!property->isRetaining() && 7640 !(property->getPropertyIvarDecl() && 7641 property->getPropertyIvarDecl()->getType() 7642 .getObjCLifetime() == Qualifiers::OCL_Strong)) 7643 return false; 7644 7645 owner.Indirect = true; 7646 if (pre->isSuperReceiver()) { 7647 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 7648 if (!owner.Variable) 7649 return false; 7650 owner.Loc = pre->getLocation(); 7651 owner.Range = pre->getSourceRange(); 7652 return true; 7653 } 7654 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 7655 ->getSourceExpr()); 7656 continue; 7657 } 7658 7659 // Array ivars? 7660 7661 return false; 7662 } 7663 } 7664 7665 namespace { 7666 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 7667 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 7668 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 7669 Context(Context), Variable(variable), Capturer(nullptr), 7670 VarWillBeReased(false) {} 7671 ASTContext &Context; 7672 VarDecl *Variable; 7673 Expr *Capturer; 7674 bool VarWillBeReased; 7675 7676 void VisitDeclRefExpr(DeclRefExpr *ref) { 7677 if (ref->getDecl() == Variable && !Capturer) 7678 Capturer = ref; 7679 } 7680 7681 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 7682 if (Capturer) return; 7683 Visit(ref->getBase()); 7684 if (Capturer && ref->isFreeIvar()) 7685 Capturer = ref; 7686 } 7687 7688 void VisitBlockExpr(BlockExpr *block) { 7689 // Look inside nested blocks 7690 if (block->getBlockDecl()->capturesVariable(Variable)) 7691 Visit(block->getBlockDecl()->getBody()); 7692 } 7693 7694 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 7695 if (Capturer) return; 7696 if (OVE->getSourceExpr()) 7697 Visit(OVE->getSourceExpr()); 7698 } 7699 void VisitBinaryOperator(BinaryOperator *BinOp) { 7700 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 7701 return; 7702 Expr *LHS = BinOp->getLHS(); 7703 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 7704 if (DRE->getDecl() != Variable) 7705 return; 7706 if (Expr *RHS = BinOp->getRHS()) { 7707 RHS = RHS->IgnoreParenCasts(); 7708 llvm::APSInt Value; 7709 VarWillBeReased = 7710 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 7711 } 7712 } 7713 } 7714 }; 7715 } 7716 7717 /// Check whether the given argument is a block which captures a 7718 /// variable. 7719 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 7720 assert(owner.Variable && owner.Loc.isValid()); 7721 7722 e = e->IgnoreParenCasts(); 7723 7724 // Look through [^{...} copy] and Block_copy(^{...}). 7725 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 7726 Selector Cmd = ME->getSelector(); 7727 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 7728 e = ME->getInstanceReceiver(); 7729 if (!e) 7730 return nullptr; 7731 e = e->IgnoreParenCasts(); 7732 } 7733 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 7734 if (CE->getNumArgs() == 1) { 7735 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 7736 if (Fn) { 7737 const IdentifierInfo *FnI = Fn->getIdentifier(); 7738 if (FnI && FnI->isStr("_Block_copy")) { 7739 e = CE->getArg(0)->IgnoreParenCasts(); 7740 } 7741 } 7742 } 7743 } 7744 7745 BlockExpr *block = dyn_cast<BlockExpr>(e); 7746 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 7747 return nullptr; 7748 7749 FindCaptureVisitor visitor(S.Context, owner.Variable); 7750 visitor.Visit(block->getBlockDecl()->getBody()); 7751 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 7752 } 7753 7754 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 7755 RetainCycleOwner &owner) { 7756 assert(capturer); 7757 assert(owner.Variable && owner.Loc.isValid()); 7758 7759 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 7760 << owner.Variable << capturer->getSourceRange(); 7761 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 7762 << owner.Indirect << owner.Range; 7763 } 7764 7765 /// Check for a keyword selector that starts with the word 'add' or 7766 /// 'set'. 7767 static bool isSetterLikeSelector(Selector sel) { 7768 if (sel.isUnarySelector()) return false; 7769 7770 StringRef str = sel.getNameForSlot(0); 7771 while (!str.empty() && str.front() == '_') str = str.substr(1); 7772 if (str.startswith("set")) 7773 str = str.substr(3); 7774 else if (str.startswith("add")) { 7775 // Specially whitelist 'addOperationWithBlock:'. 7776 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 7777 return false; 7778 str = str.substr(3); 7779 } 7780 else 7781 return false; 7782 7783 if (str.empty()) return true; 7784 return !isLowercase(str.front()); 7785 } 7786 7787 /// Check a message send to see if it's likely to cause a retain cycle. 7788 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 7789 // Only check instance methods whose selector looks like a setter. 7790 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 7791 return; 7792 7793 // Try to find a variable that the receiver is strongly owned by. 7794 RetainCycleOwner owner; 7795 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 7796 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 7797 return; 7798 } else { 7799 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 7800 owner.Variable = getCurMethodDecl()->getSelfDecl(); 7801 owner.Loc = msg->getSuperLoc(); 7802 owner.Range = msg->getSuperLoc(); 7803 } 7804 7805 // Check whether the receiver is captured by any of the arguments. 7806 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 7807 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 7808 return diagnoseRetainCycle(*this, capturer, owner); 7809 } 7810 7811 /// Check a property assign to see if it's likely to cause a retain cycle. 7812 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 7813 RetainCycleOwner owner; 7814 if (!findRetainCycleOwner(*this, receiver, owner)) 7815 return; 7816 7817 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 7818 diagnoseRetainCycle(*this, capturer, owner); 7819 } 7820 7821 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 7822 RetainCycleOwner Owner; 7823 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 7824 return; 7825 7826 // Because we don't have an expression for the variable, we have to set the 7827 // location explicitly here. 7828 Owner.Loc = Var->getLocation(); 7829 Owner.Range = Var->getSourceRange(); 7830 7831 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 7832 diagnoseRetainCycle(*this, Capturer, Owner); 7833 } 7834 7835 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 7836 Expr *RHS, bool isProperty) { 7837 // Check if RHS is an Objective-C object literal, which also can get 7838 // immediately zapped in a weak reference. Note that we explicitly 7839 // allow ObjCStringLiterals, since those are designed to never really die. 7840 RHS = RHS->IgnoreParenImpCasts(); 7841 7842 // This enum needs to match with the 'select' in 7843 // warn_objc_arc_literal_assign (off-by-1). 7844 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 7845 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 7846 return false; 7847 7848 S.Diag(Loc, diag::warn_arc_literal_assign) 7849 << (unsigned) Kind 7850 << (isProperty ? 0 : 1) 7851 << RHS->getSourceRange(); 7852 7853 return true; 7854 } 7855 7856 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 7857 Qualifiers::ObjCLifetime LT, 7858 Expr *RHS, bool isProperty) { 7859 // Strip off any implicit cast added to get to the one ARC-specific. 7860 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 7861 if (cast->getCastKind() == CK_ARCConsumeObject) { 7862 S.Diag(Loc, diag::warn_arc_retained_assign) 7863 << (LT == Qualifiers::OCL_ExplicitNone) 7864 << (isProperty ? 0 : 1) 7865 << RHS->getSourceRange(); 7866 return true; 7867 } 7868 RHS = cast->getSubExpr(); 7869 } 7870 7871 if (LT == Qualifiers::OCL_Weak && 7872 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 7873 return true; 7874 7875 return false; 7876 } 7877 7878 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 7879 QualType LHS, Expr *RHS) { 7880 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 7881 7882 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 7883 return false; 7884 7885 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 7886 return true; 7887 7888 return false; 7889 } 7890 7891 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 7892 Expr *LHS, Expr *RHS) { 7893 QualType LHSType; 7894 // PropertyRef on LHS type need be directly obtained from 7895 // its declaration as it has a PseudoType. 7896 ObjCPropertyRefExpr *PRE 7897 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 7898 if (PRE && !PRE->isImplicitProperty()) { 7899 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 7900 if (PD) 7901 LHSType = PD->getType(); 7902 } 7903 7904 if (LHSType.isNull()) 7905 LHSType = LHS->getType(); 7906 7907 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 7908 7909 if (LT == Qualifiers::OCL_Weak) { 7910 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 7911 getCurFunction()->markSafeWeakUse(LHS); 7912 } 7913 7914 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 7915 return; 7916 7917 // FIXME. Check for other life times. 7918 if (LT != Qualifiers::OCL_None) 7919 return; 7920 7921 if (PRE) { 7922 if (PRE->isImplicitProperty()) 7923 return; 7924 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 7925 if (!PD) 7926 return; 7927 7928 unsigned Attributes = PD->getPropertyAttributes(); 7929 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 7930 // when 'assign' attribute was not explicitly specified 7931 // by user, ignore it and rely on property type itself 7932 // for lifetime info. 7933 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 7934 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 7935 LHSType->isObjCRetainableType()) 7936 return; 7937 7938 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 7939 if (cast->getCastKind() == CK_ARCConsumeObject) { 7940 Diag(Loc, diag::warn_arc_retained_property_assign) 7941 << RHS->getSourceRange(); 7942 return; 7943 } 7944 RHS = cast->getSubExpr(); 7945 } 7946 } 7947 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 7948 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 7949 return; 7950 } 7951 } 7952 } 7953 7954 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 7955 7956 namespace { 7957 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 7958 SourceLocation StmtLoc, 7959 const NullStmt *Body) { 7960 // Do not warn if the body is a macro that expands to nothing, e.g: 7961 // 7962 // #define CALL(x) 7963 // if (condition) 7964 // CALL(0); 7965 // 7966 if (Body->hasLeadingEmptyMacro()) 7967 return false; 7968 7969 // Get line numbers of statement and body. 7970 bool StmtLineInvalid; 7971 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 7972 &StmtLineInvalid); 7973 if (StmtLineInvalid) 7974 return false; 7975 7976 bool BodyLineInvalid; 7977 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 7978 &BodyLineInvalid); 7979 if (BodyLineInvalid) 7980 return false; 7981 7982 // Warn if null statement and body are on the same line. 7983 if (StmtLine != BodyLine) 7984 return false; 7985 7986 return true; 7987 } 7988 } // Unnamed namespace 7989 7990 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 7991 const Stmt *Body, 7992 unsigned DiagID) { 7993 // Since this is a syntactic check, don't emit diagnostic for template 7994 // instantiations, this just adds noise. 7995 if (CurrentInstantiationScope) 7996 return; 7997 7998 // The body should be a null statement. 7999 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 8000 if (!NBody) 8001 return; 8002 8003 // Do the usual checks. 8004 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 8005 return; 8006 8007 Diag(NBody->getSemiLoc(), DiagID); 8008 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 8009 } 8010 8011 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 8012 const Stmt *PossibleBody) { 8013 assert(!CurrentInstantiationScope); // Ensured by caller 8014 8015 SourceLocation StmtLoc; 8016 const Stmt *Body; 8017 unsigned DiagID; 8018 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 8019 StmtLoc = FS->getRParenLoc(); 8020 Body = FS->getBody(); 8021 DiagID = diag::warn_empty_for_body; 8022 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 8023 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 8024 Body = WS->getBody(); 8025 DiagID = diag::warn_empty_while_body; 8026 } else 8027 return; // Neither `for' nor `while'. 8028 8029 // The body should be a null statement. 8030 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 8031 if (!NBody) 8032 return; 8033 8034 // Skip expensive checks if diagnostic is disabled. 8035 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 8036 return; 8037 8038 // Do the usual checks. 8039 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 8040 return; 8041 8042 // `for(...);' and `while(...);' are popular idioms, so in order to keep 8043 // noise level low, emit diagnostics only if for/while is followed by a 8044 // CompoundStmt, e.g.: 8045 // for (int i = 0; i < n; i++); 8046 // { 8047 // a(i); 8048 // } 8049 // or if for/while is followed by a statement with more indentation 8050 // than for/while itself: 8051 // for (int i = 0; i < n; i++); 8052 // a(i); 8053 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 8054 if (!ProbableTypo) { 8055 bool BodyColInvalid; 8056 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 8057 PossibleBody->getLocStart(), 8058 &BodyColInvalid); 8059 if (BodyColInvalid) 8060 return; 8061 8062 bool StmtColInvalid; 8063 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 8064 S->getLocStart(), 8065 &StmtColInvalid); 8066 if (StmtColInvalid) 8067 return; 8068 8069 if (BodyCol > StmtCol) 8070 ProbableTypo = true; 8071 } 8072 8073 if (ProbableTypo) { 8074 Diag(NBody->getSemiLoc(), DiagID); 8075 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 8076 } 8077 } 8078 8079 //===--- Layout compatibility ----------------------------------------------// 8080 8081 namespace { 8082 8083 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 8084 8085 /// \brief Check if two enumeration types are layout-compatible. 8086 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 8087 // C++11 [dcl.enum] p8: 8088 // Two enumeration types are layout-compatible if they have the same 8089 // underlying type. 8090 return ED1->isComplete() && ED2->isComplete() && 8091 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 8092 } 8093 8094 /// \brief Check if two fields are layout-compatible. 8095 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 8096 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 8097 return false; 8098 8099 if (Field1->isBitField() != Field2->isBitField()) 8100 return false; 8101 8102 if (Field1->isBitField()) { 8103 // Make sure that the bit-fields are the same length. 8104 unsigned Bits1 = Field1->getBitWidthValue(C); 8105 unsigned Bits2 = Field2->getBitWidthValue(C); 8106 8107 if (Bits1 != Bits2) 8108 return false; 8109 } 8110 8111 return true; 8112 } 8113 8114 /// \brief Check if two standard-layout structs are layout-compatible. 8115 /// (C++11 [class.mem] p17) 8116 bool isLayoutCompatibleStruct(ASTContext &C, 8117 RecordDecl *RD1, 8118 RecordDecl *RD2) { 8119 // If both records are C++ classes, check that base classes match. 8120 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 8121 // If one of records is a CXXRecordDecl we are in C++ mode, 8122 // thus the other one is a CXXRecordDecl, too. 8123 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 8124 // Check number of base classes. 8125 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 8126 return false; 8127 8128 // Check the base classes. 8129 for (CXXRecordDecl::base_class_const_iterator 8130 Base1 = D1CXX->bases_begin(), 8131 BaseEnd1 = D1CXX->bases_end(), 8132 Base2 = D2CXX->bases_begin(); 8133 Base1 != BaseEnd1; 8134 ++Base1, ++Base2) { 8135 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 8136 return false; 8137 } 8138 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 8139 // If only RD2 is a C++ class, it should have zero base classes. 8140 if (D2CXX->getNumBases() > 0) 8141 return false; 8142 } 8143 8144 // Check the fields. 8145 RecordDecl::field_iterator Field2 = RD2->field_begin(), 8146 Field2End = RD2->field_end(), 8147 Field1 = RD1->field_begin(), 8148 Field1End = RD1->field_end(); 8149 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 8150 if (!isLayoutCompatible(C, *Field1, *Field2)) 8151 return false; 8152 } 8153 if (Field1 != Field1End || Field2 != Field2End) 8154 return false; 8155 8156 return true; 8157 } 8158 8159 /// \brief Check if two standard-layout unions are layout-compatible. 8160 /// (C++11 [class.mem] p18) 8161 bool isLayoutCompatibleUnion(ASTContext &C, 8162 RecordDecl *RD1, 8163 RecordDecl *RD2) { 8164 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 8165 for (auto *Field2 : RD2->fields()) 8166 UnmatchedFields.insert(Field2); 8167 8168 for (auto *Field1 : RD1->fields()) { 8169 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 8170 I = UnmatchedFields.begin(), 8171 E = UnmatchedFields.end(); 8172 8173 for ( ; I != E; ++I) { 8174 if (isLayoutCompatible(C, Field1, *I)) { 8175 bool Result = UnmatchedFields.erase(*I); 8176 (void) Result; 8177 assert(Result); 8178 break; 8179 } 8180 } 8181 if (I == E) 8182 return false; 8183 } 8184 8185 return UnmatchedFields.empty(); 8186 } 8187 8188 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 8189 if (RD1->isUnion() != RD2->isUnion()) 8190 return false; 8191 8192 if (RD1->isUnion()) 8193 return isLayoutCompatibleUnion(C, RD1, RD2); 8194 else 8195 return isLayoutCompatibleStruct(C, RD1, RD2); 8196 } 8197 8198 /// \brief Check if two types are layout-compatible in C++11 sense. 8199 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 8200 if (T1.isNull() || T2.isNull()) 8201 return false; 8202 8203 // C++11 [basic.types] p11: 8204 // If two types T1 and T2 are the same type, then T1 and T2 are 8205 // layout-compatible types. 8206 if (C.hasSameType(T1, T2)) 8207 return true; 8208 8209 T1 = T1.getCanonicalType().getUnqualifiedType(); 8210 T2 = T2.getCanonicalType().getUnqualifiedType(); 8211 8212 const Type::TypeClass TC1 = T1->getTypeClass(); 8213 const Type::TypeClass TC2 = T2->getTypeClass(); 8214 8215 if (TC1 != TC2) 8216 return false; 8217 8218 if (TC1 == Type::Enum) { 8219 return isLayoutCompatible(C, 8220 cast<EnumType>(T1)->getDecl(), 8221 cast<EnumType>(T2)->getDecl()); 8222 } else if (TC1 == Type::Record) { 8223 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 8224 return false; 8225 8226 return isLayoutCompatible(C, 8227 cast<RecordType>(T1)->getDecl(), 8228 cast<RecordType>(T2)->getDecl()); 8229 } 8230 8231 return false; 8232 } 8233 } 8234 8235 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 8236 8237 namespace { 8238 /// \brief Given a type tag expression find the type tag itself. 8239 /// 8240 /// \param TypeExpr Type tag expression, as it appears in user's code. 8241 /// 8242 /// \param VD Declaration of an identifier that appears in a type tag. 8243 /// 8244 /// \param MagicValue Type tag magic value. 8245 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 8246 const ValueDecl **VD, uint64_t *MagicValue) { 8247 while(true) { 8248 if (!TypeExpr) 8249 return false; 8250 8251 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 8252 8253 switch (TypeExpr->getStmtClass()) { 8254 case Stmt::UnaryOperatorClass: { 8255 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 8256 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 8257 TypeExpr = UO->getSubExpr(); 8258 continue; 8259 } 8260 return false; 8261 } 8262 8263 case Stmt::DeclRefExprClass: { 8264 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 8265 *VD = DRE->getDecl(); 8266 return true; 8267 } 8268 8269 case Stmt::IntegerLiteralClass: { 8270 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 8271 llvm::APInt MagicValueAPInt = IL->getValue(); 8272 if (MagicValueAPInt.getActiveBits() <= 64) { 8273 *MagicValue = MagicValueAPInt.getZExtValue(); 8274 return true; 8275 } else 8276 return false; 8277 } 8278 8279 case Stmt::BinaryConditionalOperatorClass: 8280 case Stmt::ConditionalOperatorClass: { 8281 const AbstractConditionalOperator *ACO = 8282 cast<AbstractConditionalOperator>(TypeExpr); 8283 bool Result; 8284 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 8285 if (Result) 8286 TypeExpr = ACO->getTrueExpr(); 8287 else 8288 TypeExpr = ACO->getFalseExpr(); 8289 continue; 8290 } 8291 return false; 8292 } 8293 8294 case Stmt::BinaryOperatorClass: { 8295 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 8296 if (BO->getOpcode() == BO_Comma) { 8297 TypeExpr = BO->getRHS(); 8298 continue; 8299 } 8300 return false; 8301 } 8302 8303 default: 8304 return false; 8305 } 8306 } 8307 } 8308 8309 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 8310 /// 8311 /// \param TypeExpr Expression that specifies a type tag. 8312 /// 8313 /// \param MagicValues Registered magic values. 8314 /// 8315 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 8316 /// kind. 8317 /// 8318 /// \param TypeInfo Information about the corresponding C type. 8319 /// 8320 /// \returns true if the corresponding C type was found. 8321 bool GetMatchingCType( 8322 const IdentifierInfo *ArgumentKind, 8323 const Expr *TypeExpr, const ASTContext &Ctx, 8324 const llvm::DenseMap<Sema::TypeTagMagicValue, 8325 Sema::TypeTagData> *MagicValues, 8326 bool &FoundWrongKind, 8327 Sema::TypeTagData &TypeInfo) { 8328 FoundWrongKind = false; 8329 8330 // Variable declaration that has type_tag_for_datatype attribute. 8331 const ValueDecl *VD = nullptr; 8332 8333 uint64_t MagicValue; 8334 8335 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 8336 return false; 8337 8338 if (VD) { 8339 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 8340 if (I->getArgumentKind() != ArgumentKind) { 8341 FoundWrongKind = true; 8342 return false; 8343 } 8344 TypeInfo.Type = I->getMatchingCType(); 8345 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 8346 TypeInfo.MustBeNull = I->getMustBeNull(); 8347 return true; 8348 } 8349 return false; 8350 } 8351 8352 if (!MagicValues) 8353 return false; 8354 8355 llvm::DenseMap<Sema::TypeTagMagicValue, 8356 Sema::TypeTagData>::const_iterator I = 8357 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 8358 if (I == MagicValues->end()) 8359 return false; 8360 8361 TypeInfo = I->second; 8362 return true; 8363 } 8364 } // unnamed namespace 8365 8366 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 8367 uint64_t MagicValue, QualType Type, 8368 bool LayoutCompatible, 8369 bool MustBeNull) { 8370 if (!TypeTagForDatatypeMagicValues) 8371 TypeTagForDatatypeMagicValues.reset( 8372 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 8373 8374 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 8375 (*TypeTagForDatatypeMagicValues)[Magic] = 8376 TypeTagData(Type, LayoutCompatible, MustBeNull); 8377 } 8378 8379 namespace { 8380 bool IsSameCharType(QualType T1, QualType T2) { 8381 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 8382 if (!BT1) 8383 return false; 8384 8385 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 8386 if (!BT2) 8387 return false; 8388 8389 BuiltinType::Kind T1Kind = BT1->getKind(); 8390 BuiltinType::Kind T2Kind = BT2->getKind(); 8391 8392 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 8393 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 8394 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 8395 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 8396 } 8397 } // unnamed namespace 8398 8399 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 8400 const Expr * const *ExprArgs) { 8401 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 8402 bool IsPointerAttr = Attr->getIsPointer(); 8403 8404 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 8405 bool FoundWrongKind; 8406 TypeTagData TypeInfo; 8407 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 8408 TypeTagForDatatypeMagicValues.get(), 8409 FoundWrongKind, TypeInfo)) { 8410 if (FoundWrongKind) 8411 Diag(TypeTagExpr->getExprLoc(), 8412 diag::warn_type_tag_for_datatype_wrong_kind) 8413 << TypeTagExpr->getSourceRange(); 8414 return; 8415 } 8416 8417 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 8418 if (IsPointerAttr) { 8419 // Skip implicit cast of pointer to `void *' (as a function argument). 8420 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 8421 if (ICE->getType()->isVoidPointerType() && 8422 ICE->getCastKind() == CK_BitCast) 8423 ArgumentExpr = ICE->getSubExpr(); 8424 } 8425 QualType ArgumentType = ArgumentExpr->getType(); 8426 8427 // Passing a `void*' pointer shouldn't trigger a warning. 8428 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 8429 return; 8430 8431 if (TypeInfo.MustBeNull) { 8432 // Type tag with matching void type requires a null pointer. 8433 if (!ArgumentExpr->isNullPointerConstant(Context, 8434 Expr::NPC_ValueDependentIsNotNull)) { 8435 Diag(ArgumentExpr->getExprLoc(), 8436 diag::warn_type_safety_null_pointer_required) 8437 << ArgumentKind->getName() 8438 << ArgumentExpr->getSourceRange() 8439 << TypeTagExpr->getSourceRange(); 8440 } 8441 return; 8442 } 8443 8444 QualType RequiredType = TypeInfo.Type; 8445 if (IsPointerAttr) 8446 RequiredType = Context.getPointerType(RequiredType); 8447 8448 bool mismatch = false; 8449 if (!TypeInfo.LayoutCompatible) { 8450 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 8451 8452 // C++11 [basic.fundamental] p1: 8453 // Plain char, signed char, and unsigned char are three distinct types. 8454 // 8455 // But we treat plain `char' as equivalent to `signed char' or `unsigned 8456 // char' depending on the current char signedness mode. 8457 if (mismatch) 8458 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 8459 RequiredType->getPointeeType())) || 8460 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 8461 mismatch = false; 8462 } else 8463 if (IsPointerAttr) 8464 mismatch = !isLayoutCompatible(Context, 8465 ArgumentType->getPointeeType(), 8466 RequiredType->getPointeeType()); 8467 else 8468 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 8469 8470 if (mismatch) 8471 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 8472 << ArgumentType << ArgumentKind 8473 << TypeInfo.LayoutCompatible << RequiredType 8474 << ArgumentExpr->getSourceRange() 8475 << TypeTagExpr->getSourceRange(); 8476 } 8477 8478