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