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