SemaChecking.cpp revision 2edcde8747a000113b434a5c88b4648beed4197b
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/Initialization.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/Initialization.h" 19#include "clang/Sema/Lookup.h" 20#include "clang/Sema/ScopeInfo.h" 21#include "clang/Analysis/Analyses/FormatString.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/CharUnits.h" 24#include "clang/AST/DeclCXX.h" 25#include "clang/AST/DeclObjC.h" 26#include "clang/AST/Expr.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/ExprObjC.h" 29#include "clang/AST/EvaluatedExprVisitor.h" 30#include "clang/AST/DeclObjC.h" 31#include "clang/AST/StmtCXX.h" 32#include "clang/AST/StmtObjC.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/ADT/BitVector.h" 35#include "llvm/ADT/SmallString.h" 36#include "llvm/ADT/STLExtras.h" 37#include "llvm/Support/raw_ostream.h" 38#include "clang/Basic/TargetBuiltins.h" 39#include "clang/Basic/TargetInfo.h" 40#include "clang/Basic/ConvertUTF.h" 41#include <limits> 42using namespace clang; 43using namespace sema; 44 45SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 46 unsigned ByteNo) const { 47 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 48 PP.getLangOpts(), PP.getTargetInfo()); 49} 50 51/// Checks that a call expression's argument count is the desired number. 52/// This is useful when doing custom type-checking. Returns true on error. 53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 54 unsigned argCount = call->getNumArgs(); 55 if (argCount == desiredArgCount) return false; 56 57 if (argCount < desiredArgCount) 58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 59 << 0 /*function call*/ << desiredArgCount << argCount 60 << call->getSourceRange(); 61 62 // Highlight all the excess arguments. 63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 64 call->getArg(argCount - 1)->getLocEnd()); 65 66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 67 << 0 /*function call*/ << desiredArgCount << argCount 68 << call->getArg(1)->getSourceRange(); 69} 70 71/// Check that the first argument to __builtin_annotation is an integer 72/// and the second argument is a non-wide string literal. 73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 74 if (checkArgCount(S, TheCall, 2)) 75 return true; 76 77 // First argument should be an integer. 78 Expr *ValArg = TheCall->getArg(0); 79 QualType Ty = ValArg->getType(); 80 if (!Ty->isIntegerType()) { 81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 82 << ValArg->getSourceRange(); 83 return true; 84 } 85 86 // Second argument should be a constant string. 87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 89 if (!Literal || !Literal->isAscii()) { 90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 91 << StrArg->getSourceRange(); 92 return true; 93 } 94 95 TheCall->setType(Ty); 96 return false; 97} 98 99ExprResult 100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 101 ExprResult TheCallResult(Owned(TheCall)); 102 103 // Find out if any arguments are required to be integer constant expressions. 104 unsigned ICEArguments = 0; 105 ASTContext::GetBuiltinTypeError Error; 106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 107 if (Error != ASTContext::GE_None) 108 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 109 110 // If any arguments are required to be ICE's, check and diagnose. 111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 112 // Skip arguments not required to be ICE's. 113 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 114 115 llvm::APSInt Result; 116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 117 return true; 118 ICEArguments &= ~(1 << ArgNo); 119 } 120 121 switch (BuiltinID) { 122 case Builtin::BI__builtin___CFStringMakeConstantString: 123 assert(TheCall->getNumArgs() == 1 && 124 "Wrong # arguments to builtin CFStringMakeConstantString"); 125 if (CheckObjCString(TheCall->getArg(0))) 126 return ExprError(); 127 break; 128 case Builtin::BI__builtin_stdarg_start: 129 case Builtin::BI__builtin_va_start: 130 if (SemaBuiltinVAStart(TheCall)) 131 return ExprError(); 132 break; 133 case Builtin::BI__builtin_isgreater: 134 case Builtin::BI__builtin_isgreaterequal: 135 case Builtin::BI__builtin_isless: 136 case Builtin::BI__builtin_islessequal: 137 case Builtin::BI__builtin_islessgreater: 138 case Builtin::BI__builtin_isunordered: 139 if (SemaBuiltinUnorderedCompare(TheCall)) 140 return ExprError(); 141 break; 142 case Builtin::BI__builtin_fpclassify: 143 if (SemaBuiltinFPClassification(TheCall, 6)) 144 return ExprError(); 145 break; 146 case Builtin::BI__builtin_isfinite: 147 case Builtin::BI__builtin_isinf: 148 case Builtin::BI__builtin_isinf_sign: 149 case Builtin::BI__builtin_isnan: 150 case Builtin::BI__builtin_isnormal: 151 if (SemaBuiltinFPClassification(TheCall, 1)) 152 return ExprError(); 153 break; 154 case Builtin::BI__builtin_shufflevector: 155 return SemaBuiltinShuffleVector(TheCall); 156 // TheCall will be freed by the smart pointer here, but that's fine, since 157 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 158 case Builtin::BI__builtin_prefetch: 159 if (SemaBuiltinPrefetch(TheCall)) 160 return ExprError(); 161 break; 162 case Builtin::BI__builtin_object_size: 163 if (SemaBuiltinObjectSize(TheCall)) 164 return ExprError(); 165 break; 166 case Builtin::BI__builtin_longjmp: 167 if (SemaBuiltinLongjmp(TheCall)) 168 return ExprError(); 169 break; 170 171 case Builtin::BI__builtin_classify_type: 172 if (checkArgCount(*this, TheCall, 1)) return true; 173 TheCall->setType(Context.IntTy); 174 break; 175 case Builtin::BI__builtin_constant_p: 176 if (checkArgCount(*this, TheCall, 1)) return true; 177 TheCall->setType(Context.IntTy); 178 break; 179 case Builtin::BI__sync_fetch_and_add: 180 case Builtin::BI__sync_fetch_and_add_1: 181 case Builtin::BI__sync_fetch_and_add_2: 182 case Builtin::BI__sync_fetch_and_add_4: 183 case Builtin::BI__sync_fetch_and_add_8: 184 case Builtin::BI__sync_fetch_and_add_16: 185 case Builtin::BI__sync_fetch_and_sub: 186 case Builtin::BI__sync_fetch_and_sub_1: 187 case Builtin::BI__sync_fetch_and_sub_2: 188 case Builtin::BI__sync_fetch_and_sub_4: 189 case Builtin::BI__sync_fetch_and_sub_8: 190 case Builtin::BI__sync_fetch_and_sub_16: 191 case Builtin::BI__sync_fetch_and_or: 192 case Builtin::BI__sync_fetch_and_or_1: 193 case Builtin::BI__sync_fetch_and_or_2: 194 case Builtin::BI__sync_fetch_and_or_4: 195 case Builtin::BI__sync_fetch_and_or_8: 196 case Builtin::BI__sync_fetch_and_or_16: 197 case Builtin::BI__sync_fetch_and_and: 198 case Builtin::BI__sync_fetch_and_and_1: 199 case Builtin::BI__sync_fetch_and_and_2: 200 case Builtin::BI__sync_fetch_and_and_4: 201 case Builtin::BI__sync_fetch_and_and_8: 202 case Builtin::BI__sync_fetch_and_and_16: 203 case Builtin::BI__sync_fetch_and_xor: 204 case Builtin::BI__sync_fetch_and_xor_1: 205 case Builtin::BI__sync_fetch_and_xor_2: 206 case Builtin::BI__sync_fetch_and_xor_4: 207 case Builtin::BI__sync_fetch_and_xor_8: 208 case Builtin::BI__sync_fetch_and_xor_16: 209 case Builtin::BI__sync_add_and_fetch: 210 case Builtin::BI__sync_add_and_fetch_1: 211 case Builtin::BI__sync_add_and_fetch_2: 212 case Builtin::BI__sync_add_and_fetch_4: 213 case Builtin::BI__sync_add_and_fetch_8: 214 case Builtin::BI__sync_add_and_fetch_16: 215 case Builtin::BI__sync_sub_and_fetch: 216 case Builtin::BI__sync_sub_and_fetch_1: 217 case Builtin::BI__sync_sub_and_fetch_2: 218 case Builtin::BI__sync_sub_and_fetch_4: 219 case Builtin::BI__sync_sub_and_fetch_8: 220 case Builtin::BI__sync_sub_and_fetch_16: 221 case Builtin::BI__sync_and_and_fetch: 222 case Builtin::BI__sync_and_and_fetch_1: 223 case Builtin::BI__sync_and_and_fetch_2: 224 case Builtin::BI__sync_and_and_fetch_4: 225 case Builtin::BI__sync_and_and_fetch_8: 226 case Builtin::BI__sync_and_and_fetch_16: 227 case Builtin::BI__sync_or_and_fetch: 228 case Builtin::BI__sync_or_and_fetch_1: 229 case Builtin::BI__sync_or_and_fetch_2: 230 case Builtin::BI__sync_or_and_fetch_4: 231 case Builtin::BI__sync_or_and_fetch_8: 232 case Builtin::BI__sync_or_and_fetch_16: 233 case Builtin::BI__sync_xor_and_fetch: 234 case Builtin::BI__sync_xor_and_fetch_1: 235 case Builtin::BI__sync_xor_and_fetch_2: 236 case Builtin::BI__sync_xor_and_fetch_4: 237 case Builtin::BI__sync_xor_and_fetch_8: 238 case Builtin::BI__sync_xor_and_fetch_16: 239 case Builtin::BI__sync_val_compare_and_swap: 240 case Builtin::BI__sync_val_compare_and_swap_1: 241 case Builtin::BI__sync_val_compare_and_swap_2: 242 case Builtin::BI__sync_val_compare_and_swap_4: 243 case Builtin::BI__sync_val_compare_and_swap_8: 244 case Builtin::BI__sync_val_compare_and_swap_16: 245 case Builtin::BI__sync_bool_compare_and_swap: 246 case Builtin::BI__sync_bool_compare_and_swap_1: 247 case Builtin::BI__sync_bool_compare_and_swap_2: 248 case Builtin::BI__sync_bool_compare_and_swap_4: 249 case Builtin::BI__sync_bool_compare_and_swap_8: 250 case Builtin::BI__sync_bool_compare_and_swap_16: 251 case Builtin::BI__sync_lock_test_and_set: 252 case Builtin::BI__sync_lock_test_and_set_1: 253 case Builtin::BI__sync_lock_test_and_set_2: 254 case Builtin::BI__sync_lock_test_and_set_4: 255 case Builtin::BI__sync_lock_test_and_set_8: 256 case Builtin::BI__sync_lock_test_and_set_16: 257 case Builtin::BI__sync_lock_release: 258 case Builtin::BI__sync_lock_release_1: 259 case Builtin::BI__sync_lock_release_2: 260 case Builtin::BI__sync_lock_release_4: 261 case Builtin::BI__sync_lock_release_8: 262 case Builtin::BI__sync_lock_release_16: 263 case Builtin::BI__sync_swap: 264 case Builtin::BI__sync_swap_1: 265 case Builtin::BI__sync_swap_2: 266 case Builtin::BI__sync_swap_4: 267 case Builtin::BI__sync_swap_8: 268 case Builtin::BI__sync_swap_16: 269 return SemaBuiltinAtomicOverloaded(TheCallResult); 270#define BUILTIN(ID, TYPE, ATTRS) 271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 272 case Builtin::BI##ID: \ 273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 274#include "clang/Basic/Builtins.def" 275 case Builtin::BI__builtin_annotation: 276 if (SemaBuiltinAnnotation(*this, TheCall)) 277 return ExprError(); 278 break; 279 } 280 281 // Since the target specific builtins for each arch overlap, only check those 282 // of the arch we are compiling for. 283 if (BuiltinID >= Builtin::FirstTSBuiltin) { 284 switch (Context.getTargetInfo().getTriple().getArch()) { 285 case llvm::Triple::arm: 286 case llvm::Triple::thumb: 287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 288 return ExprError(); 289 break; 290 case llvm::Triple::mips: 291 case llvm::Triple::mipsel: 292 case llvm::Triple::mips64: 293 case llvm::Triple::mips64el: 294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 295 return ExprError(); 296 break; 297 default: 298 break; 299 } 300 } 301 302 return TheCallResult; 303} 304 305// Get the valid immediate range for the specified NEON type code. 306static unsigned RFT(unsigned t, bool shift = false) { 307 NeonTypeFlags Type(t); 308 int IsQuad = Type.isQuad(); 309 switch (Type.getEltType()) { 310 case NeonTypeFlags::Int8: 311 case NeonTypeFlags::Poly8: 312 return shift ? 7 : (8 << IsQuad) - 1; 313 case NeonTypeFlags::Int16: 314 case NeonTypeFlags::Poly16: 315 return shift ? 15 : (4 << IsQuad) - 1; 316 case NeonTypeFlags::Int32: 317 return shift ? 31 : (2 << IsQuad) - 1; 318 case NeonTypeFlags::Int64: 319 return shift ? 63 : (1 << IsQuad) - 1; 320 case NeonTypeFlags::Float16: 321 assert(!shift && "cannot shift float types!"); 322 return (4 << IsQuad) - 1; 323 case NeonTypeFlags::Float32: 324 assert(!shift && "cannot shift float types!"); 325 return (2 << IsQuad) - 1; 326 } 327 llvm_unreachable("Invalid NeonTypeFlag!"); 328} 329 330/// getNeonEltType - Return the QualType corresponding to the elements of 331/// the vector type specified by the NeonTypeFlags. This is used to check 332/// the pointer arguments for Neon load/store intrinsics. 333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 334 switch (Flags.getEltType()) { 335 case NeonTypeFlags::Int8: 336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 337 case NeonTypeFlags::Int16: 338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 339 case NeonTypeFlags::Int32: 340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 341 case NeonTypeFlags::Int64: 342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 343 case NeonTypeFlags::Poly8: 344 return Context.SignedCharTy; 345 case NeonTypeFlags::Poly16: 346 return Context.ShortTy; 347 case NeonTypeFlags::Float16: 348 return Context.UnsignedShortTy; 349 case NeonTypeFlags::Float32: 350 return Context.FloatTy; 351 } 352 llvm_unreachable("Invalid NeonTypeFlag!"); 353} 354 355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 356 llvm::APSInt Result; 357 358 uint64_t mask = 0; 359 unsigned TV = 0; 360 int PtrArgNum = -1; 361 bool HasConstPtr = false; 362 switch (BuiltinID) { 363#define GET_NEON_OVERLOAD_CHECK 364#include "clang/Basic/arm_neon.inc" 365#undef GET_NEON_OVERLOAD_CHECK 366 } 367 368 // For NEON intrinsics which are overloaded on vector element type, validate 369 // the immediate which specifies which variant to emit. 370 unsigned ImmArg = TheCall->getNumArgs()-1; 371 if (mask) { 372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 373 return true; 374 375 TV = Result.getLimitedValue(64); 376 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 378 << TheCall->getArg(ImmArg)->getSourceRange(); 379 } 380 381 if (PtrArgNum >= 0) { 382 // Check that pointer arguments have the specified type. 383 Expr *Arg = TheCall->getArg(PtrArgNum); 384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 385 Arg = ICE->getSubExpr(); 386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 387 QualType RHSTy = RHS.get()->getType(); 388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 389 if (HasConstPtr) 390 EltTy = EltTy.withConst(); 391 QualType LHSTy = Context.getPointerType(EltTy); 392 AssignConvertType ConvTy; 393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 394 if (RHS.isInvalid()) 395 return true; 396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 397 RHS.get(), AA_Assigning)) 398 return true; 399 } 400 401 // For NEON intrinsics which take an immediate value as part of the 402 // instruction, range check them here. 403 unsigned i = 0, l = 0, u = 0; 404 switch (BuiltinID) { 405 default: return false; 406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 408 case ARM::BI__builtin_arm_vcvtr_f: 409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 410#define GET_NEON_IMMEDIATE_CHECK 411#include "clang/Basic/arm_neon.inc" 412#undef GET_NEON_IMMEDIATE_CHECK 413 }; 414 415 // We can't check the value of a dependent argument. 416 if (TheCall->getArg(i)->isTypeDependent() || 417 TheCall->getArg(i)->isValueDependent()) 418 return false; 419 420 // Check that the immediate argument is actually a constant. 421 if (SemaBuiltinConstantArg(TheCall, i, Result)) 422 return true; 423 424 // Range check against the upper/lower values for this isntruction. 425 unsigned Val = Result.getZExtValue(); 426 if (Val < l || Val > (u + l)) 427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 428 << l << u+l << TheCall->getArg(i)->getSourceRange(); 429 430 // FIXME: VFP Intrinsics should error if VFP not present. 431 return false; 432} 433 434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 435 unsigned i = 0, l = 0, u = 0; 436 switch (BuiltinID) { 437 default: return false; 438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 445 }; 446 447 // We can't check the value of a dependent argument. 448 if (TheCall->getArg(i)->isTypeDependent() || 449 TheCall->getArg(i)->isValueDependent()) 450 return false; 451 452 // Check that the immediate argument is actually a constant. 453 llvm::APSInt Result; 454 if (SemaBuiltinConstantArg(TheCall, i, Result)) 455 return true; 456 457 // Range check against the upper/lower values for this instruction. 458 unsigned Val = Result.getZExtValue(); 459 if (Val < l || Val > u) 460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 461 << l << u << TheCall->getArg(i)->getSourceRange(); 462 463 return false; 464} 465 466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 467/// parameter with the FormatAttr's correct format_idx and firstDataArg. 468/// Returns true when the format fits the function and the FormatStringInfo has 469/// been populated. 470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 471 FormatStringInfo *FSI) { 472 FSI->HasVAListArg = Format->getFirstArg() == 0; 473 FSI->FormatIdx = Format->getFormatIdx() - 1; 474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 475 476 // The way the format attribute works in GCC, the implicit this argument 477 // of member functions is counted. However, it doesn't appear in our own 478 // lists, so decrement format_idx in that case. 479 if (IsCXXMember) { 480 if(FSI->FormatIdx == 0) 481 return false; 482 --FSI->FormatIdx; 483 if (FSI->FirstDataArg != 0) 484 --FSI->FirstDataArg; 485 } 486 return true; 487} 488 489/// Handles the checks for format strings, non-POD arguments to vararg 490/// functions, and NULL arguments passed to non-NULL parameters. 491void Sema::checkCall(NamedDecl *FDecl, Expr **Args, 492 unsigned NumArgs, 493 unsigned NumProtoArgs, 494 bool IsMemberFunction, 495 SourceLocation Loc, 496 SourceRange Range, 497 VariadicCallType CallType) { 498 if (CurContext->isDependentContext()) 499 return; 500 501 // Printf and scanf checking. 502 bool HandledFormatString = false; 503 for (specific_attr_iterator<FormatAttr> 504 I = FDecl->specific_attr_begin<FormatAttr>(), 505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I) 506 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType, 507 Loc, Range)) 508 HandledFormatString = true; 509 510 // Refuse POD arguments that weren't caught by the format string 511 // checks above. 512 if (!HandledFormatString && CallType != VariadicDoesNotApply) 513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx) 514 variadicArgumentPODCheck(Args[ArgIdx], CallType); 515 516 for (specific_attr_iterator<NonNullAttr> 517 I = FDecl->specific_attr_begin<NonNullAttr>(), 518 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) 519 CheckNonNullArguments(*I, Args, Loc); 520 521 // Type safety checking. 522 for (specific_attr_iterator<ArgumentWithTypeTagAttr> 523 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(), 524 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) { 525 CheckArgumentWithTypeTag(*i, Args); 526 } 527} 528 529/// CheckConstructorCall - Check a constructor call for correctness and safety 530/// properties not enforced by the C type system. 531void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args, 532 unsigned NumArgs, 533 const FunctionProtoType *Proto, 534 SourceLocation Loc) { 535 VariadicCallType CallType = 536 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 537 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(), 538 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 539} 540 541/// CheckFunctionCall - Check a direct function call for various correctness 542/// and safety properties not strictly enforced by the C type system. 543bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 544 const FunctionProtoType *Proto) { 545 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 546 isa<CXXMethodDecl>(FDecl); 547 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 548 IsMemberOperatorCall; 549 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 550 TheCall->getCallee()); 551 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 552 Expr** Args = TheCall->getArgs(); 553 unsigned NumArgs = TheCall->getNumArgs(); 554 if (isa<CXXOperatorCallExpr>(TheCall) && isa<CXXMethodDecl>(FDecl)) { 555 // If this is a call to a member operator, hide the first argument 556 // from checkCall. 557 // FIXME: Our choice of AST representation here is less than ideal. 558 ++Args; 559 --NumArgs; 560 } 561 checkCall(FDecl, Args, NumArgs, NumProtoArgs, 562 IsMemberFunction, TheCall->getRParenLoc(), 563 TheCall->getCallee()->getSourceRange(), CallType); 564 565 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 566 // None of the checks below are needed for functions that don't have 567 // simple names (e.g., C++ conversion functions). 568 if (!FnInfo) 569 return false; 570 571 unsigned CMId = FDecl->getMemoryFunctionKind(); 572 if (CMId == 0) 573 return false; 574 575 // Handle memory setting and copying functions. 576 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 577 CheckStrlcpycatArguments(TheCall, FnInfo); 578 else if (CMId == Builtin::BIstrncat) 579 CheckStrncatArguments(TheCall, FnInfo); 580 else 581 CheckMemaccessArguments(TheCall, CMId, FnInfo); 582 583 return false; 584} 585 586bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 587 Expr **Args, unsigned NumArgs) { 588 VariadicCallType CallType = 589 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 590 591 checkCall(Method, Args, NumArgs, Method->param_size(), 592 /*IsMemberFunction=*/false, 593 lbrac, Method->getSourceRange(), CallType); 594 595 return false; 596} 597 598bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall, 599 const FunctionProtoType *Proto) { 600 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 601 if (!V) 602 return false; 603 604 QualType Ty = V->getType(); 605 if (!Ty->isBlockPointerType()) 606 return false; 607 608 VariadicCallType CallType = 609 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ; 610 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0; 611 612 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(), 613 NumProtoArgs, /*IsMemberFunction=*/false, 614 TheCall->getRParenLoc(), 615 TheCall->getCallee()->getSourceRange(), CallType); 616 617 return false; 618} 619 620ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 621 AtomicExpr::AtomicOp Op) { 622 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 623 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 624 625 // All these operations take one of the following forms: 626 enum { 627 // C __c11_atomic_init(A *, C) 628 Init, 629 // C __c11_atomic_load(A *, int) 630 Load, 631 // void __atomic_load(A *, CP, int) 632 Copy, 633 // C __c11_atomic_add(A *, M, int) 634 Arithmetic, 635 // C __atomic_exchange_n(A *, CP, int) 636 Xchg, 637 // void __atomic_exchange(A *, C *, CP, int) 638 GNUXchg, 639 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 640 C11CmpXchg, 641 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 642 GNUCmpXchg 643 } Form = Init; 644 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 645 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 646 // where: 647 // C is an appropriate type, 648 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 649 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 650 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 651 // the int parameters are for orderings. 652 653 assert(AtomicExpr::AO__c11_atomic_init == 0 && 654 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 655 && "need to update code for modified C11 atomics"); 656 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 657 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 658 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 659 Op == AtomicExpr::AO__atomic_store_n || 660 Op == AtomicExpr::AO__atomic_exchange_n || 661 Op == AtomicExpr::AO__atomic_compare_exchange_n; 662 bool IsAddSub = false; 663 664 switch (Op) { 665 case AtomicExpr::AO__c11_atomic_init: 666 Form = Init; 667 break; 668 669 case AtomicExpr::AO__c11_atomic_load: 670 case AtomicExpr::AO__atomic_load_n: 671 Form = Load; 672 break; 673 674 case AtomicExpr::AO__c11_atomic_store: 675 case AtomicExpr::AO__atomic_load: 676 case AtomicExpr::AO__atomic_store: 677 case AtomicExpr::AO__atomic_store_n: 678 Form = Copy; 679 break; 680 681 case AtomicExpr::AO__c11_atomic_fetch_add: 682 case AtomicExpr::AO__c11_atomic_fetch_sub: 683 case AtomicExpr::AO__atomic_fetch_add: 684 case AtomicExpr::AO__atomic_fetch_sub: 685 case AtomicExpr::AO__atomic_add_fetch: 686 case AtomicExpr::AO__atomic_sub_fetch: 687 IsAddSub = true; 688 // Fall through. 689 case AtomicExpr::AO__c11_atomic_fetch_and: 690 case AtomicExpr::AO__c11_atomic_fetch_or: 691 case AtomicExpr::AO__c11_atomic_fetch_xor: 692 case AtomicExpr::AO__atomic_fetch_and: 693 case AtomicExpr::AO__atomic_fetch_or: 694 case AtomicExpr::AO__atomic_fetch_xor: 695 case AtomicExpr::AO__atomic_fetch_nand: 696 case AtomicExpr::AO__atomic_and_fetch: 697 case AtomicExpr::AO__atomic_or_fetch: 698 case AtomicExpr::AO__atomic_xor_fetch: 699 case AtomicExpr::AO__atomic_nand_fetch: 700 Form = Arithmetic; 701 break; 702 703 case AtomicExpr::AO__c11_atomic_exchange: 704 case AtomicExpr::AO__atomic_exchange_n: 705 Form = Xchg; 706 break; 707 708 case AtomicExpr::AO__atomic_exchange: 709 Form = GNUXchg; 710 break; 711 712 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 713 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 714 Form = C11CmpXchg; 715 break; 716 717 case AtomicExpr::AO__atomic_compare_exchange: 718 case AtomicExpr::AO__atomic_compare_exchange_n: 719 Form = GNUCmpXchg; 720 break; 721 } 722 723 // Check we have the right number of arguments. 724 if (TheCall->getNumArgs() < NumArgs[Form]) { 725 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 726 << 0 << NumArgs[Form] << TheCall->getNumArgs() 727 << TheCall->getCallee()->getSourceRange(); 728 return ExprError(); 729 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 730 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 731 diag::err_typecheck_call_too_many_args) 732 << 0 << NumArgs[Form] << TheCall->getNumArgs() 733 << TheCall->getCallee()->getSourceRange(); 734 return ExprError(); 735 } 736 737 // Inspect the first argument of the atomic operation. 738 Expr *Ptr = TheCall->getArg(0); 739 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 740 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 741 if (!pointerType) { 742 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 743 << Ptr->getType() << Ptr->getSourceRange(); 744 return ExprError(); 745 } 746 747 // For a __c11 builtin, this should be a pointer to an _Atomic type. 748 QualType AtomTy = pointerType->getPointeeType(); // 'A' 749 QualType ValType = AtomTy; // 'C' 750 if (IsC11) { 751 if (!AtomTy->isAtomicType()) { 752 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 753 << Ptr->getType() << Ptr->getSourceRange(); 754 return ExprError(); 755 } 756 if (AtomTy.isConstQualified()) { 757 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 758 << Ptr->getType() << Ptr->getSourceRange(); 759 return ExprError(); 760 } 761 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 762 } 763 764 // For an arithmetic operation, the implied arithmetic must be well-formed. 765 if (Form == Arithmetic) { 766 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 767 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 768 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 769 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 770 return ExprError(); 771 } 772 if (!IsAddSub && !ValType->isIntegerType()) { 773 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 774 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 775 return ExprError(); 776 } 777 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 778 // For __atomic_*_n operations, the value type must be a scalar integral or 779 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 780 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 781 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 782 return ExprError(); 783 } 784 785 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) { 786 // For GNU atomics, require a trivially-copyable type. This is not part of 787 // the GNU atomics specification, but we enforce it for sanity. 788 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 789 << Ptr->getType() << Ptr->getSourceRange(); 790 return ExprError(); 791 } 792 793 // FIXME: For any builtin other than a load, the ValType must not be 794 // const-qualified. 795 796 switch (ValType.getObjCLifetime()) { 797 case Qualifiers::OCL_None: 798 case Qualifiers::OCL_ExplicitNone: 799 // okay 800 break; 801 802 case Qualifiers::OCL_Weak: 803 case Qualifiers::OCL_Strong: 804 case Qualifiers::OCL_Autoreleasing: 805 // FIXME: Can this happen? By this point, ValType should be known 806 // to be trivially copyable. 807 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 808 << ValType << Ptr->getSourceRange(); 809 return ExprError(); 810 } 811 812 QualType ResultType = ValType; 813 if (Form == Copy || Form == GNUXchg || Form == Init) 814 ResultType = Context.VoidTy; 815 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 816 ResultType = Context.BoolTy; 817 818 // The type of a parameter passed 'by value'. In the GNU atomics, such 819 // arguments are actually passed as pointers. 820 QualType ByValType = ValType; // 'CP' 821 if (!IsC11 && !IsN) 822 ByValType = Ptr->getType(); 823 824 // The first argument --- the pointer --- has a fixed type; we 825 // deduce the types of the rest of the arguments accordingly. Walk 826 // the remaining arguments, converting them to the deduced value type. 827 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 828 QualType Ty; 829 if (i < NumVals[Form] + 1) { 830 switch (i) { 831 case 1: 832 // The second argument is the non-atomic operand. For arithmetic, this 833 // is always passed by value, and for a compare_exchange it is always 834 // passed by address. For the rest, GNU uses by-address and C11 uses 835 // by-value. 836 assert(Form != Load); 837 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 838 Ty = ValType; 839 else if (Form == Copy || Form == Xchg) 840 Ty = ByValType; 841 else if (Form == Arithmetic) 842 Ty = Context.getPointerDiffType(); 843 else 844 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 845 break; 846 case 2: 847 // The third argument to compare_exchange / GNU exchange is a 848 // (pointer to a) desired value. 849 Ty = ByValType; 850 break; 851 case 3: 852 // The fourth argument to GNU compare_exchange is a 'weak' flag. 853 Ty = Context.BoolTy; 854 break; 855 } 856 } else { 857 // The order(s) are always converted to int. 858 Ty = Context.IntTy; 859 } 860 861 InitializedEntity Entity = 862 InitializedEntity::InitializeParameter(Context, Ty, false); 863 ExprResult Arg = TheCall->getArg(i); 864 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 865 if (Arg.isInvalid()) 866 return true; 867 TheCall->setArg(i, Arg.get()); 868 } 869 870 // Permute the arguments into a 'consistent' order. 871 SmallVector<Expr*, 5> SubExprs; 872 SubExprs.push_back(Ptr); 873 switch (Form) { 874 case Init: 875 // Note, AtomicExpr::getVal1() has a special case for this atomic. 876 SubExprs.push_back(TheCall->getArg(1)); // Val1 877 break; 878 case Load: 879 SubExprs.push_back(TheCall->getArg(1)); // Order 880 break; 881 case Copy: 882 case Arithmetic: 883 case Xchg: 884 SubExprs.push_back(TheCall->getArg(2)); // Order 885 SubExprs.push_back(TheCall->getArg(1)); // Val1 886 break; 887 case GNUXchg: 888 // Note, AtomicExpr::getVal2() has a special case for this atomic. 889 SubExprs.push_back(TheCall->getArg(3)); // Order 890 SubExprs.push_back(TheCall->getArg(1)); // Val1 891 SubExprs.push_back(TheCall->getArg(2)); // Val2 892 break; 893 case C11CmpXchg: 894 SubExprs.push_back(TheCall->getArg(3)); // Order 895 SubExprs.push_back(TheCall->getArg(1)); // Val1 896 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 897 SubExprs.push_back(TheCall->getArg(2)); // Val2 898 break; 899 case GNUCmpXchg: 900 SubExprs.push_back(TheCall->getArg(4)); // Order 901 SubExprs.push_back(TheCall->getArg(1)); // Val1 902 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 903 SubExprs.push_back(TheCall->getArg(2)); // Val2 904 SubExprs.push_back(TheCall->getArg(3)); // Weak 905 break; 906 } 907 908 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 909 SubExprs, ResultType, Op, 910 TheCall->getRParenLoc())); 911} 912 913 914/// checkBuiltinArgument - Given a call to a builtin function, perform 915/// normal type-checking on the given argument, updating the call in 916/// place. This is useful when a builtin function requires custom 917/// type-checking for some of its arguments but not necessarily all of 918/// them. 919/// 920/// Returns true on error. 921static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 922 FunctionDecl *Fn = E->getDirectCallee(); 923 assert(Fn && "builtin call without direct callee!"); 924 925 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 926 InitializedEntity Entity = 927 InitializedEntity::InitializeParameter(S.Context, Param); 928 929 ExprResult Arg = E->getArg(0); 930 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 931 if (Arg.isInvalid()) 932 return true; 933 934 E->setArg(ArgIndex, Arg.take()); 935 return false; 936} 937 938/// SemaBuiltinAtomicOverloaded - We have a call to a function like 939/// __sync_fetch_and_add, which is an overloaded function based on the pointer 940/// type of its first argument. The main ActOnCallExpr routines have already 941/// promoted the types of arguments because all of these calls are prototyped as 942/// void(...). 943/// 944/// This function goes through and does final semantic checking for these 945/// builtins, 946ExprResult 947Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 948 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 949 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 950 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 951 952 // Ensure that we have at least one argument to do type inference from. 953 if (TheCall->getNumArgs() < 1) { 954 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 955 << 0 << 1 << TheCall->getNumArgs() 956 << TheCall->getCallee()->getSourceRange(); 957 return ExprError(); 958 } 959 960 // Inspect the first argument of the atomic builtin. This should always be 961 // a pointer type, whose element is an integral scalar or pointer type. 962 // Because it is a pointer type, we don't have to worry about any implicit 963 // casts here. 964 // FIXME: We don't allow floating point scalars as input. 965 Expr *FirstArg = TheCall->getArg(0); 966 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 967 if (FirstArgResult.isInvalid()) 968 return ExprError(); 969 FirstArg = FirstArgResult.take(); 970 TheCall->setArg(0, FirstArg); 971 972 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 973 if (!pointerType) { 974 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 975 << FirstArg->getType() << FirstArg->getSourceRange(); 976 return ExprError(); 977 } 978 979 QualType ValType = pointerType->getPointeeType(); 980 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 981 !ValType->isBlockPointerType()) { 982 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 983 << FirstArg->getType() << FirstArg->getSourceRange(); 984 return ExprError(); 985 } 986 987 switch (ValType.getObjCLifetime()) { 988 case Qualifiers::OCL_None: 989 case Qualifiers::OCL_ExplicitNone: 990 // okay 991 break; 992 993 case Qualifiers::OCL_Weak: 994 case Qualifiers::OCL_Strong: 995 case Qualifiers::OCL_Autoreleasing: 996 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 997 << ValType << FirstArg->getSourceRange(); 998 return ExprError(); 999 } 1000 1001 // Strip any qualifiers off ValType. 1002 ValType = ValType.getUnqualifiedType(); 1003 1004 // The majority of builtins return a value, but a few have special return 1005 // types, so allow them to override appropriately below. 1006 QualType ResultType = ValType; 1007 1008 // We need to figure out which concrete builtin this maps onto. For example, 1009 // __sync_fetch_and_add with a 2 byte object turns into 1010 // __sync_fetch_and_add_2. 1011#define BUILTIN_ROW(x) \ 1012 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 1013 Builtin::BI##x##_8, Builtin::BI##x##_16 } 1014 1015 static const unsigned BuiltinIndices[][5] = { 1016 BUILTIN_ROW(__sync_fetch_and_add), 1017 BUILTIN_ROW(__sync_fetch_and_sub), 1018 BUILTIN_ROW(__sync_fetch_and_or), 1019 BUILTIN_ROW(__sync_fetch_and_and), 1020 BUILTIN_ROW(__sync_fetch_and_xor), 1021 1022 BUILTIN_ROW(__sync_add_and_fetch), 1023 BUILTIN_ROW(__sync_sub_and_fetch), 1024 BUILTIN_ROW(__sync_and_and_fetch), 1025 BUILTIN_ROW(__sync_or_and_fetch), 1026 BUILTIN_ROW(__sync_xor_and_fetch), 1027 1028 BUILTIN_ROW(__sync_val_compare_and_swap), 1029 BUILTIN_ROW(__sync_bool_compare_and_swap), 1030 BUILTIN_ROW(__sync_lock_test_and_set), 1031 BUILTIN_ROW(__sync_lock_release), 1032 BUILTIN_ROW(__sync_swap) 1033 }; 1034#undef BUILTIN_ROW 1035 1036 // Determine the index of the size. 1037 unsigned SizeIndex; 1038 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1039 case 1: SizeIndex = 0; break; 1040 case 2: SizeIndex = 1; break; 1041 case 4: SizeIndex = 2; break; 1042 case 8: SizeIndex = 3; break; 1043 case 16: SizeIndex = 4; break; 1044 default: 1045 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1046 << FirstArg->getType() << FirstArg->getSourceRange(); 1047 return ExprError(); 1048 } 1049 1050 // Each of these builtins has one pointer argument, followed by some number of 1051 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1052 // that we ignore. Find out which row of BuiltinIndices to read from as well 1053 // as the number of fixed args. 1054 unsigned BuiltinID = FDecl->getBuiltinID(); 1055 unsigned BuiltinIndex, NumFixed = 1; 1056 switch (BuiltinID) { 1057 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1058 case Builtin::BI__sync_fetch_and_add: 1059 case Builtin::BI__sync_fetch_and_add_1: 1060 case Builtin::BI__sync_fetch_and_add_2: 1061 case Builtin::BI__sync_fetch_and_add_4: 1062 case Builtin::BI__sync_fetch_and_add_8: 1063 case Builtin::BI__sync_fetch_and_add_16: 1064 BuiltinIndex = 0; 1065 break; 1066 1067 case Builtin::BI__sync_fetch_and_sub: 1068 case Builtin::BI__sync_fetch_and_sub_1: 1069 case Builtin::BI__sync_fetch_and_sub_2: 1070 case Builtin::BI__sync_fetch_and_sub_4: 1071 case Builtin::BI__sync_fetch_and_sub_8: 1072 case Builtin::BI__sync_fetch_and_sub_16: 1073 BuiltinIndex = 1; 1074 break; 1075 1076 case Builtin::BI__sync_fetch_and_or: 1077 case Builtin::BI__sync_fetch_and_or_1: 1078 case Builtin::BI__sync_fetch_and_or_2: 1079 case Builtin::BI__sync_fetch_and_or_4: 1080 case Builtin::BI__sync_fetch_and_or_8: 1081 case Builtin::BI__sync_fetch_and_or_16: 1082 BuiltinIndex = 2; 1083 break; 1084 1085 case Builtin::BI__sync_fetch_and_and: 1086 case Builtin::BI__sync_fetch_and_and_1: 1087 case Builtin::BI__sync_fetch_and_and_2: 1088 case Builtin::BI__sync_fetch_and_and_4: 1089 case Builtin::BI__sync_fetch_and_and_8: 1090 case Builtin::BI__sync_fetch_and_and_16: 1091 BuiltinIndex = 3; 1092 break; 1093 1094 case Builtin::BI__sync_fetch_and_xor: 1095 case Builtin::BI__sync_fetch_and_xor_1: 1096 case Builtin::BI__sync_fetch_and_xor_2: 1097 case Builtin::BI__sync_fetch_and_xor_4: 1098 case Builtin::BI__sync_fetch_and_xor_8: 1099 case Builtin::BI__sync_fetch_and_xor_16: 1100 BuiltinIndex = 4; 1101 break; 1102 1103 case Builtin::BI__sync_add_and_fetch: 1104 case Builtin::BI__sync_add_and_fetch_1: 1105 case Builtin::BI__sync_add_and_fetch_2: 1106 case Builtin::BI__sync_add_and_fetch_4: 1107 case Builtin::BI__sync_add_and_fetch_8: 1108 case Builtin::BI__sync_add_and_fetch_16: 1109 BuiltinIndex = 5; 1110 break; 1111 1112 case Builtin::BI__sync_sub_and_fetch: 1113 case Builtin::BI__sync_sub_and_fetch_1: 1114 case Builtin::BI__sync_sub_and_fetch_2: 1115 case Builtin::BI__sync_sub_and_fetch_4: 1116 case Builtin::BI__sync_sub_and_fetch_8: 1117 case Builtin::BI__sync_sub_and_fetch_16: 1118 BuiltinIndex = 6; 1119 break; 1120 1121 case Builtin::BI__sync_and_and_fetch: 1122 case Builtin::BI__sync_and_and_fetch_1: 1123 case Builtin::BI__sync_and_and_fetch_2: 1124 case Builtin::BI__sync_and_and_fetch_4: 1125 case Builtin::BI__sync_and_and_fetch_8: 1126 case Builtin::BI__sync_and_and_fetch_16: 1127 BuiltinIndex = 7; 1128 break; 1129 1130 case Builtin::BI__sync_or_and_fetch: 1131 case Builtin::BI__sync_or_and_fetch_1: 1132 case Builtin::BI__sync_or_and_fetch_2: 1133 case Builtin::BI__sync_or_and_fetch_4: 1134 case Builtin::BI__sync_or_and_fetch_8: 1135 case Builtin::BI__sync_or_and_fetch_16: 1136 BuiltinIndex = 8; 1137 break; 1138 1139 case Builtin::BI__sync_xor_and_fetch: 1140 case Builtin::BI__sync_xor_and_fetch_1: 1141 case Builtin::BI__sync_xor_and_fetch_2: 1142 case Builtin::BI__sync_xor_and_fetch_4: 1143 case Builtin::BI__sync_xor_and_fetch_8: 1144 case Builtin::BI__sync_xor_and_fetch_16: 1145 BuiltinIndex = 9; 1146 break; 1147 1148 case Builtin::BI__sync_val_compare_and_swap: 1149 case Builtin::BI__sync_val_compare_and_swap_1: 1150 case Builtin::BI__sync_val_compare_and_swap_2: 1151 case Builtin::BI__sync_val_compare_and_swap_4: 1152 case Builtin::BI__sync_val_compare_and_swap_8: 1153 case Builtin::BI__sync_val_compare_and_swap_16: 1154 BuiltinIndex = 10; 1155 NumFixed = 2; 1156 break; 1157 1158 case Builtin::BI__sync_bool_compare_and_swap: 1159 case Builtin::BI__sync_bool_compare_and_swap_1: 1160 case Builtin::BI__sync_bool_compare_and_swap_2: 1161 case Builtin::BI__sync_bool_compare_and_swap_4: 1162 case Builtin::BI__sync_bool_compare_and_swap_8: 1163 case Builtin::BI__sync_bool_compare_and_swap_16: 1164 BuiltinIndex = 11; 1165 NumFixed = 2; 1166 ResultType = Context.BoolTy; 1167 break; 1168 1169 case Builtin::BI__sync_lock_test_and_set: 1170 case Builtin::BI__sync_lock_test_and_set_1: 1171 case Builtin::BI__sync_lock_test_and_set_2: 1172 case Builtin::BI__sync_lock_test_and_set_4: 1173 case Builtin::BI__sync_lock_test_and_set_8: 1174 case Builtin::BI__sync_lock_test_and_set_16: 1175 BuiltinIndex = 12; 1176 break; 1177 1178 case Builtin::BI__sync_lock_release: 1179 case Builtin::BI__sync_lock_release_1: 1180 case Builtin::BI__sync_lock_release_2: 1181 case Builtin::BI__sync_lock_release_4: 1182 case Builtin::BI__sync_lock_release_8: 1183 case Builtin::BI__sync_lock_release_16: 1184 BuiltinIndex = 13; 1185 NumFixed = 0; 1186 ResultType = Context.VoidTy; 1187 break; 1188 1189 case Builtin::BI__sync_swap: 1190 case Builtin::BI__sync_swap_1: 1191 case Builtin::BI__sync_swap_2: 1192 case Builtin::BI__sync_swap_4: 1193 case Builtin::BI__sync_swap_8: 1194 case Builtin::BI__sync_swap_16: 1195 BuiltinIndex = 14; 1196 break; 1197 } 1198 1199 // Now that we know how many fixed arguments we expect, first check that we 1200 // have at least that many. 1201 if (TheCall->getNumArgs() < 1+NumFixed) { 1202 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1203 << 0 << 1+NumFixed << TheCall->getNumArgs() 1204 << TheCall->getCallee()->getSourceRange(); 1205 return ExprError(); 1206 } 1207 1208 // Get the decl for the concrete builtin from this, we can tell what the 1209 // concrete integer type we should convert to is. 1210 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1211 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1212 FunctionDecl *NewBuiltinDecl; 1213 if (NewBuiltinID == BuiltinID) 1214 NewBuiltinDecl = FDecl; 1215 else { 1216 // Perform builtin lookup to avoid redeclaring it. 1217 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 1218 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 1219 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 1220 assert(Res.getFoundDecl()); 1221 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 1222 if (NewBuiltinDecl == 0) 1223 return ExprError(); 1224 } 1225 1226 // The first argument --- the pointer --- has a fixed type; we 1227 // deduce the types of the rest of the arguments accordingly. Walk 1228 // the remaining arguments, converting them to the deduced value type. 1229 for (unsigned i = 0; i != NumFixed; ++i) { 1230 ExprResult Arg = TheCall->getArg(i+1); 1231 1232 // GCC does an implicit conversion to the pointer or integer ValType. This 1233 // can fail in some cases (1i -> int**), check for this error case now. 1234 // Initialize the argument. 1235 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1236 ValType, /*consume*/ false); 1237 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1238 if (Arg.isInvalid()) 1239 return ExprError(); 1240 1241 // Okay, we have something that *can* be converted to the right type. Check 1242 // to see if there is a potentially weird extension going on here. This can 1243 // happen when you do an atomic operation on something like an char* and 1244 // pass in 42. The 42 gets converted to char. This is even more strange 1245 // for things like 45.123 -> char, etc. 1246 // FIXME: Do this check. 1247 TheCall->setArg(i+1, Arg.take()); 1248 } 1249 1250 ASTContext& Context = this->getASTContext(); 1251 1252 // Create a new DeclRefExpr to refer to the new decl. 1253 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1254 Context, 1255 DRE->getQualifierLoc(), 1256 SourceLocation(), 1257 NewBuiltinDecl, 1258 /*enclosing*/ false, 1259 DRE->getLocation(), 1260 Context.BuiltinFnTy, 1261 DRE->getValueKind()); 1262 1263 // Set the callee in the CallExpr. 1264 // FIXME: This loses syntactic information. 1265 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 1266 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 1267 CK_BuiltinFnToFnPtr); 1268 TheCall->setCallee(PromotedCall.take()); 1269 1270 // Change the result type of the call to match the original value type. This 1271 // is arbitrary, but the codegen for these builtins ins design to handle it 1272 // gracefully. 1273 TheCall->setType(ResultType); 1274 1275 return TheCallResult; 1276} 1277 1278/// CheckObjCString - Checks that the argument to the builtin 1279/// CFString constructor is correct 1280/// Note: It might also make sense to do the UTF-16 conversion here (would 1281/// simplify the backend). 1282bool Sema::CheckObjCString(Expr *Arg) { 1283 Arg = Arg->IgnoreParenCasts(); 1284 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1285 1286 if (!Literal || !Literal->isAscii()) { 1287 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1288 << Arg->getSourceRange(); 1289 return true; 1290 } 1291 1292 if (Literal->containsNonAsciiOrNull()) { 1293 StringRef String = Literal->getString(); 1294 unsigned NumBytes = String.size(); 1295 SmallVector<UTF16, 128> ToBuf(NumBytes); 1296 const UTF8 *FromPtr = (const UTF8 *)String.data(); 1297 UTF16 *ToPtr = &ToBuf[0]; 1298 1299 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1300 &ToPtr, ToPtr + NumBytes, 1301 strictConversion); 1302 // Check for conversion failure. 1303 if (Result != conversionOK) 1304 Diag(Arg->getLocStart(), 1305 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1306 } 1307 return false; 1308} 1309 1310/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1311/// Emit an error and return true on failure, return false on success. 1312bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1313 Expr *Fn = TheCall->getCallee(); 1314 if (TheCall->getNumArgs() > 2) { 1315 Diag(TheCall->getArg(2)->getLocStart(), 1316 diag::err_typecheck_call_too_many_args) 1317 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1318 << Fn->getSourceRange() 1319 << SourceRange(TheCall->getArg(2)->getLocStart(), 1320 (*(TheCall->arg_end()-1))->getLocEnd()); 1321 return true; 1322 } 1323 1324 if (TheCall->getNumArgs() < 2) { 1325 return Diag(TheCall->getLocEnd(), 1326 diag::err_typecheck_call_too_few_args_at_least) 1327 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1328 } 1329 1330 // Type-check the first argument normally. 1331 if (checkBuiltinArgument(*this, TheCall, 0)) 1332 return true; 1333 1334 // Determine whether the current function is variadic or not. 1335 BlockScopeInfo *CurBlock = getCurBlock(); 1336 bool isVariadic; 1337 if (CurBlock) 1338 isVariadic = CurBlock->TheDecl->isVariadic(); 1339 else if (FunctionDecl *FD = getCurFunctionDecl()) 1340 isVariadic = FD->isVariadic(); 1341 else 1342 isVariadic = getCurMethodDecl()->isVariadic(); 1343 1344 if (!isVariadic) { 1345 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1346 return true; 1347 } 1348 1349 // Verify that the second argument to the builtin is the last argument of the 1350 // current function or method. 1351 bool SecondArgIsLastNamedArgument = false; 1352 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1353 1354 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1355 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1356 // FIXME: This isn't correct for methods (results in bogus warning). 1357 // Get the last formal in the current function. 1358 const ParmVarDecl *LastArg; 1359 if (CurBlock) 1360 LastArg = *(CurBlock->TheDecl->param_end()-1); 1361 else if (FunctionDecl *FD = getCurFunctionDecl()) 1362 LastArg = *(FD->param_end()-1); 1363 else 1364 LastArg = *(getCurMethodDecl()->param_end()-1); 1365 SecondArgIsLastNamedArgument = PV == LastArg; 1366 } 1367 } 1368 1369 if (!SecondArgIsLastNamedArgument) 1370 Diag(TheCall->getArg(1)->getLocStart(), 1371 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1372 return false; 1373} 1374 1375/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1376/// friends. This is declared to take (...), so we have to check everything. 1377bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1378 if (TheCall->getNumArgs() < 2) 1379 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1380 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1381 if (TheCall->getNumArgs() > 2) 1382 return Diag(TheCall->getArg(2)->getLocStart(), 1383 diag::err_typecheck_call_too_many_args) 1384 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1385 << SourceRange(TheCall->getArg(2)->getLocStart(), 1386 (*(TheCall->arg_end()-1))->getLocEnd()); 1387 1388 ExprResult OrigArg0 = TheCall->getArg(0); 1389 ExprResult OrigArg1 = TheCall->getArg(1); 1390 1391 // Do standard promotions between the two arguments, returning their common 1392 // type. 1393 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1394 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1395 return true; 1396 1397 // Make sure any conversions are pushed back into the call; this is 1398 // type safe since unordered compare builtins are declared as "_Bool 1399 // foo(...)". 1400 TheCall->setArg(0, OrigArg0.get()); 1401 TheCall->setArg(1, OrigArg1.get()); 1402 1403 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1404 return false; 1405 1406 // If the common type isn't a real floating type, then the arguments were 1407 // invalid for this operation. 1408 if (Res.isNull() || !Res->isRealFloatingType()) 1409 return Diag(OrigArg0.get()->getLocStart(), 1410 diag::err_typecheck_call_invalid_ordered_compare) 1411 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1412 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1413 1414 return false; 1415} 1416 1417/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1418/// __builtin_isnan and friends. This is declared to take (...), so we have 1419/// to check everything. We expect the last argument to be a floating point 1420/// value. 1421bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1422 if (TheCall->getNumArgs() < NumArgs) 1423 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1424 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1425 if (TheCall->getNumArgs() > NumArgs) 1426 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1427 diag::err_typecheck_call_too_many_args) 1428 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1429 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1430 (*(TheCall->arg_end()-1))->getLocEnd()); 1431 1432 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1433 1434 if (OrigArg->isTypeDependent()) 1435 return false; 1436 1437 // This operation requires a non-_Complex floating-point number. 1438 if (!OrigArg->getType()->isRealFloatingType()) 1439 return Diag(OrigArg->getLocStart(), 1440 diag::err_typecheck_call_invalid_unary_fp) 1441 << OrigArg->getType() << OrigArg->getSourceRange(); 1442 1443 // If this is an implicit conversion from float -> double, remove it. 1444 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1445 Expr *CastArg = Cast->getSubExpr(); 1446 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1447 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1448 "promotion from float to double is the only expected cast here"); 1449 Cast->setSubExpr(0); 1450 TheCall->setArg(NumArgs-1, CastArg); 1451 } 1452 } 1453 1454 return false; 1455} 1456 1457/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1458// This is declared to take (...), so we have to check everything. 1459ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1460 if (TheCall->getNumArgs() < 2) 1461 return ExprError(Diag(TheCall->getLocEnd(), 1462 diag::err_typecheck_call_too_few_args_at_least) 1463 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1464 << TheCall->getSourceRange()); 1465 1466 // Determine which of the following types of shufflevector we're checking: 1467 // 1) unary, vector mask: (lhs, mask) 1468 // 2) binary, vector mask: (lhs, rhs, mask) 1469 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1470 QualType resType = TheCall->getArg(0)->getType(); 1471 unsigned numElements = 0; 1472 1473 if (!TheCall->getArg(0)->isTypeDependent() && 1474 !TheCall->getArg(1)->isTypeDependent()) { 1475 QualType LHSType = TheCall->getArg(0)->getType(); 1476 QualType RHSType = TheCall->getArg(1)->getType(); 1477 1478 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1479 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1480 << SourceRange(TheCall->getArg(0)->getLocStart(), 1481 TheCall->getArg(1)->getLocEnd()); 1482 return ExprError(); 1483 } 1484 1485 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1486 unsigned numResElements = TheCall->getNumArgs() - 2; 1487 1488 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1489 // with mask. If so, verify that RHS is an integer vector type with the 1490 // same number of elts as lhs. 1491 if (TheCall->getNumArgs() == 2) { 1492 if (!RHSType->hasIntegerRepresentation() || 1493 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1494 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1495 << SourceRange(TheCall->getArg(1)->getLocStart(), 1496 TheCall->getArg(1)->getLocEnd()); 1497 numResElements = numElements; 1498 } 1499 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1500 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1501 << SourceRange(TheCall->getArg(0)->getLocStart(), 1502 TheCall->getArg(1)->getLocEnd()); 1503 return ExprError(); 1504 } else if (numElements != numResElements) { 1505 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1506 resType = Context.getVectorType(eltType, numResElements, 1507 VectorType::GenericVector); 1508 } 1509 } 1510 1511 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1512 if (TheCall->getArg(i)->isTypeDependent() || 1513 TheCall->getArg(i)->isValueDependent()) 1514 continue; 1515 1516 llvm::APSInt Result(32); 1517 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1518 return ExprError(Diag(TheCall->getLocStart(), 1519 diag::err_shufflevector_nonconstant_argument) 1520 << TheCall->getArg(i)->getSourceRange()); 1521 1522 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1523 return ExprError(Diag(TheCall->getLocStart(), 1524 diag::err_shufflevector_argument_too_large) 1525 << TheCall->getArg(i)->getSourceRange()); 1526 } 1527 1528 SmallVector<Expr*, 32> exprs; 1529 1530 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1531 exprs.push_back(TheCall->getArg(i)); 1532 TheCall->setArg(i, 0); 1533 } 1534 1535 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType, 1536 TheCall->getCallee()->getLocStart(), 1537 TheCall->getRParenLoc())); 1538} 1539 1540/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1541// This is declared to take (const void*, ...) and can take two 1542// optional constant int args. 1543bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1544 unsigned NumArgs = TheCall->getNumArgs(); 1545 1546 if (NumArgs > 3) 1547 return Diag(TheCall->getLocEnd(), 1548 diag::err_typecheck_call_too_many_args_at_most) 1549 << 0 /*function call*/ << 3 << NumArgs 1550 << TheCall->getSourceRange(); 1551 1552 // Argument 0 is checked for us and the remaining arguments must be 1553 // constant integers. 1554 for (unsigned i = 1; i != NumArgs; ++i) { 1555 Expr *Arg = TheCall->getArg(i); 1556 1557 // We can't check the value of a dependent argument. 1558 if (Arg->isTypeDependent() || Arg->isValueDependent()) 1559 continue; 1560 1561 llvm::APSInt Result; 1562 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1563 return true; 1564 1565 // FIXME: gcc issues a warning and rewrites these to 0. These 1566 // seems especially odd for the third argument since the default 1567 // is 3. 1568 if (i == 1) { 1569 if (Result.getLimitedValue() > 1) 1570 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1571 << "0" << "1" << Arg->getSourceRange(); 1572 } else { 1573 if (Result.getLimitedValue() > 3) 1574 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1575 << "0" << "3" << Arg->getSourceRange(); 1576 } 1577 } 1578 1579 return false; 1580} 1581 1582/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1583/// TheCall is a constant expression. 1584bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1585 llvm::APSInt &Result) { 1586 Expr *Arg = TheCall->getArg(ArgNum); 1587 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1588 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1589 1590 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1591 1592 if (!Arg->isIntegerConstantExpr(Result, Context)) 1593 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1594 << FDecl->getDeclName() << Arg->getSourceRange(); 1595 1596 return false; 1597} 1598 1599/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1600/// int type). This simply type checks that type is one of the defined 1601/// constants (0-3). 1602// For compatibility check 0-3, llvm only handles 0 and 2. 1603bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1604 llvm::APSInt Result; 1605 1606 // We can't check the value of a dependent argument. 1607 if (TheCall->getArg(1)->isTypeDependent() || 1608 TheCall->getArg(1)->isValueDependent()) 1609 return false; 1610 1611 // Check constant-ness first. 1612 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1613 return true; 1614 1615 Expr *Arg = TheCall->getArg(1); 1616 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1617 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1618 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1619 } 1620 1621 return false; 1622} 1623 1624/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1625/// This checks that val is a constant 1. 1626bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1627 Expr *Arg = TheCall->getArg(1); 1628 llvm::APSInt Result; 1629 1630 // TODO: This is less than ideal. Overload this to take a value. 1631 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1632 return true; 1633 1634 if (Result != 1) 1635 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1636 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1637 1638 return false; 1639} 1640 1641// Determine if an expression is a string literal or constant string. 1642// If this function returns false on the arguments to a function expecting a 1643// format string, we will usually need to emit a warning. 1644// True string literals are then checked by CheckFormatString. 1645Sema::StringLiteralCheckType 1646Sema::checkFormatStringExpr(const Expr *E, Expr **Args, 1647 unsigned NumArgs, bool HasVAListArg, 1648 unsigned format_idx, unsigned firstDataArg, 1649 FormatStringType Type, VariadicCallType CallType, 1650 bool inFunctionCall) { 1651 tryAgain: 1652 if (E->isTypeDependent() || E->isValueDependent()) 1653 return SLCT_NotALiteral; 1654 1655 E = E->IgnoreParenCasts(); 1656 1657 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 1658 // Technically -Wformat-nonliteral does not warn about this case. 1659 // The behavior of printf and friends in this case is implementation 1660 // dependent. Ideally if the format string cannot be null then 1661 // it should have a 'nonnull' attribute in the function prototype. 1662 return SLCT_CheckedLiteral; 1663 1664 switch (E->getStmtClass()) { 1665 case Stmt::BinaryConditionalOperatorClass: 1666 case Stmt::ConditionalOperatorClass: { 1667 // The expression is a literal if both sub-expressions were, and it was 1668 // completely checked only if both sub-expressions were checked. 1669 const AbstractConditionalOperator *C = 1670 cast<AbstractConditionalOperator>(E); 1671 StringLiteralCheckType Left = 1672 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs, 1673 HasVAListArg, format_idx, firstDataArg, 1674 Type, CallType, inFunctionCall); 1675 if (Left == SLCT_NotALiteral) 1676 return SLCT_NotALiteral; 1677 StringLiteralCheckType Right = 1678 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs, 1679 HasVAListArg, format_idx, firstDataArg, 1680 Type, CallType, inFunctionCall); 1681 return Left < Right ? Left : Right; 1682 } 1683 1684 case Stmt::ImplicitCastExprClass: { 1685 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1686 goto tryAgain; 1687 } 1688 1689 case Stmt::OpaqueValueExprClass: 1690 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1691 E = src; 1692 goto tryAgain; 1693 } 1694 return SLCT_NotALiteral; 1695 1696 case Stmt::PredefinedExprClass: 1697 // While __func__, etc., are technically not string literals, they 1698 // cannot contain format specifiers and thus are not a security 1699 // liability. 1700 return SLCT_UncheckedLiteral; 1701 1702 case Stmt::DeclRefExprClass: { 1703 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1704 1705 // As an exception, do not flag errors for variables binding to 1706 // const string literals. 1707 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1708 bool isConstant = false; 1709 QualType T = DR->getType(); 1710 1711 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1712 isConstant = AT->getElementType().isConstant(Context); 1713 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1714 isConstant = T.isConstant(Context) && 1715 PT->getPointeeType().isConstant(Context); 1716 } else if (T->isObjCObjectPointerType()) { 1717 // In ObjC, there is usually no "const ObjectPointer" type, 1718 // so don't check if the pointee type is constant. 1719 isConstant = T.isConstant(Context); 1720 } 1721 1722 if (isConstant) { 1723 if (const Expr *Init = VD->getAnyInitializer()) { 1724 // Look through initializers like const char c[] = { "foo" } 1725 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 1726 if (InitList->isStringLiteralInit()) 1727 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 1728 } 1729 return checkFormatStringExpr(Init, Args, NumArgs, 1730 HasVAListArg, format_idx, 1731 firstDataArg, Type, CallType, 1732 /*inFunctionCall*/false); 1733 } 1734 } 1735 1736 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1737 // special check to see if the format string is a function parameter 1738 // of the function calling the printf function. If the function 1739 // has an attribute indicating it is a printf-like function, then we 1740 // should suppress warnings concerning non-literals being used in a call 1741 // to a vprintf function. For example: 1742 // 1743 // void 1744 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1745 // va_list ap; 1746 // va_start(ap, fmt); 1747 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1748 // ... 1749 // 1750 if (HasVAListArg) { 1751 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 1752 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 1753 int PVIndex = PV->getFunctionScopeIndex() + 1; 1754 for (specific_attr_iterator<FormatAttr> 1755 i = ND->specific_attr_begin<FormatAttr>(), 1756 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) { 1757 FormatAttr *PVFormat = *i; 1758 // adjust for implicit parameter 1759 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1760 if (MD->isInstance()) 1761 ++PVIndex; 1762 // We also check if the formats are compatible. 1763 // We can't pass a 'scanf' string to a 'printf' function. 1764 if (PVIndex == PVFormat->getFormatIdx() && 1765 Type == GetFormatStringType(PVFormat)) 1766 return SLCT_UncheckedLiteral; 1767 } 1768 } 1769 } 1770 } 1771 } 1772 1773 return SLCT_NotALiteral; 1774 } 1775 1776 case Stmt::CallExprClass: 1777 case Stmt::CXXMemberCallExprClass: { 1778 const CallExpr *CE = cast<CallExpr>(E); 1779 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 1780 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 1781 unsigned ArgIndex = FA->getFormatIdx(); 1782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1783 if (MD->isInstance()) 1784 --ArgIndex; 1785 const Expr *Arg = CE->getArg(ArgIndex - 1); 1786 1787 return checkFormatStringExpr(Arg, Args, NumArgs, 1788 HasVAListArg, format_idx, firstDataArg, 1789 Type, CallType, inFunctionCall); 1790 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 1791 unsigned BuiltinID = FD->getBuiltinID(); 1792 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 1793 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 1794 const Expr *Arg = CE->getArg(0); 1795 return checkFormatStringExpr(Arg, Args, NumArgs, 1796 HasVAListArg, format_idx, 1797 firstDataArg, Type, CallType, 1798 inFunctionCall); 1799 } 1800 } 1801 } 1802 1803 return SLCT_NotALiteral; 1804 } 1805 case Stmt::ObjCStringLiteralClass: 1806 case Stmt::StringLiteralClass: { 1807 const StringLiteral *StrE = NULL; 1808 1809 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1810 StrE = ObjCFExpr->getString(); 1811 else 1812 StrE = cast<StringLiteral>(E); 1813 1814 if (StrE) { 1815 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1816 firstDataArg, Type, inFunctionCall, CallType); 1817 return SLCT_CheckedLiteral; 1818 } 1819 1820 return SLCT_NotALiteral; 1821 } 1822 1823 default: 1824 return SLCT_NotALiteral; 1825 } 1826} 1827 1828void 1829Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1830 const Expr * const *ExprArgs, 1831 SourceLocation CallSiteLoc) { 1832 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1833 e = NonNull->args_end(); 1834 i != e; ++i) { 1835 const Expr *ArgExpr = ExprArgs[*i]; 1836 if (ArgExpr->isNullPointerConstant(Context, 1837 Expr::NPC_ValueDependentIsNotNull)) 1838 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1839 } 1840} 1841 1842Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 1843 return llvm::StringSwitch<FormatStringType>(Format->getType()) 1844 .Case("scanf", FST_Scanf) 1845 .Cases("printf", "printf0", FST_Printf) 1846 .Cases("NSString", "CFString", FST_NSString) 1847 .Case("strftime", FST_Strftime) 1848 .Case("strfmon", FST_Strfmon) 1849 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 1850 .Default(FST_Unknown); 1851} 1852 1853/// CheckFormatArguments - Check calls to printf and scanf (and similar 1854/// functions) for correct use of format strings. 1855/// Returns true if a format string has been fully checked. 1856bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1857 unsigned NumArgs, bool IsCXXMember, 1858 VariadicCallType CallType, 1859 SourceLocation Loc, SourceRange Range) { 1860 FormatStringInfo FSI; 1861 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 1862 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx, 1863 FSI.FirstDataArg, GetFormatStringType(Format), 1864 CallType, Loc, Range); 1865 return false; 1866} 1867 1868bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs, 1869 bool HasVAListArg, unsigned format_idx, 1870 unsigned firstDataArg, FormatStringType Type, 1871 VariadicCallType CallType, 1872 SourceLocation Loc, SourceRange Range) { 1873 // CHECK: printf/scanf-like function is called with no format string. 1874 if (format_idx >= NumArgs) { 1875 Diag(Loc, diag::warn_missing_format_string) << Range; 1876 return false; 1877 } 1878 1879 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1880 1881 // CHECK: format string is not a string literal. 1882 // 1883 // Dynamically generated format strings are difficult to 1884 // automatically vet at compile time. Requiring that format strings 1885 // are string literals: (1) permits the checking of format strings by 1886 // the compiler and thereby (2) can practically remove the source of 1887 // many format string exploits. 1888 1889 // Format string can be either ObjC string (e.g. @"%d") or 1890 // C string (e.g. "%d") 1891 // ObjC string uses the same format specifiers as C string, so we can use 1892 // the same format string checking logic for both ObjC and C strings. 1893 StringLiteralCheckType CT = 1894 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1895 format_idx, firstDataArg, Type, CallType); 1896 if (CT != SLCT_NotALiteral) 1897 // Literal format string found, check done! 1898 return CT == SLCT_CheckedLiteral; 1899 1900 // Strftime is particular as it always uses a single 'time' argument, 1901 // so it is safe to pass a non-literal string. 1902 if (Type == FST_Strftime) 1903 return false; 1904 1905 // Do not emit diag when the string param is a macro expansion and the 1906 // format is either NSString or CFString. This is a hack to prevent 1907 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 1908 // which are usually used in place of NS and CF string literals. 1909 if (Type == FST_NSString && 1910 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 1911 return false; 1912 1913 // If there are no arguments specified, warn with -Wformat-security, otherwise 1914 // warn only with -Wformat-nonliteral. 1915 if (NumArgs == format_idx+1) 1916 Diag(Args[format_idx]->getLocStart(), 1917 diag::warn_format_nonliteral_noargs) 1918 << OrigFormatExpr->getSourceRange(); 1919 else 1920 Diag(Args[format_idx]->getLocStart(), 1921 diag::warn_format_nonliteral) 1922 << OrigFormatExpr->getSourceRange(); 1923 return false; 1924} 1925 1926namespace { 1927class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1928protected: 1929 Sema &S; 1930 const StringLiteral *FExpr; 1931 const Expr *OrigFormatExpr; 1932 const unsigned FirstDataArg; 1933 const unsigned NumDataArgs; 1934 const char *Beg; // Start of format string. 1935 const bool HasVAListArg; 1936 const Expr * const *Args; 1937 const unsigned NumArgs; 1938 unsigned FormatIdx; 1939 llvm::BitVector CoveredArgs; 1940 bool usesPositionalArgs; 1941 bool atFirstArg; 1942 bool inFunctionCall; 1943 Sema::VariadicCallType CallType; 1944public: 1945 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1946 const Expr *origFormatExpr, unsigned firstDataArg, 1947 unsigned numDataArgs, const char *beg, bool hasVAListArg, 1948 Expr **args, unsigned numArgs, 1949 unsigned formatIdx, bool inFunctionCall, 1950 Sema::VariadicCallType callType) 1951 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1952 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 1953 Beg(beg), HasVAListArg(hasVAListArg), 1954 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1955 usesPositionalArgs(false), atFirstArg(true), 1956 inFunctionCall(inFunctionCall), CallType(callType) { 1957 CoveredArgs.resize(numDataArgs); 1958 CoveredArgs.reset(); 1959 } 1960 1961 void DoneProcessing(); 1962 1963 void HandleIncompleteSpecifier(const char *startSpecifier, 1964 unsigned specifierLen); 1965 1966 void HandleInvalidLengthModifier( 1967 const analyze_format_string::FormatSpecifier &FS, 1968 const analyze_format_string::ConversionSpecifier &CS, 1969 const char *startSpecifier, unsigned specifierLen, unsigned DiagID); 1970 1971 void HandleNonStandardLengthModifier( 1972 const analyze_format_string::FormatSpecifier &FS, 1973 const char *startSpecifier, unsigned specifierLen); 1974 1975 void HandleNonStandardConversionSpecifier( 1976 const analyze_format_string::ConversionSpecifier &CS, 1977 const char *startSpecifier, unsigned specifierLen); 1978 1979 virtual void HandlePosition(const char *startPos, unsigned posLen); 1980 1981 virtual void HandleInvalidPosition(const char *startSpecifier, 1982 unsigned specifierLen, 1983 analyze_format_string::PositionContext p); 1984 1985 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1986 1987 void HandleNullChar(const char *nullCharacter); 1988 1989 template <typename Range> 1990 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1991 const Expr *ArgumentExpr, 1992 PartialDiagnostic PDiag, 1993 SourceLocation StringLoc, 1994 bool IsStringLocation, Range StringRange, 1995 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>()); 1996 1997protected: 1998 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1999 const char *startSpec, 2000 unsigned specifierLen, 2001 const char *csStart, unsigned csLen); 2002 2003 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 2004 const char *startSpec, 2005 unsigned specifierLen); 2006 2007 SourceRange getFormatStringRange(); 2008 CharSourceRange getSpecifierRange(const char *startSpecifier, 2009 unsigned specifierLen); 2010 SourceLocation getLocationOfByte(const char *x); 2011 2012 const Expr *getDataArg(unsigned i) const; 2013 2014 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 2015 const analyze_format_string::ConversionSpecifier &CS, 2016 const char *startSpecifier, unsigned specifierLen, 2017 unsigned argIndex); 2018 2019 template <typename Range> 2020 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 2021 bool IsStringLocation, Range StringRange, 2022 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>()); 2023 2024 void CheckPositionalAndNonpositionalArgs( 2025 const analyze_format_string::FormatSpecifier *FS); 2026}; 2027} 2028 2029SourceRange CheckFormatHandler::getFormatStringRange() { 2030 return OrigFormatExpr->getSourceRange(); 2031} 2032 2033CharSourceRange CheckFormatHandler:: 2034getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2035 SourceLocation Start = getLocationOfByte(startSpecifier); 2036 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2037 2038 // Advance the end SourceLocation by one due to half-open ranges. 2039 End = End.getLocWithOffset(1); 2040 2041 return CharSourceRange::getCharRange(Start, End); 2042} 2043 2044SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2045 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2046} 2047 2048void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2049 unsigned specifierLen){ 2050 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2051 getLocationOfByte(startSpecifier), 2052 /*IsStringLocation*/true, 2053 getSpecifierRange(startSpecifier, specifierLen)); 2054} 2055 2056void CheckFormatHandler::HandleInvalidLengthModifier( 2057 const analyze_format_string::FormatSpecifier &FS, 2058 const analyze_format_string::ConversionSpecifier &CS, 2059 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 2060 using namespace analyze_format_string; 2061 2062 const LengthModifier &LM = FS.getLengthModifier(); 2063 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2064 2065 // See if we know how to fix this length modifier. 2066 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2067 if (FixedLM) { 2068 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2069 getLocationOfByte(LM.getStart()), 2070 /*IsStringLocation*/true, 2071 getSpecifierRange(startSpecifier, specifierLen)); 2072 2073 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2074 << FixedLM->toString() 2075 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2076 2077 } else { 2078 FixItHint Hint; 2079 if (DiagID == diag::warn_format_nonsensical_length) 2080 Hint = FixItHint::CreateRemoval(LMRange); 2081 2082 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2083 getLocationOfByte(LM.getStart()), 2084 /*IsStringLocation*/true, 2085 getSpecifierRange(startSpecifier, specifierLen), 2086 Hint); 2087 } 2088} 2089 2090void CheckFormatHandler::HandleNonStandardLengthModifier( 2091 const analyze_format_string::FormatSpecifier &FS, 2092 const char *startSpecifier, unsigned specifierLen) { 2093 using namespace analyze_format_string; 2094 2095 const LengthModifier &LM = FS.getLengthModifier(); 2096 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2097 2098 // See if we know how to fix this length modifier. 2099 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2100 if (FixedLM) { 2101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2102 << LM.toString() << 0, 2103 getLocationOfByte(LM.getStart()), 2104 /*IsStringLocation*/true, 2105 getSpecifierRange(startSpecifier, specifierLen)); 2106 2107 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2108 << FixedLM->toString() 2109 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2110 2111 } else { 2112 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2113 << LM.toString() << 0, 2114 getLocationOfByte(LM.getStart()), 2115 /*IsStringLocation*/true, 2116 getSpecifierRange(startSpecifier, specifierLen)); 2117 } 2118} 2119 2120void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2121 const analyze_format_string::ConversionSpecifier &CS, 2122 const char *startSpecifier, unsigned specifierLen) { 2123 using namespace analyze_format_string; 2124 2125 // See if we know how to fix this conversion specifier. 2126 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 2127 if (FixedCS) { 2128 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2129 << CS.toString() << /*conversion specifier*/1, 2130 getLocationOfByte(CS.getStart()), 2131 /*IsStringLocation*/true, 2132 getSpecifierRange(startSpecifier, specifierLen)); 2133 2134 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 2135 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 2136 << FixedCS->toString() 2137 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 2138 } else { 2139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2140 << CS.toString() << /*conversion specifier*/1, 2141 getLocationOfByte(CS.getStart()), 2142 /*IsStringLocation*/true, 2143 getSpecifierRange(startSpecifier, specifierLen)); 2144 } 2145} 2146 2147void CheckFormatHandler::HandlePosition(const char *startPos, 2148 unsigned posLen) { 2149 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2150 getLocationOfByte(startPos), 2151 /*IsStringLocation*/true, 2152 getSpecifierRange(startPos, posLen)); 2153} 2154 2155void 2156CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2157 analyze_format_string::PositionContext p) { 2158 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2159 << (unsigned) p, 2160 getLocationOfByte(startPos), /*IsStringLocation*/true, 2161 getSpecifierRange(startPos, posLen)); 2162} 2163 2164void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2165 unsigned posLen) { 2166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 2167 getLocationOfByte(startPos), 2168 /*IsStringLocation*/true, 2169 getSpecifierRange(startPos, posLen)); 2170} 2171 2172void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 2173 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 2174 // The presence of a null character is likely an error. 2175 EmitFormatDiagnostic( 2176 S.PDiag(diag::warn_printf_format_string_contains_null_char), 2177 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 2178 getFormatStringRange()); 2179 } 2180} 2181 2182// Note that this may return NULL if there was an error parsing or building 2183// one of the argument expressions. 2184const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 2185 return Args[FirstDataArg + i]; 2186} 2187 2188void CheckFormatHandler::DoneProcessing() { 2189 // Does the number of data arguments exceed the number of 2190 // format conversions in the format string? 2191 if (!HasVAListArg) { 2192 // Find any arguments that weren't covered. 2193 CoveredArgs.flip(); 2194 signed notCoveredArg = CoveredArgs.find_first(); 2195 if (notCoveredArg >= 0) { 2196 assert((unsigned)notCoveredArg < NumDataArgs); 2197 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 2198 SourceLocation Loc = E->getLocStart(); 2199 if (!S.getSourceManager().isInSystemMacro(Loc)) { 2200 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 2201 Loc, /*IsStringLocation*/false, 2202 getFormatStringRange()); 2203 } 2204 } 2205 } 2206 } 2207} 2208 2209bool 2210CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 2211 SourceLocation Loc, 2212 const char *startSpec, 2213 unsigned specifierLen, 2214 const char *csStart, 2215 unsigned csLen) { 2216 2217 bool keepGoing = true; 2218 if (argIndex < NumDataArgs) { 2219 // Consider the argument coverered, even though the specifier doesn't 2220 // make sense. 2221 CoveredArgs.set(argIndex); 2222 } 2223 else { 2224 // If argIndex exceeds the number of data arguments we 2225 // don't issue a warning because that is just a cascade of warnings (and 2226 // they may have intended '%%' anyway). We don't want to continue processing 2227 // the format string after this point, however, as we will like just get 2228 // gibberish when trying to match arguments. 2229 keepGoing = false; 2230 } 2231 2232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 2233 << StringRef(csStart, csLen), 2234 Loc, /*IsStringLocation*/true, 2235 getSpecifierRange(startSpec, specifierLen)); 2236 2237 return keepGoing; 2238} 2239 2240void 2241CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 2242 const char *startSpec, 2243 unsigned specifierLen) { 2244 EmitFormatDiagnostic( 2245 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 2246 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 2247} 2248 2249bool 2250CheckFormatHandler::CheckNumArgs( 2251 const analyze_format_string::FormatSpecifier &FS, 2252 const analyze_format_string::ConversionSpecifier &CS, 2253 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 2254 2255 if (argIndex >= NumDataArgs) { 2256 PartialDiagnostic PDiag = FS.usesPositionalArg() 2257 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 2258 << (argIndex+1) << NumDataArgs) 2259 : S.PDiag(diag::warn_printf_insufficient_data_args); 2260 EmitFormatDiagnostic( 2261 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 2262 getSpecifierRange(startSpecifier, specifierLen)); 2263 return false; 2264 } 2265 return true; 2266} 2267 2268template<typename Range> 2269void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 2270 SourceLocation Loc, 2271 bool IsStringLocation, 2272 Range StringRange, 2273 ArrayRef<FixItHint> FixIt) { 2274 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 2275 Loc, IsStringLocation, StringRange, FixIt); 2276} 2277 2278/// \brief If the format string is not within the funcion call, emit a note 2279/// so that the function call and string are in diagnostic messages. 2280/// 2281/// \param InFunctionCall if true, the format string is within the function 2282/// call and only one diagnostic message will be produced. Otherwise, an 2283/// extra note will be emitted pointing to location of the format string. 2284/// 2285/// \param ArgumentExpr the expression that is passed as the format string 2286/// argument in the function call. Used for getting locations when two 2287/// diagnostics are emitted. 2288/// 2289/// \param PDiag the callee should already have provided any strings for the 2290/// diagnostic message. This function only adds locations and fixits 2291/// to diagnostics. 2292/// 2293/// \param Loc primary location for diagnostic. If two diagnostics are 2294/// required, one will be at Loc and a new SourceLocation will be created for 2295/// the other one. 2296/// 2297/// \param IsStringLocation if true, Loc points to the format string should be 2298/// used for the note. Otherwise, Loc points to the argument list and will 2299/// be used with PDiag. 2300/// 2301/// \param StringRange some or all of the string to highlight. This is 2302/// templated so it can accept either a CharSourceRange or a SourceRange. 2303/// 2304/// \param FixIt optional fix it hint for the format string. 2305template<typename Range> 2306void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 2307 const Expr *ArgumentExpr, 2308 PartialDiagnostic PDiag, 2309 SourceLocation Loc, 2310 bool IsStringLocation, 2311 Range StringRange, 2312 ArrayRef<FixItHint> FixIt) { 2313 if (InFunctionCall) { 2314 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 2315 D << StringRange; 2316 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2317 I != E; ++I) { 2318 D << *I; 2319 } 2320 } else { 2321 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 2322 << ArgumentExpr->getSourceRange(); 2323 2324 const Sema::SemaDiagnosticBuilder &Note = 2325 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 2326 diag::note_format_string_defined); 2327 2328 Note << StringRange; 2329 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end(); 2330 I != E; ++I) { 2331 Note << *I; 2332 } 2333 } 2334} 2335 2336//===--- CHECK: Printf format string checking ------------------------------===// 2337 2338namespace { 2339class CheckPrintfHandler : public CheckFormatHandler { 2340 bool ObjCContext; 2341public: 2342 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 2343 const Expr *origFormatExpr, unsigned firstDataArg, 2344 unsigned numDataArgs, bool isObjC, 2345 const char *beg, bool hasVAListArg, 2346 Expr **Args, unsigned NumArgs, 2347 unsigned formatIdx, bool inFunctionCall, 2348 Sema::VariadicCallType CallType) 2349 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2350 numDataArgs, beg, hasVAListArg, Args, NumArgs, 2351 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC) 2352 {} 2353 2354 2355 bool HandleInvalidPrintfConversionSpecifier( 2356 const analyze_printf::PrintfSpecifier &FS, 2357 const char *startSpecifier, 2358 unsigned specifierLen); 2359 2360 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 2361 const char *startSpecifier, 2362 unsigned specifierLen); 2363 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2364 const char *StartSpecifier, 2365 unsigned SpecifierLen, 2366 const Expr *E); 2367 2368 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 2369 const char *startSpecifier, unsigned specifierLen); 2370 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 2371 const analyze_printf::OptionalAmount &Amt, 2372 unsigned type, 2373 const char *startSpecifier, unsigned specifierLen); 2374 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2375 const analyze_printf::OptionalFlag &flag, 2376 const char *startSpecifier, unsigned specifierLen); 2377 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 2378 const analyze_printf::OptionalFlag &ignoredFlag, 2379 const analyze_printf::OptionalFlag &flag, 2380 const char *startSpecifier, unsigned specifierLen); 2381 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 2382 const Expr *E, const CharSourceRange &CSR); 2383 2384}; 2385} 2386 2387bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 2388 const analyze_printf::PrintfSpecifier &FS, 2389 const char *startSpecifier, 2390 unsigned specifierLen) { 2391 const analyze_printf::PrintfConversionSpecifier &CS = 2392 FS.getConversionSpecifier(); 2393 2394 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2395 getLocationOfByte(CS.getStart()), 2396 startSpecifier, specifierLen, 2397 CS.getStart(), CS.getLength()); 2398} 2399 2400bool CheckPrintfHandler::HandleAmount( 2401 const analyze_format_string::OptionalAmount &Amt, 2402 unsigned k, const char *startSpecifier, 2403 unsigned specifierLen) { 2404 2405 if (Amt.hasDataArgument()) { 2406 if (!HasVAListArg) { 2407 unsigned argIndex = Amt.getArgIndex(); 2408 if (argIndex >= NumDataArgs) { 2409 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 2410 << k, 2411 getLocationOfByte(Amt.getStart()), 2412 /*IsStringLocation*/true, 2413 getSpecifierRange(startSpecifier, specifierLen)); 2414 // Don't do any more checking. We will just emit 2415 // spurious errors. 2416 return false; 2417 } 2418 2419 // Type check the data argument. It should be an 'int'. 2420 // Although not in conformance with C99, we also allow the argument to be 2421 // an 'unsigned int' as that is a reasonably safe case. GCC also 2422 // doesn't emit a warning for that case. 2423 CoveredArgs.set(argIndex); 2424 const Expr *Arg = getDataArg(argIndex); 2425 if (!Arg) 2426 return false; 2427 2428 QualType T = Arg->getType(); 2429 2430 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 2431 assert(AT.isValid()); 2432 2433 if (!AT.matchesType(S.Context, T)) { 2434 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2435 << k << AT.getRepresentativeTypeName(S.Context) 2436 << T << Arg->getSourceRange(), 2437 getLocationOfByte(Amt.getStart()), 2438 /*IsStringLocation*/true, 2439 getSpecifierRange(startSpecifier, specifierLen)); 2440 // Don't do any more checking. We will just emit 2441 // spurious errors. 2442 return false; 2443 } 2444 } 2445 } 2446 return true; 2447} 2448 2449void CheckPrintfHandler::HandleInvalidAmount( 2450 const analyze_printf::PrintfSpecifier &FS, 2451 const analyze_printf::OptionalAmount &Amt, 2452 unsigned type, 2453 const char *startSpecifier, 2454 unsigned specifierLen) { 2455 const analyze_printf::PrintfConversionSpecifier &CS = 2456 FS.getConversionSpecifier(); 2457 2458 FixItHint fixit = 2459 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2460 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2461 Amt.getConstantLength())) 2462 : FixItHint(); 2463 2464 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2465 << type << CS.toString(), 2466 getLocationOfByte(Amt.getStart()), 2467 /*IsStringLocation*/true, 2468 getSpecifierRange(startSpecifier, specifierLen), 2469 fixit); 2470} 2471 2472void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2473 const analyze_printf::OptionalFlag &flag, 2474 const char *startSpecifier, 2475 unsigned specifierLen) { 2476 // Warn about pointless flag with a fixit removal. 2477 const analyze_printf::PrintfConversionSpecifier &CS = 2478 FS.getConversionSpecifier(); 2479 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2480 << flag.toString() << CS.toString(), 2481 getLocationOfByte(flag.getPosition()), 2482 /*IsStringLocation*/true, 2483 getSpecifierRange(startSpecifier, specifierLen), 2484 FixItHint::CreateRemoval( 2485 getSpecifierRange(flag.getPosition(), 1))); 2486} 2487 2488void CheckPrintfHandler::HandleIgnoredFlag( 2489 const analyze_printf::PrintfSpecifier &FS, 2490 const analyze_printf::OptionalFlag &ignoredFlag, 2491 const analyze_printf::OptionalFlag &flag, 2492 const char *startSpecifier, 2493 unsigned specifierLen) { 2494 // Warn about ignored flag with a fixit removal. 2495 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2496 << ignoredFlag.toString() << flag.toString(), 2497 getLocationOfByte(ignoredFlag.getPosition()), 2498 /*IsStringLocation*/true, 2499 getSpecifierRange(startSpecifier, specifierLen), 2500 FixItHint::CreateRemoval( 2501 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2502} 2503 2504// Determines if the specified is a C++ class or struct containing 2505// a member with the specified name and kind (e.g. a CXXMethodDecl named 2506// "c_str()"). 2507template<typename MemberKind> 2508static llvm::SmallPtrSet<MemberKind*, 1> 2509CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 2510 const RecordType *RT = Ty->getAs<RecordType>(); 2511 llvm::SmallPtrSet<MemberKind*, 1> Results; 2512 2513 if (!RT) 2514 return Results; 2515 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 2516 if (!RD) 2517 return Results; 2518 2519 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(), 2520 Sema::LookupMemberName); 2521 2522 // We just need to include all members of the right kind turned up by the 2523 // filter, at this point. 2524 if (S.LookupQualifiedName(R, RT->getDecl())) 2525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2526 NamedDecl *decl = (*I)->getUnderlyingDecl(); 2527 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 2528 Results.insert(FK); 2529 } 2530 return Results; 2531} 2532 2533// Check if a (w)string was passed when a (w)char* was needed, and offer a 2534// better diagnostic if so. AT is assumed to be valid. 2535// Returns true when a c_str() conversion method is found. 2536bool CheckPrintfHandler::checkForCStrMembers( 2537 const analyze_printf::ArgType &AT, const Expr *E, 2538 const CharSourceRange &CSR) { 2539 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 2540 2541 MethodSet Results = 2542 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 2543 2544 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 2545 MI != ME; ++MI) { 2546 const CXXMethodDecl *Method = *MI; 2547 if (Method->getNumParams() == 0 && 2548 AT.matchesType(S.Context, Method->getResultType())) { 2549 // FIXME: Suggest parens if the expression needs them. 2550 SourceLocation EndLoc = 2551 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()); 2552 S.Diag(E->getLocStart(), diag::note_printf_c_str) 2553 << "c_str()" 2554 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 2555 return true; 2556 } 2557 } 2558 2559 return false; 2560} 2561 2562bool 2563CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2564 &FS, 2565 const char *startSpecifier, 2566 unsigned specifierLen) { 2567 2568 using namespace analyze_format_string; 2569 using namespace analyze_printf; 2570 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2571 2572 if (FS.consumesDataArgument()) { 2573 if (atFirstArg) { 2574 atFirstArg = false; 2575 usesPositionalArgs = FS.usesPositionalArg(); 2576 } 2577 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2578 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2579 startSpecifier, specifierLen); 2580 return false; 2581 } 2582 } 2583 2584 // First check if the field width, precision, and conversion specifier 2585 // have matching data arguments. 2586 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2587 startSpecifier, specifierLen)) { 2588 return false; 2589 } 2590 2591 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2592 startSpecifier, specifierLen)) { 2593 return false; 2594 } 2595 2596 if (!CS.consumesDataArgument()) { 2597 // FIXME: Technically specifying a precision or field width here 2598 // makes no sense. Worth issuing a warning at some point. 2599 return true; 2600 } 2601 2602 // Consume the argument. 2603 unsigned argIndex = FS.getArgIndex(); 2604 if (argIndex < NumDataArgs) { 2605 // The check to see if the argIndex is valid will come later. 2606 // We set the bit here because we may exit early from this 2607 // function if we encounter some other error. 2608 CoveredArgs.set(argIndex); 2609 } 2610 2611 // Check for using an Objective-C specific conversion specifier 2612 // in a non-ObjC literal. 2613 if (!ObjCContext && CS.isObjCArg()) { 2614 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2615 specifierLen); 2616 } 2617 2618 // Check for invalid use of field width 2619 if (!FS.hasValidFieldWidth()) { 2620 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2621 startSpecifier, specifierLen); 2622 } 2623 2624 // Check for invalid use of precision 2625 if (!FS.hasValidPrecision()) { 2626 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2627 startSpecifier, specifierLen); 2628 } 2629 2630 // Check each flag does not conflict with any other component. 2631 if (!FS.hasValidThousandsGroupingPrefix()) 2632 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2633 if (!FS.hasValidLeadingZeros()) 2634 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2635 if (!FS.hasValidPlusPrefix()) 2636 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2637 if (!FS.hasValidSpacePrefix()) 2638 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2639 if (!FS.hasValidAlternativeForm()) 2640 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2641 if (!FS.hasValidLeftJustified()) 2642 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2643 2644 // Check that flags are not ignored by another flag 2645 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2646 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2647 startSpecifier, specifierLen); 2648 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2649 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2650 startSpecifier, specifierLen); 2651 2652 // Check the length modifier is valid with the given conversion specifier. 2653 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 2654 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 2655 diag::warn_format_nonsensical_length); 2656 else if (!FS.hasStandardLengthModifier()) 2657 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 2658 else if (!FS.hasStandardLengthConversionCombination()) 2659 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 2660 diag::warn_format_non_standard_conversion_spec); 2661 2662 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2663 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2664 2665 // The remaining checks depend on the data arguments. 2666 if (HasVAListArg) 2667 return true; 2668 2669 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2670 return false; 2671 2672 const Expr *Arg = getDataArg(argIndex); 2673 if (!Arg) 2674 return true; 2675 2676 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 2677} 2678 2679static bool requiresParensToAddCast(const Expr *E) { 2680 // FIXME: We should have a general way to reason about operator 2681 // precedence and whether parens are actually needed here. 2682 // Take care of a few common cases where they aren't. 2683 const Expr *Inside = E->IgnoreImpCasts(); 2684 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 2685 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 2686 2687 switch (Inside->getStmtClass()) { 2688 case Stmt::ArraySubscriptExprClass: 2689 case Stmt::CallExprClass: 2690 case Stmt::DeclRefExprClass: 2691 case Stmt::MemberExprClass: 2692 case Stmt::ObjCIvarRefExprClass: 2693 case Stmt::ObjCMessageExprClass: 2694 case Stmt::ObjCPropertyRefExprClass: 2695 case Stmt::ParenExprClass: 2696 case Stmt::UnaryOperatorClass: 2697 return false; 2698 default: 2699 return true; 2700 } 2701} 2702 2703bool 2704CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 2705 const char *StartSpecifier, 2706 unsigned SpecifierLen, 2707 const Expr *E) { 2708 using namespace analyze_format_string; 2709 using namespace analyze_printf; 2710 // Now type check the data expression that matches the 2711 // format specifier. 2712 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 2713 ObjCContext); 2714 if (!AT.isValid()) 2715 return true; 2716 2717 QualType IntendedTy = E->getType(); 2718 if (AT.matchesType(S.Context, IntendedTy)) 2719 return true; 2720 2721 // Look through argument promotions for our error message's reported type. 2722 // This includes the integral and floating promotions, but excludes array 2723 // and function pointer decay; seeing that an argument intended to be a 2724 // string has type 'char [6]' is probably more confusing than 'char *'. 2725 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 2726 if (ICE->getCastKind() == CK_IntegralCast || 2727 ICE->getCastKind() == CK_FloatingCast) { 2728 E = ICE->getSubExpr(); 2729 IntendedTy = E->getType(); 2730 2731 // Check if we didn't match because of an implicit cast from a 'char' 2732 // or 'short' to an 'int'. This is done because printf is a varargs 2733 // function. 2734 if (ICE->getType() == S.Context.IntTy || 2735 ICE->getType() == S.Context.UnsignedIntTy) { 2736 // All further checking is done on the subexpression. 2737 if (AT.matchesType(S.Context, IntendedTy)) 2738 return true; 2739 } 2740 } 2741 } 2742 2743 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 2744 // Special-case some of Darwin's platform-independence types. 2745 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) { 2746 StringRef Name = UserTy->getDecl()->getName(); 2747 IntendedTy = llvm::StringSwitch<QualType>(Name) 2748 .Case("NSInteger", S.Context.LongTy) 2749 .Case("NSUInteger", S.Context.UnsignedLongTy) 2750 .Case("SInt32", S.Context.IntTy) 2751 .Case("UInt32", S.Context.UnsignedIntTy) 2752 .Default(IntendedTy); 2753 } 2754 } 2755 2756 // We may be able to offer a FixItHint if it is a supported type. 2757 PrintfSpecifier fixedFS = FS; 2758 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 2759 S.Context, ObjCContext); 2760 2761 if (success) { 2762 // Get the fix string from the fixed format specifier 2763 SmallString<16> buf; 2764 llvm::raw_svector_ostream os(buf); 2765 fixedFS.toString(os); 2766 2767 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 2768 2769 if (IntendedTy != E->getType()) { 2770 // The canonical type for formatting this value is different from the 2771 // actual type of the expression. (This occurs, for example, with Darwin's 2772 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 2773 // should be printed as 'long' for 64-bit compatibility.) 2774 // Rather than emitting a normal format/argument mismatch, we want to 2775 // add a cast to the recommended type (and correct the format string 2776 // if necessary). 2777 SmallString<16> CastBuf; 2778 llvm::raw_svector_ostream CastFix(CastBuf); 2779 CastFix << "("; 2780 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 2781 CastFix << ")"; 2782 2783 SmallVector<FixItHint,4> Hints; 2784 if (!AT.matchesType(S.Context, IntendedTy)) 2785 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 2786 2787 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 2788 // If there's already a cast present, just replace it. 2789 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 2790 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 2791 2792 } else if (!requiresParensToAddCast(E)) { 2793 // If the expression has high enough precedence, 2794 // just write the C-style cast. 2795 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 2796 CastFix.str())); 2797 } else { 2798 // Otherwise, add parens around the expression as well as the cast. 2799 CastFix << "("; 2800 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 2801 CastFix.str())); 2802 2803 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd()); 2804 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 2805 } 2806 2807 // We extract the name from the typedef because we don't want to show 2808 // the underlying type in the diagnostic. 2809 const TypedefType *UserTy = cast<TypedefType>(E->getType()); 2810 StringRef Name = UserTy->getDecl()->getName(); 2811 2812 // Finally, emit the diagnostic. 2813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 2814 << Name << IntendedTy 2815 << E->getSourceRange(), 2816 E->getLocStart(), /*IsStringLocation=*/false, 2817 SpecRange, Hints); 2818 } else { 2819 EmitFormatDiagnostic( 2820 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2821 << AT.getRepresentativeTypeName(S.Context) << IntendedTy 2822 << E->getSourceRange(), 2823 E->getLocStart(), 2824 /*IsStringLocation*/false, 2825 SpecRange, 2826 FixItHint::CreateReplacement(SpecRange, os.str())); 2827 } 2828 } else { 2829 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 2830 SpecifierLen); 2831 // Since the warning for passing non-POD types to variadic functions 2832 // was deferred until now, we emit a warning for non-POD 2833 // arguments here. 2834 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) { 2835 unsigned DiagKind; 2836 if (E->getType()->isObjCObjectType()) 2837 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format; 2838 else 2839 DiagKind = diag::warn_non_pod_vararg_with_format_string; 2840 2841 EmitFormatDiagnostic( 2842 S.PDiag(DiagKind) 2843 << S.getLangOpts().CPlusPlus0x 2844 << E->getType() 2845 << CallType 2846 << AT.getRepresentativeTypeName(S.Context) 2847 << CSR 2848 << E->getSourceRange(), 2849 E->getLocStart(), /*IsStringLocation*/false, CSR); 2850 2851 checkForCStrMembers(AT, E, CSR); 2852 } else 2853 EmitFormatDiagnostic( 2854 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2855 << AT.getRepresentativeTypeName(S.Context) << E->getType() 2856 << CSR 2857 << E->getSourceRange(), 2858 E->getLocStart(), /*IsStringLocation*/false, CSR); 2859 } 2860 2861 return true; 2862} 2863 2864//===--- CHECK: Scanf format string checking ------------------------------===// 2865 2866namespace { 2867class CheckScanfHandler : public CheckFormatHandler { 2868public: 2869 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2870 const Expr *origFormatExpr, unsigned firstDataArg, 2871 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2872 Expr **Args, unsigned NumArgs, 2873 unsigned formatIdx, bool inFunctionCall, 2874 Sema::VariadicCallType CallType) 2875 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2876 numDataArgs, beg, hasVAListArg, 2877 Args, NumArgs, formatIdx, inFunctionCall, CallType) 2878 {} 2879 2880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2881 const char *startSpecifier, 2882 unsigned specifierLen); 2883 2884 bool HandleInvalidScanfConversionSpecifier( 2885 const analyze_scanf::ScanfSpecifier &FS, 2886 const char *startSpecifier, 2887 unsigned specifierLen); 2888 2889 void HandleIncompleteScanList(const char *start, const char *end); 2890}; 2891} 2892 2893void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2894 const char *end) { 2895 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2896 getLocationOfByte(end), /*IsStringLocation*/true, 2897 getSpecifierRange(start, end - start)); 2898} 2899 2900bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2901 const analyze_scanf::ScanfSpecifier &FS, 2902 const char *startSpecifier, 2903 unsigned specifierLen) { 2904 2905 const analyze_scanf::ScanfConversionSpecifier &CS = 2906 FS.getConversionSpecifier(); 2907 2908 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2909 getLocationOfByte(CS.getStart()), 2910 startSpecifier, specifierLen, 2911 CS.getStart(), CS.getLength()); 2912} 2913 2914bool CheckScanfHandler::HandleScanfSpecifier( 2915 const analyze_scanf::ScanfSpecifier &FS, 2916 const char *startSpecifier, 2917 unsigned specifierLen) { 2918 2919 using namespace analyze_scanf; 2920 using namespace analyze_format_string; 2921 2922 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2923 2924 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2925 // be used to decide if we are using positional arguments consistently. 2926 if (FS.consumesDataArgument()) { 2927 if (atFirstArg) { 2928 atFirstArg = false; 2929 usesPositionalArgs = FS.usesPositionalArg(); 2930 } 2931 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2932 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2933 startSpecifier, specifierLen); 2934 return false; 2935 } 2936 } 2937 2938 // Check if the field with is non-zero. 2939 const OptionalAmount &Amt = FS.getFieldWidth(); 2940 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2941 if (Amt.getConstantAmount() == 0) { 2942 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2943 Amt.getConstantLength()); 2944 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2945 getLocationOfByte(Amt.getStart()), 2946 /*IsStringLocation*/true, R, 2947 FixItHint::CreateRemoval(R)); 2948 } 2949 } 2950 2951 if (!FS.consumesDataArgument()) { 2952 // FIXME: Technically specifying a precision or field width here 2953 // makes no sense. Worth issuing a warning at some point. 2954 return true; 2955 } 2956 2957 // Consume the argument. 2958 unsigned argIndex = FS.getArgIndex(); 2959 if (argIndex < NumDataArgs) { 2960 // The check to see if the argIndex is valid will come later. 2961 // We set the bit here because we may exit early from this 2962 // function if we encounter some other error. 2963 CoveredArgs.set(argIndex); 2964 } 2965 2966 // Check the length modifier is valid with the given conversion specifier. 2967 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 2968 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 2969 diag::warn_format_nonsensical_length); 2970 else if (!FS.hasStandardLengthModifier()) 2971 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 2972 else if (!FS.hasStandardLengthConversionCombination()) 2973 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 2974 diag::warn_format_non_standard_conversion_spec); 2975 2976 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 2977 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 2978 2979 // The remaining checks depend on the data arguments. 2980 if (HasVAListArg) 2981 return true; 2982 2983 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2984 return false; 2985 2986 // Check that the argument type matches the format specifier. 2987 const Expr *Ex = getDataArg(argIndex); 2988 if (!Ex) 2989 return true; 2990 2991 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 2992 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) { 2993 ScanfSpecifier fixedFS = FS; 2994 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(), 2995 S.Context); 2996 2997 if (success) { 2998 // Get the fix string from the fixed format specifier. 2999 SmallString<128> buf; 3000 llvm::raw_svector_ostream os(buf); 3001 fixedFS.toString(os); 3002 3003 EmitFormatDiagnostic( 3004 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3005 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3006 << Ex->getSourceRange(), 3007 Ex->getLocStart(), 3008 /*IsStringLocation*/false, 3009 getSpecifierRange(startSpecifier, specifierLen), 3010 FixItHint::CreateReplacement( 3011 getSpecifierRange(startSpecifier, specifierLen), 3012 os.str())); 3013 } else { 3014 EmitFormatDiagnostic( 3015 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 3016 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3017 << Ex->getSourceRange(), 3018 Ex->getLocStart(), 3019 /*IsStringLocation*/false, 3020 getSpecifierRange(startSpecifier, specifierLen)); 3021 } 3022 } 3023 3024 return true; 3025} 3026 3027void Sema::CheckFormatString(const StringLiteral *FExpr, 3028 const Expr *OrigFormatExpr, 3029 Expr **Args, unsigned NumArgs, 3030 bool HasVAListArg, unsigned format_idx, 3031 unsigned firstDataArg, FormatStringType Type, 3032 bool inFunctionCall, VariadicCallType CallType) { 3033 3034 // CHECK: is the format string a wide literal? 3035 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 3036 CheckFormatHandler::EmitFormatDiagnostic( 3037 *this, inFunctionCall, Args[format_idx], 3038 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 3039 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3040 return; 3041 } 3042 3043 // Str - The format string. NOTE: this is NOT null-terminated! 3044 StringRef StrRef = FExpr->getString(); 3045 const char *Str = StrRef.data(); 3046 unsigned StrLen = StrRef.size(); 3047 const unsigned numDataArgs = NumArgs - firstDataArg; 3048 3049 // CHECK: empty format string? 3050 if (StrLen == 0 && numDataArgs > 0) { 3051 CheckFormatHandler::EmitFormatDiagnostic( 3052 *this, inFunctionCall, Args[format_idx], 3053 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 3054 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 3055 return; 3056 } 3057 3058 if (Type == FST_Printf || Type == FST_NSString) { 3059 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 3060 numDataArgs, (Type == FST_NSString), 3061 Str, HasVAListArg, Args, NumArgs, format_idx, 3062 inFunctionCall, CallType); 3063 3064 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 3065 getLangOpts(), 3066 Context.getTargetInfo())) 3067 H.DoneProcessing(); 3068 } else if (Type == FST_Scanf) { 3069 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 3070 Str, HasVAListArg, Args, NumArgs, format_idx, 3071 inFunctionCall, CallType); 3072 3073 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 3074 getLangOpts(), 3075 Context.getTargetInfo())) 3076 H.DoneProcessing(); 3077 } // TODO: handle other formats 3078} 3079 3080//===--- CHECK: Standard memory functions ---------------------------------===// 3081 3082/// \brief Determine whether the given type is a dynamic class type (e.g., 3083/// whether it has a vtable). 3084static bool isDynamicClassType(QualType T) { 3085 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3086 if (CXXRecordDecl *Definition = Record->getDefinition()) 3087 if (Definition->isDynamicClass()) 3088 return true; 3089 3090 return false; 3091} 3092 3093/// \brief If E is a sizeof expression, returns its argument expression, 3094/// otherwise returns NULL. 3095static const Expr *getSizeOfExprArg(const Expr* E) { 3096 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3097 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3098 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 3099 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 3100 3101 return 0; 3102} 3103 3104/// \brief If E is a sizeof expression, returns its argument type. 3105static QualType getSizeOfArgType(const Expr* E) { 3106 if (const UnaryExprOrTypeTraitExpr *SizeOf = 3107 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 3108 if (SizeOf->getKind() == clang::UETT_SizeOf) 3109 return SizeOf->getTypeOfArgument(); 3110 3111 return QualType(); 3112} 3113 3114/// \brief Check for dangerous or invalid arguments to memset(). 3115/// 3116/// This issues warnings on known problematic, dangerous or unspecified 3117/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 3118/// function calls. 3119/// 3120/// \param Call The call expression to diagnose. 3121void Sema::CheckMemaccessArguments(const CallExpr *Call, 3122 unsigned BId, 3123 IdentifierInfo *FnName) { 3124 assert(BId != 0); 3125 3126 // It is possible to have a non-standard definition of memset. Validate 3127 // we have enough arguments, and if not, abort further checking. 3128 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 3129 if (Call->getNumArgs() < ExpectedNumArgs) 3130 return; 3131 3132 unsigned LastArg = (BId == Builtin::BImemset || 3133 BId == Builtin::BIstrndup ? 1 : 2); 3134 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 3135 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 3136 3137 // We have special checking when the length is a sizeof expression. 3138 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 3139 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 3140 llvm::FoldingSetNodeID SizeOfArgID; 3141 3142 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 3143 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 3144 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 3145 3146 QualType DestTy = Dest->getType(); 3147 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 3148 QualType PointeeTy = DestPtrTy->getPointeeType(); 3149 3150 // Never warn about void type pointers. This can be used to suppress 3151 // false positives. 3152 if (PointeeTy->isVoidType()) 3153 continue; 3154 3155 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 3156 // actually comparing the expressions for equality. Because computing the 3157 // expression IDs can be expensive, we only do this if the diagnostic is 3158 // enabled. 3159 if (SizeOfArg && 3160 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 3161 SizeOfArg->getExprLoc())) { 3162 // We only compute IDs for expressions if the warning is enabled, and 3163 // cache the sizeof arg's ID. 3164 if (SizeOfArgID == llvm::FoldingSetNodeID()) 3165 SizeOfArg->Profile(SizeOfArgID, Context, true); 3166 llvm::FoldingSetNodeID DestID; 3167 Dest->Profile(DestID, Context, true); 3168 if (DestID == SizeOfArgID) { 3169 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 3170 // over sizeof(src) as well. 3171 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 3172 StringRef ReadableName = FnName->getName(); 3173 3174 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 3175 if (UnaryOp->getOpcode() == UO_AddrOf) 3176 ActionIdx = 1; // If its an address-of operator, just remove it. 3177 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 3178 ActionIdx = 2; // If the pointee's size is sizeof(char), 3179 // suggest an explicit length. 3180 3181 // If the function is defined as a builtin macro, do not show macro 3182 // expansion. 3183 SourceLocation SL = SizeOfArg->getExprLoc(); 3184 SourceRange DSR = Dest->getSourceRange(); 3185 SourceRange SSR = SizeOfArg->getSourceRange(); 3186 SourceManager &SM = PP.getSourceManager(); 3187 3188 if (SM.isMacroArgExpansion(SL)) { 3189 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 3190 SL = SM.getSpellingLoc(SL); 3191 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 3192 SM.getSpellingLoc(DSR.getEnd())); 3193 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 3194 SM.getSpellingLoc(SSR.getEnd())); 3195 } 3196 3197 DiagRuntimeBehavior(SL, SizeOfArg, 3198 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 3199 << ReadableName 3200 << PointeeTy 3201 << DestTy 3202 << DSR 3203 << SSR); 3204 DiagRuntimeBehavior(SL, SizeOfArg, 3205 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 3206 << ActionIdx 3207 << SSR); 3208 3209 break; 3210 } 3211 } 3212 3213 // Also check for cases where the sizeof argument is the exact same 3214 // type as the memory argument, and where it points to a user-defined 3215 // record type. 3216 if (SizeOfArgTy != QualType()) { 3217 if (PointeeTy->isRecordType() && 3218 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 3219 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 3220 PDiag(diag::warn_sizeof_pointer_type_memaccess) 3221 << FnName << SizeOfArgTy << ArgIdx 3222 << PointeeTy << Dest->getSourceRange() 3223 << LenExpr->getSourceRange()); 3224 break; 3225 } 3226 } 3227 3228 // Always complain about dynamic classes. 3229 if (isDynamicClassType(PointeeTy)) { 3230 3231 unsigned OperationType = 0; 3232 // "overwritten" if we're warning about the destination for any call 3233 // but memcmp; otherwise a verb appropriate to the call. 3234 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 3235 if (BId == Builtin::BImemcpy) 3236 OperationType = 1; 3237 else if(BId == Builtin::BImemmove) 3238 OperationType = 2; 3239 else if (BId == Builtin::BImemcmp) 3240 OperationType = 3; 3241 } 3242 3243 DiagRuntimeBehavior( 3244 Dest->getExprLoc(), Dest, 3245 PDiag(diag::warn_dyn_class_memaccess) 3246 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 3247 << FnName << PointeeTy 3248 << OperationType 3249 << Call->getCallee()->getSourceRange()); 3250 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 3251 BId != Builtin::BImemset) 3252 DiagRuntimeBehavior( 3253 Dest->getExprLoc(), Dest, 3254 PDiag(diag::warn_arc_object_memaccess) 3255 << ArgIdx << FnName << PointeeTy 3256 << Call->getCallee()->getSourceRange()); 3257 else 3258 continue; 3259 3260 DiagRuntimeBehavior( 3261 Dest->getExprLoc(), Dest, 3262 PDiag(diag::note_bad_memaccess_silence) 3263 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 3264 break; 3265 } 3266 } 3267} 3268 3269// A little helper routine: ignore addition and subtraction of integer literals. 3270// This intentionally does not ignore all integer constant expressions because 3271// we don't want to remove sizeof(). 3272static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 3273 Ex = Ex->IgnoreParenCasts(); 3274 3275 for (;;) { 3276 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 3277 if (!BO || !BO->isAdditiveOp()) 3278 break; 3279 3280 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 3281 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 3282 3283 if (isa<IntegerLiteral>(RHS)) 3284 Ex = LHS; 3285 else if (isa<IntegerLiteral>(LHS)) 3286 Ex = RHS; 3287 else 3288 break; 3289 } 3290 3291 return Ex; 3292} 3293 3294static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 3295 ASTContext &Context) { 3296 // Only handle constant-sized or VLAs, but not flexible members. 3297 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 3298 // Only issue the FIXIT for arrays of size > 1. 3299 if (CAT->getSize().getSExtValue() <= 1) 3300 return false; 3301 } else if (!Ty->isVariableArrayType()) { 3302 return false; 3303 } 3304 return true; 3305} 3306 3307// Warn if the user has made the 'size' argument to strlcpy or strlcat 3308// be the size of the source, instead of the destination. 3309void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 3310 IdentifierInfo *FnName) { 3311 3312 // Don't crash if the user has the wrong number of arguments 3313 if (Call->getNumArgs() != 3) 3314 return; 3315 3316 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 3317 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 3318 const Expr *CompareWithSrc = NULL; 3319 3320 // Look for 'strlcpy(dst, x, sizeof(x))' 3321 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 3322 CompareWithSrc = Ex; 3323 else { 3324 // Look for 'strlcpy(dst, x, strlen(x))' 3325 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 3326 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 3327 && SizeCall->getNumArgs() == 1) 3328 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 3329 } 3330 } 3331 3332 if (!CompareWithSrc) 3333 return; 3334 3335 // Determine if the argument to sizeof/strlen is equal to the source 3336 // argument. In principle there's all kinds of things you could do 3337 // here, for instance creating an == expression and evaluating it with 3338 // EvaluateAsBooleanCondition, but this uses a more direct technique: 3339 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 3340 if (!SrcArgDRE) 3341 return; 3342 3343 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 3344 if (!CompareWithSrcDRE || 3345 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 3346 return; 3347 3348 const Expr *OriginalSizeArg = Call->getArg(2); 3349 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 3350 << OriginalSizeArg->getSourceRange() << FnName; 3351 3352 // Output a FIXIT hint if the destination is an array (rather than a 3353 // pointer to an array). This could be enhanced to handle some 3354 // pointers if we know the actual size, like if DstArg is 'array+2' 3355 // we could say 'sizeof(array)-2'. 3356 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 3357 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 3358 return; 3359 3360 SmallString<128> sizeString; 3361 llvm::raw_svector_ostream OS(sizeString); 3362 OS << "sizeof("; 3363 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3364 OS << ")"; 3365 3366 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 3367 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 3368 OS.str()); 3369} 3370 3371/// Check if two expressions refer to the same declaration. 3372static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 3373 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 3374 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 3375 return D1->getDecl() == D2->getDecl(); 3376 return false; 3377} 3378 3379static const Expr *getStrlenExprArg(const Expr *E) { 3380 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 3381 const FunctionDecl *FD = CE->getDirectCallee(); 3382 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 3383 return 0; 3384 return CE->getArg(0)->IgnoreParenCasts(); 3385 } 3386 return 0; 3387} 3388 3389// Warn on anti-patterns as the 'size' argument to strncat. 3390// The correct size argument should look like following: 3391// strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 3392void Sema::CheckStrncatArguments(const CallExpr *CE, 3393 IdentifierInfo *FnName) { 3394 // Don't crash if the user has the wrong number of arguments. 3395 if (CE->getNumArgs() < 3) 3396 return; 3397 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 3398 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 3399 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 3400 3401 // Identify common expressions, which are wrongly used as the size argument 3402 // to strncat and may lead to buffer overflows. 3403 unsigned PatternType = 0; 3404 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 3405 // - sizeof(dst) 3406 if (referToTheSameDecl(SizeOfArg, DstArg)) 3407 PatternType = 1; 3408 // - sizeof(src) 3409 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 3410 PatternType = 2; 3411 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 3412 if (BE->getOpcode() == BO_Sub) { 3413 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 3414 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 3415 // - sizeof(dst) - strlen(dst) 3416 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 3417 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 3418 PatternType = 1; 3419 // - sizeof(src) - (anything) 3420 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 3421 PatternType = 2; 3422 } 3423 } 3424 3425 if (PatternType == 0) 3426 return; 3427 3428 // Generate the diagnostic. 3429 SourceLocation SL = LenArg->getLocStart(); 3430 SourceRange SR = LenArg->getSourceRange(); 3431 SourceManager &SM = PP.getSourceManager(); 3432 3433 // If the function is defined as a builtin macro, do not show macro expansion. 3434 if (SM.isMacroArgExpansion(SL)) { 3435 SL = SM.getSpellingLoc(SL); 3436 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 3437 SM.getSpellingLoc(SR.getEnd())); 3438 } 3439 3440 // Check if the destination is an array (rather than a pointer to an array). 3441 QualType DstTy = DstArg->getType(); 3442 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 3443 Context); 3444 if (!isKnownSizeArray) { 3445 if (PatternType == 1) 3446 Diag(SL, diag::warn_strncat_wrong_size) << SR; 3447 else 3448 Diag(SL, diag::warn_strncat_src_size) << SR; 3449 return; 3450 } 3451 3452 if (PatternType == 1) 3453 Diag(SL, diag::warn_strncat_large_size) << SR; 3454 else 3455 Diag(SL, diag::warn_strncat_src_size) << SR; 3456 3457 SmallString<128> sizeString; 3458 llvm::raw_svector_ostream OS(sizeString); 3459 OS << "sizeof("; 3460 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3461 OS << ") - "; 3462 OS << "strlen("; 3463 DstArg->printPretty(OS, 0, getPrintingPolicy()); 3464 OS << ") - 1"; 3465 3466 Diag(SL, diag::note_strncat_wrong_size) 3467 << FixItHint::CreateReplacement(SR, OS.str()); 3468} 3469 3470//===--- CHECK: Return Address of Stack Variable --------------------------===// 3471 3472static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3473 Decl *ParentDecl); 3474static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 3475 Decl *ParentDecl); 3476 3477/// CheckReturnStackAddr - Check if a return statement returns the address 3478/// of a stack variable. 3479void 3480Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 3481 SourceLocation ReturnLoc) { 3482 3483 Expr *stackE = 0; 3484 SmallVector<DeclRefExpr *, 8> refVars; 3485 3486 // Perform checking for returned stack addresses, local blocks, 3487 // label addresses or references to temporaries. 3488 if (lhsType->isPointerType() || 3489 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 3490 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0); 3491 } else if (lhsType->isReferenceType()) { 3492 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0); 3493 } 3494 3495 if (stackE == 0) 3496 return; // Nothing suspicious was found. 3497 3498 SourceLocation diagLoc; 3499 SourceRange diagRange; 3500 if (refVars.empty()) { 3501 diagLoc = stackE->getLocStart(); 3502 diagRange = stackE->getSourceRange(); 3503 } else { 3504 // We followed through a reference variable. 'stackE' contains the 3505 // problematic expression but we will warn at the return statement pointing 3506 // at the reference variable. We will later display the "trail" of 3507 // reference variables using notes. 3508 diagLoc = refVars[0]->getLocStart(); 3509 diagRange = refVars[0]->getSourceRange(); 3510 } 3511 3512 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 3513 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 3514 : diag::warn_ret_stack_addr) 3515 << DR->getDecl()->getDeclName() << diagRange; 3516 } else if (isa<BlockExpr>(stackE)) { // local block. 3517 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 3518 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 3519 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 3520 } else { // local temporary. 3521 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 3522 : diag::warn_ret_local_temp_addr) 3523 << diagRange; 3524 } 3525 3526 // Display the "trail" of reference variables that we followed until we 3527 // found the problematic expression using notes. 3528 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 3529 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 3530 // If this var binds to another reference var, show the range of the next 3531 // var, otherwise the var binds to the problematic expression, in which case 3532 // show the range of the expression. 3533 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 3534 : stackE->getSourceRange(); 3535 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 3536 << VD->getDeclName() << range; 3537 } 3538} 3539 3540/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 3541/// check if the expression in a return statement evaluates to an address 3542/// to a location on the stack, a local block, an address of a label, or a 3543/// reference to local temporary. The recursion is used to traverse the 3544/// AST of the return expression, with recursion backtracking when we 3545/// encounter a subexpression that (1) clearly does not lead to one of the 3546/// above problematic expressions (2) is something we cannot determine leads to 3547/// a problematic expression based on such local checking. 3548/// 3549/// Both EvalAddr and EvalVal follow through reference variables to evaluate 3550/// the expression that they point to. Such variables are added to the 3551/// 'refVars' vector so that we know what the reference variable "trail" was. 3552/// 3553/// EvalAddr processes expressions that are pointers that are used as 3554/// references (and not L-values). EvalVal handles all other values. 3555/// At the base case of the recursion is a check for the above problematic 3556/// expressions. 3557/// 3558/// This implementation handles: 3559/// 3560/// * pointer-to-pointer casts 3561/// * implicit conversions from array references to pointers 3562/// * taking the address of fields 3563/// * arbitrary interplay between "&" and "*" operators 3564/// * pointer arithmetic from an address of a stack variable 3565/// * taking the address of an array element where the array is on the stack 3566static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3567 Decl *ParentDecl) { 3568 if (E->isTypeDependent()) 3569 return NULL; 3570 3571 // We should only be called for evaluating pointer expressions. 3572 assert((E->getType()->isAnyPointerType() || 3573 E->getType()->isBlockPointerType() || 3574 E->getType()->isObjCQualifiedIdType()) && 3575 "EvalAddr only works on pointers"); 3576 3577 E = E->IgnoreParens(); 3578 3579 // Our "symbolic interpreter" is just a dispatch off the currently 3580 // viewed AST node. We then recursively traverse the AST by calling 3581 // EvalAddr and EvalVal appropriately. 3582 switch (E->getStmtClass()) { 3583 case Stmt::DeclRefExprClass: { 3584 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3585 3586 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 3587 // If this is a reference variable, follow through to the expression that 3588 // it points to. 3589 if (V->hasLocalStorage() && 3590 V->getType()->isReferenceType() && V->hasInit()) { 3591 // Add the reference variable to the "trail". 3592 refVars.push_back(DR); 3593 return EvalAddr(V->getInit(), refVars, ParentDecl); 3594 } 3595 3596 return NULL; 3597 } 3598 3599 case Stmt::UnaryOperatorClass: { 3600 // The only unary operator that make sense to handle here 3601 // is AddrOf. All others don't make sense as pointers. 3602 UnaryOperator *U = cast<UnaryOperator>(E); 3603 3604 if (U->getOpcode() == UO_AddrOf) 3605 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 3606 else 3607 return NULL; 3608 } 3609 3610 case Stmt::BinaryOperatorClass: { 3611 // Handle pointer arithmetic. All other binary operators are not valid 3612 // in this context. 3613 BinaryOperator *B = cast<BinaryOperator>(E); 3614 BinaryOperatorKind op = B->getOpcode(); 3615 3616 if (op != BO_Add && op != BO_Sub) 3617 return NULL; 3618 3619 Expr *Base = B->getLHS(); 3620 3621 // Determine which argument is the real pointer base. It could be 3622 // the RHS argument instead of the LHS. 3623 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 3624 3625 assert (Base->getType()->isPointerType()); 3626 return EvalAddr(Base, refVars, ParentDecl); 3627 } 3628 3629 // For conditional operators we need to see if either the LHS or RHS are 3630 // valid DeclRefExpr*s. If one of them is valid, we return it. 3631 case Stmt::ConditionalOperatorClass: { 3632 ConditionalOperator *C = cast<ConditionalOperator>(E); 3633 3634 // Handle the GNU extension for missing LHS. 3635 if (Expr *lhsExpr = C->getLHS()) { 3636 // In C++, we can have a throw-expression, which has 'void' type. 3637 if (!lhsExpr->getType()->isVoidType()) 3638 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl)) 3639 return LHS; 3640 } 3641 3642 // In C++, we can have a throw-expression, which has 'void' type. 3643 if (C->getRHS()->getType()->isVoidType()) 3644 return NULL; 3645 3646 return EvalAddr(C->getRHS(), refVars, ParentDecl); 3647 } 3648 3649 case Stmt::BlockExprClass: 3650 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 3651 return E; // local block. 3652 return NULL; 3653 3654 case Stmt::AddrLabelExprClass: 3655 return E; // address of label. 3656 3657 case Stmt::ExprWithCleanupsClass: 3658 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 3659 ParentDecl); 3660 3661 // For casts, we need to handle conversions from arrays to 3662 // pointer values, and pointer-to-pointer conversions. 3663 case Stmt::ImplicitCastExprClass: 3664 case Stmt::CStyleCastExprClass: 3665 case Stmt::CXXFunctionalCastExprClass: 3666 case Stmt::ObjCBridgedCastExprClass: 3667 case Stmt::CXXStaticCastExprClass: 3668 case Stmt::CXXDynamicCastExprClass: 3669 case Stmt::CXXConstCastExprClass: 3670 case Stmt::CXXReinterpretCastExprClass: { 3671 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 3672 switch (cast<CastExpr>(E)->getCastKind()) { 3673 case CK_BitCast: 3674 case CK_LValueToRValue: 3675 case CK_NoOp: 3676 case CK_BaseToDerived: 3677 case CK_DerivedToBase: 3678 case CK_UncheckedDerivedToBase: 3679 case CK_Dynamic: 3680 case CK_CPointerToObjCPointerCast: 3681 case CK_BlockPointerToObjCPointerCast: 3682 case CK_AnyPointerToBlockPointerCast: 3683 return EvalAddr(SubExpr, refVars, ParentDecl); 3684 3685 case CK_ArrayToPointerDecay: 3686 return EvalVal(SubExpr, refVars, ParentDecl); 3687 3688 default: 3689 return 0; 3690 } 3691 } 3692 3693 case Stmt::MaterializeTemporaryExprClass: 3694 if (Expr *Result = EvalAddr( 3695 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3696 refVars, ParentDecl)) 3697 return Result; 3698 3699 return E; 3700 3701 // Everything else: we simply don't reason about them. 3702 default: 3703 return NULL; 3704 } 3705} 3706 3707 3708/// EvalVal - This function is complements EvalAddr in the mutual recursion. 3709/// See the comments for EvalAddr for more details. 3710static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 3711 Decl *ParentDecl) { 3712do { 3713 // We should only be called for evaluating non-pointer expressions, or 3714 // expressions with a pointer type that are not used as references but instead 3715 // are l-values (e.g., DeclRefExpr with a pointer type). 3716 3717 // Our "symbolic interpreter" is just a dispatch off the currently 3718 // viewed AST node. We then recursively traverse the AST by calling 3719 // EvalAddr and EvalVal appropriately. 3720 3721 E = E->IgnoreParens(); 3722 switch (E->getStmtClass()) { 3723 case Stmt::ImplicitCastExprClass: { 3724 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 3725 if (IE->getValueKind() == VK_LValue) { 3726 E = IE->getSubExpr(); 3727 continue; 3728 } 3729 return NULL; 3730 } 3731 3732 case Stmt::ExprWithCleanupsClass: 3733 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 3734 3735 case Stmt::DeclRefExprClass: { 3736 // When we hit a DeclRefExpr we are looking at code that refers to a 3737 // variable's name. If it's not a reference variable we check if it has 3738 // local storage within the function, and if so, return the expression. 3739 DeclRefExpr *DR = cast<DeclRefExpr>(E); 3740 3741 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 3742 // Check if it refers to itself, e.g. "int& i = i;". 3743 if (V == ParentDecl) 3744 return DR; 3745 3746 if (V->hasLocalStorage()) { 3747 if (!V->getType()->isReferenceType()) 3748 return DR; 3749 3750 // Reference variable, follow through to the expression that 3751 // it points to. 3752 if (V->hasInit()) { 3753 // Add the reference variable to the "trail". 3754 refVars.push_back(DR); 3755 return EvalVal(V->getInit(), refVars, V); 3756 } 3757 } 3758 } 3759 3760 return NULL; 3761 } 3762 3763 case Stmt::UnaryOperatorClass: { 3764 // The only unary operator that make sense to handle here 3765 // is Deref. All others don't resolve to a "name." This includes 3766 // handling all sorts of rvalues passed to a unary operator. 3767 UnaryOperator *U = cast<UnaryOperator>(E); 3768 3769 if (U->getOpcode() == UO_Deref) 3770 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 3771 3772 return NULL; 3773 } 3774 3775 case Stmt::ArraySubscriptExprClass: { 3776 // Array subscripts are potential references to data on the stack. We 3777 // retrieve the DeclRefExpr* for the array variable if it indeed 3778 // has local storage. 3779 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 3780 } 3781 3782 case Stmt::ConditionalOperatorClass: { 3783 // For conditional operators we need to see if either the LHS or RHS are 3784 // non-NULL Expr's. If one is non-NULL, we return it. 3785 ConditionalOperator *C = cast<ConditionalOperator>(E); 3786 3787 // Handle the GNU extension for missing LHS. 3788 if (Expr *lhsExpr = C->getLHS()) 3789 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl)) 3790 return LHS; 3791 3792 return EvalVal(C->getRHS(), refVars, ParentDecl); 3793 } 3794 3795 // Accesses to members are potential references to data on the stack. 3796 case Stmt::MemberExprClass: { 3797 MemberExpr *M = cast<MemberExpr>(E); 3798 3799 // Check for indirect access. We only want direct field accesses. 3800 if (M->isArrow()) 3801 return NULL; 3802 3803 // Check whether the member type is itself a reference, in which case 3804 // we're not going to refer to the member, but to what the member refers to. 3805 if (M->getMemberDecl()->getType()->isReferenceType()) 3806 return NULL; 3807 3808 return EvalVal(M->getBase(), refVars, ParentDecl); 3809 } 3810 3811 case Stmt::MaterializeTemporaryExprClass: 3812 if (Expr *Result = EvalVal( 3813 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3814 refVars, ParentDecl)) 3815 return Result; 3816 3817 return E; 3818 3819 default: 3820 // Check that we don't return or take the address of a reference to a 3821 // temporary. This is only useful in C++. 3822 if (!E->isTypeDependent() && E->isRValue()) 3823 return E; 3824 3825 // Everything else: we simply don't reason about them. 3826 return NULL; 3827 } 3828} while (true); 3829} 3830 3831//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3832 3833/// Check for comparisons of floating point operands using != and ==. 3834/// Issue a warning if these are no self-comparisons, as they are not likely 3835/// to do what the programmer intended. 3836void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3837 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3838 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3839 3840 // Special case: check for x == x (which is OK). 3841 // Do not emit warnings for such cases. 3842 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3843 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3844 if (DRL->getDecl() == DRR->getDecl()) 3845 return; 3846 3847 3848 // Special case: check for comparisons against literals that can be exactly 3849 // represented by APFloat. In such cases, do not emit a warning. This 3850 // is a heuristic: often comparison against such literals are used to 3851 // detect if a value in a variable has not changed. This clearly can 3852 // lead to false negatives. 3853 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3854 if (FLL->isExact()) 3855 return; 3856 } else 3857 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 3858 if (FLR->isExact()) 3859 return; 3860 3861 // Check for comparisons with builtin types. 3862 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3863 if (CL->isBuiltinCall()) 3864 return; 3865 3866 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3867 if (CR->isBuiltinCall()) 3868 return; 3869 3870 // Emit the diagnostic. 3871 Diag(Loc, diag::warn_floatingpoint_eq) 3872 << LHS->getSourceRange() << RHS->getSourceRange(); 3873} 3874 3875//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3876//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3877 3878namespace { 3879 3880/// Structure recording the 'active' range of an integer-valued 3881/// expression. 3882struct IntRange { 3883 /// The number of bits active in the int. 3884 unsigned Width; 3885 3886 /// True if the int is known not to have negative values. 3887 bool NonNegative; 3888 3889 IntRange(unsigned Width, bool NonNegative) 3890 : Width(Width), NonNegative(NonNegative) 3891 {} 3892 3893 /// Returns the range of the bool type. 3894 static IntRange forBoolType() { 3895 return IntRange(1, true); 3896 } 3897 3898 /// Returns the range of an opaque value of the given integral type. 3899 static IntRange forValueOfType(ASTContext &C, QualType T) { 3900 return forValueOfCanonicalType(C, 3901 T->getCanonicalTypeInternal().getTypePtr()); 3902 } 3903 3904 /// Returns the range of an opaque value of a canonical integral type. 3905 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3906 assert(T->isCanonicalUnqualified()); 3907 3908 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3909 T = VT->getElementType().getTypePtr(); 3910 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3911 T = CT->getElementType().getTypePtr(); 3912 3913 // For enum types, use the known bit width of the enumerators. 3914 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3915 EnumDecl *Enum = ET->getDecl(); 3916 if (!Enum->isCompleteDefinition()) 3917 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3918 3919 unsigned NumPositive = Enum->getNumPositiveBits(); 3920 unsigned NumNegative = Enum->getNumNegativeBits(); 3921 3922 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3923 } 3924 3925 const BuiltinType *BT = cast<BuiltinType>(T); 3926 assert(BT->isInteger()); 3927 3928 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3929 } 3930 3931 /// Returns the "target" range of a canonical integral type, i.e. 3932 /// the range of values expressible in the type. 3933 /// 3934 /// This matches forValueOfCanonicalType except that enums have the 3935 /// full range of their type, not the range of their enumerators. 3936 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3937 assert(T->isCanonicalUnqualified()); 3938 3939 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3940 T = VT->getElementType().getTypePtr(); 3941 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3942 T = CT->getElementType().getTypePtr(); 3943 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3944 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3945 3946 const BuiltinType *BT = cast<BuiltinType>(T); 3947 assert(BT->isInteger()); 3948 3949 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3950 } 3951 3952 /// Returns the supremum of two ranges: i.e. their conservative merge. 3953 static IntRange join(IntRange L, IntRange R) { 3954 return IntRange(std::max(L.Width, R.Width), 3955 L.NonNegative && R.NonNegative); 3956 } 3957 3958 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3959 static IntRange meet(IntRange L, IntRange R) { 3960 return IntRange(std::min(L.Width, R.Width), 3961 L.NonNegative || R.NonNegative); 3962 } 3963}; 3964 3965static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 3966 unsigned MaxWidth) { 3967 if (value.isSigned() && value.isNegative()) 3968 return IntRange(value.getMinSignedBits(), false); 3969 3970 if (value.getBitWidth() > MaxWidth) 3971 value = value.trunc(MaxWidth); 3972 3973 // isNonNegative() just checks the sign bit without considering 3974 // signedness. 3975 return IntRange(value.getActiveBits(), true); 3976} 3977 3978static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3979 unsigned MaxWidth) { 3980 if (result.isInt()) 3981 return GetValueRange(C, result.getInt(), MaxWidth); 3982 3983 if (result.isVector()) { 3984 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3985 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3986 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3987 R = IntRange::join(R, El); 3988 } 3989 return R; 3990 } 3991 3992 if (result.isComplexInt()) { 3993 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3994 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3995 return IntRange::join(R, I); 3996 } 3997 3998 // This can happen with lossless casts to intptr_t of "based" lvalues. 3999 // Assume it might use arbitrary bits. 4000 // FIXME: The only reason we need to pass the type in here is to get 4001 // the sign right on this one case. It would be nice if APValue 4002 // preserved this. 4003 assert(result.isLValue() || result.isAddrLabelDiff()); 4004 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 4005} 4006 4007/// Pseudo-evaluate the given integer expression, estimating the 4008/// range of values it might take. 4009/// 4010/// \param MaxWidth - the width to which the value will be truncated 4011static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 4012 E = E->IgnoreParens(); 4013 4014 // Try a full evaluation first. 4015 Expr::EvalResult result; 4016 if (E->EvaluateAsRValue(result, C)) 4017 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 4018 4019 // I think we only want to look through implicit casts here; if the 4020 // user has an explicit widening cast, we should treat the value as 4021 // being of the new, wider type. 4022 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 4023 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 4024 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 4025 4026 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 4027 4028 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 4029 4030 // Assume that non-integer casts can span the full range of the type. 4031 if (!isIntegerCast) 4032 return OutputTypeRange; 4033 4034 IntRange SubRange 4035 = GetExprRange(C, CE->getSubExpr(), 4036 std::min(MaxWidth, OutputTypeRange.Width)); 4037 4038 // Bail out if the subexpr's range is as wide as the cast type. 4039 if (SubRange.Width >= OutputTypeRange.Width) 4040 return OutputTypeRange; 4041 4042 // Otherwise, we take the smaller width, and we're non-negative if 4043 // either the output type or the subexpr is. 4044 return IntRange(SubRange.Width, 4045 SubRange.NonNegative || OutputTypeRange.NonNegative); 4046 } 4047 4048 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 4049 // If we can fold the condition, just take that operand. 4050 bool CondResult; 4051 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 4052 return GetExprRange(C, CondResult ? CO->getTrueExpr() 4053 : CO->getFalseExpr(), 4054 MaxWidth); 4055 4056 // Otherwise, conservatively merge. 4057 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 4058 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 4059 return IntRange::join(L, R); 4060 } 4061 4062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4063 switch (BO->getOpcode()) { 4064 4065 // Boolean-valued operations are single-bit and positive. 4066 case BO_LAnd: 4067 case BO_LOr: 4068 case BO_LT: 4069 case BO_GT: 4070 case BO_LE: 4071 case BO_GE: 4072 case BO_EQ: 4073 case BO_NE: 4074 return IntRange::forBoolType(); 4075 4076 // The type of the assignments is the type of the LHS, so the RHS 4077 // is not necessarily the same type. 4078 case BO_MulAssign: 4079 case BO_DivAssign: 4080 case BO_RemAssign: 4081 case BO_AddAssign: 4082 case BO_SubAssign: 4083 case BO_XorAssign: 4084 case BO_OrAssign: 4085 // TODO: bitfields? 4086 return IntRange::forValueOfType(C, E->getType()); 4087 4088 // Simple assignments just pass through the RHS, which will have 4089 // been coerced to the LHS type. 4090 case BO_Assign: 4091 // TODO: bitfields? 4092 return GetExprRange(C, BO->getRHS(), MaxWidth); 4093 4094 // Operations with opaque sources are black-listed. 4095 case BO_PtrMemD: 4096 case BO_PtrMemI: 4097 return IntRange::forValueOfType(C, E->getType()); 4098 4099 // Bitwise-and uses the *infinum* of the two source ranges. 4100 case BO_And: 4101 case BO_AndAssign: 4102 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 4103 GetExprRange(C, BO->getRHS(), MaxWidth)); 4104 4105 // Left shift gets black-listed based on a judgement call. 4106 case BO_Shl: 4107 // ...except that we want to treat '1 << (blah)' as logically 4108 // positive. It's an important idiom. 4109 if (IntegerLiteral *I 4110 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 4111 if (I->getValue() == 1) { 4112 IntRange R = IntRange::forValueOfType(C, E->getType()); 4113 return IntRange(R.Width, /*NonNegative*/ true); 4114 } 4115 } 4116 // fallthrough 4117 4118 case BO_ShlAssign: 4119 return IntRange::forValueOfType(C, E->getType()); 4120 4121 // Right shift by a constant can narrow its left argument. 4122 case BO_Shr: 4123 case BO_ShrAssign: { 4124 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4125 4126 // If the shift amount is a positive constant, drop the width by 4127 // that much. 4128 llvm::APSInt shift; 4129 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 4130 shift.isNonNegative()) { 4131 unsigned zext = shift.getZExtValue(); 4132 if (zext >= L.Width) 4133 L.Width = (L.NonNegative ? 0 : 1); 4134 else 4135 L.Width -= zext; 4136 } 4137 4138 return L; 4139 } 4140 4141 // Comma acts as its right operand. 4142 case BO_Comma: 4143 return GetExprRange(C, BO->getRHS(), MaxWidth); 4144 4145 // Black-list pointer subtractions. 4146 case BO_Sub: 4147 if (BO->getLHS()->getType()->isPointerType()) 4148 return IntRange::forValueOfType(C, E->getType()); 4149 break; 4150 4151 // The width of a division result is mostly determined by the size 4152 // of the LHS. 4153 case BO_Div: { 4154 // Don't 'pre-truncate' the operands. 4155 unsigned opWidth = C.getIntWidth(E->getType()); 4156 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4157 4158 // If the divisor is constant, use that. 4159 llvm::APSInt divisor; 4160 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 4161 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 4162 if (log2 >= L.Width) 4163 L.Width = (L.NonNegative ? 0 : 1); 4164 else 4165 L.Width = std::min(L.Width - log2, MaxWidth); 4166 return L; 4167 } 4168 4169 // Otherwise, just use the LHS's width. 4170 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4171 return IntRange(L.Width, L.NonNegative && R.NonNegative); 4172 } 4173 4174 // The result of a remainder can't be larger than the result of 4175 // either side. 4176 case BO_Rem: { 4177 // Don't 'pre-truncate' the operands. 4178 unsigned opWidth = C.getIntWidth(E->getType()); 4179 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 4180 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 4181 4182 IntRange meet = IntRange::meet(L, R); 4183 meet.Width = std::min(meet.Width, MaxWidth); 4184 return meet; 4185 } 4186 4187 // The default behavior is okay for these. 4188 case BO_Mul: 4189 case BO_Add: 4190 case BO_Xor: 4191 case BO_Or: 4192 break; 4193 } 4194 4195 // The default case is to treat the operation as if it were closed 4196 // on the narrowest type that encompasses both operands. 4197 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 4198 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 4199 return IntRange::join(L, R); 4200 } 4201 4202 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 4203 switch (UO->getOpcode()) { 4204 // Boolean-valued operations are white-listed. 4205 case UO_LNot: 4206 return IntRange::forBoolType(); 4207 4208 // Operations with opaque sources are black-listed. 4209 case UO_Deref: 4210 case UO_AddrOf: // should be impossible 4211 return IntRange::forValueOfType(C, E->getType()); 4212 4213 default: 4214 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 4215 } 4216 } 4217 4218 if (dyn_cast<OffsetOfExpr>(E)) { 4219 IntRange::forValueOfType(C, E->getType()); 4220 } 4221 4222 if (FieldDecl *BitField = E->getBitField()) 4223 return IntRange(BitField->getBitWidthValue(C), 4224 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 4225 4226 return IntRange::forValueOfType(C, E->getType()); 4227} 4228 4229static IntRange GetExprRange(ASTContext &C, Expr *E) { 4230 return GetExprRange(C, E, C.getIntWidth(E->getType())); 4231} 4232 4233/// Checks whether the given value, which currently has the given 4234/// source semantics, has the same value when coerced through the 4235/// target semantics. 4236static bool IsSameFloatAfterCast(const llvm::APFloat &value, 4237 const llvm::fltSemantics &Src, 4238 const llvm::fltSemantics &Tgt) { 4239 llvm::APFloat truncated = value; 4240 4241 bool ignored; 4242 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 4243 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 4244 4245 return truncated.bitwiseIsEqual(value); 4246} 4247 4248/// Checks whether the given value, which currently has the given 4249/// source semantics, has the same value when coerced through the 4250/// target semantics. 4251/// 4252/// The value might be a vector of floats (or a complex number). 4253static bool IsSameFloatAfterCast(const APValue &value, 4254 const llvm::fltSemantics &Src, 4255 const llvm::fltSemantics &Tgt) { 4256 if (value.isFloat()) 4257 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 4258 4259 if (value.isVector()) { 4260 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 4261 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 4262 return false; 4263 return true; 4264 } 4265 4266 assert(value.isComplexFloat()); 4267 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 4268 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 4269} 4270 4271static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 4272 4273static bool IsZero(Sema &S, Expr *E) { 4274 // Suppress cases where we are comparing against an enum constant. 4275 if (const DeclRefExpr *DR = 4276 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 4277 if (isa<EnumConstantDecl>(DR->getDecl())) 4278 return false; 4279 4280 // Suppress cases where the '0' value is expanded from a macro. 4281 if (E->getLocStart().isMacroID()) 4282 return false; 4283 4284 llvm::APSInt Value; 4285 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 4286} 4287 4288static bool HasEnumType(Expr *E) { 4289 // Strip off implicit integral promotions. 4290 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4291 if (ICE->getCastKind() != CK_IntegralCast && 4292 ICE->getCastKind() != CK_NoOp) 4293 break; 4294 E = ICE->getSubExpr(); 4295 } 4296 4297 return E->getType()->isEnumeralType(); 4298} 4299 4300static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 4301 BinaryOperatorKind op = E->getOpcode(); 4302 if (E->isValueDependent()) 4303 return; 4304 4305 if (op == BO_LT && IsZero(S, E->getRHS())) { 4306 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4307 << "< 0" << "false" << HasEnumType(E->getLHS()) 4308 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4309 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 4310 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 4311 << ">= 0" << "true" << HasEnumType(E->getLHS()) 4312 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4313 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 4314 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4315 << "0 >" << "false" << HasEnumType(E->getRHS()) 4316 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4317 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 4318 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 4319 << "0 <=" << "true" << HasEnumType(E->getRHS()) 4320 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4321 } 4322} 4323 4324static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 4325 Expr *Constant, Expr *Other, 4326 llvm::APSInt Value, 4327 bool RhsConstant) { 4328 BinaryOperatorKind op = E->getOpcode(); 4329 QualType OtherT = Other->getType(); 4330 QualType ConstantT = Constant->getType(); 4331 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 4332 return; 4333 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) 4334 && "comparison with non-integer type"); 4335 // FIXME. handle cases for signedness to catch (signed char)N == 200 4336 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 4337 IntRange LitRange = GetValueRange(S.Context, Value, Value.getBitWidth()); 4338 if (OtherRange.Width >= LitRange.Width) 4339 return; 4340 bool IsTrue = true; 4341 if (op == BO_EQ) 4342 IsTrue = false; 4343 else if (op == BO_NE) 4344 IsTrue = true; 4345 else if (RhsConstant) { 4346 if (op == BO_GT || op == BO_GE) 4347 IsTrue = !LitRange.NonNegative; 4348 else // op == BO_LT || op == BO_LE 4349 IsTrue = LitRange.NonNegative; 4350 } else { 4351 if (op == BO_LT || op == BO_LE) 4352 IsTrue = !LitRange.NonNegative; 4353 else // op == BO_GT || op == BO_GE 4354 IsTrue = LitRange.NonNegative; 4355 } 4356 SmallString<16> PrettySourceValue(Value.toString(10)); 4357 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare) 4358 << PrettySourceValue << OtherT << IsTrue 4359 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 4360} 4361 4362/// Analyze the operands of the given comparison. Implements the 4363/// fallback case from AnalyzeComparison. 4364static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 4365 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4366 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4367} 4368 4369/// \brief Implements -Wsign-compare. 4370/// 4371/// \param E the binary operator to check for warnings 4372static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 4373 // The type the comparison is being performed in. 4374 QualType T = E->getLHS()->getType(); 4375 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 4376 && "comparison with mismatched types"); 4377 if (E->isValueDependent()) 4378 return AnalyzeImpConvsInComparison(S, E); 4379 4380 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 4381 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 4382 4383 bool IsComparisonConstant = false; 4384 4385 // Check whether an integer constant comparison results in a value 4386 // of 'true' or 'false'. 4387 if (T->isIntegralType(S.Context)) { 4388 llvm::APSInt RHSValue; 4389 bool IsRHSIntegralLiteral = 4390 RHS->isIntegerConstantExpr(RHSValue, S.Context); 4391 llvm::APSInt LHSValue; 4392 bool IsLHSIntegralLiteral = 4393 LHS->isIntegerConstantExpr(LHSValue, S.Context); 4394 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 4395 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 4396 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 4397 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 4398 else 4399 IsComparisonConstant = 4400 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 4401 } else if (!T->hasUnsignedIntegerRepresentation()) 4402 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 4403 4404 // We don't do anything special if this isn't an unsigned integral 4405 // comparison: we're only interested in integral comparisons, and 4406 // signed comparisons only happen in cases we don't care to warn about. 4407 // 4408 // We also don't care about value-dependent expressions or expressions 4409 // whose result is a constant. 4410 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 4411 return AnalyzeImpConvsInComparison(S, E); 4412 4413 // Check to see if one of the (unmodified) operands is of different 4414 // signedness. 4415 Expr *signedOperand, *unsignedOperand; 4416 if (LHS->getType()->hasSignedIntegerRepresentation()) { 4417 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 4418 "unsigned comparison between two signed integer expressions?"); 4419 signedOperand = LHS; 4420 unsignedOperand = RHS; 4421 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 4422 signedOperand = RHS; 4423 unsignedOperand = LHS; 4424 } else { 4425 CheckTrivialUnsignedComparison(S, E); 4426 return AnalyzeImpConvsInComparison(S, E); 4427 } 4428 4429 // Otherwise, calculate the effective range of the signed operand. 4430 IntRange signedRange = GetExprRange(S.Context, signedOperand); 4431 4432 // Go ahead and analyze implicit conversions in the operands. Note 4433 // that we skip the implicit conversions on both sides. 4434 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 4435 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 4436 4437 // If the signed range is non-negative, -Wsign-compare won't fire, 4438 // but we should still check for comparisons which are always true 4439 // or false. 4440 if (signedRange.NonNegative) 4441 return CheckTrivialUnsignedComparison(S, E); 4442 4443 // For (in)equality comparisons, if the unsigned operand is a 4444 // constant which cannot collide with a overflowed signed operand, 4445 // then reinterpreting the signed operand as unsigned will not 4446 // change the result of the comparison. 4447 if (E->isEqualityOp()) { 4448 unsigned comparisonWidth = S.Context.getIntWidth(T); 4449 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 4450 4451 // We should never be unable to prove that the unsigned operand is 4452 // non-negative. 4453 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 4454 4455 if (unsignedRange.Width < comparisonWidth) 4456 return; 4457 } 4458 4459 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 4460 S.PDiag(diag::warn_mixed_sign_comparison) 4461 << LHS->getType() << RHS->getType() 4462 << LHS->getSourceRange() << RHS->getSourceRange()); 4463} 4464 4465/// Analyzes an attempt to assign the given value to a bitfield. 4466/// 4467/// Returns true if there was something fishy about the attempt. 4468static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 4469 SourceLocation InitLoc) { 4470 assert(Bitfield->isBitField()); 4471 if (Bitfield->isInvalidDecl()) 4472 return false; 4473 4474 // White-list bool bitfields. 4475 if (Bitfield->getType()->isBooleanType()) 4476 return false; 4477 4478 // Ignore value- or type-dependent expressions. 4479 if (Bitfield->getBitWidth()->isValueDependent() || 4480 Bitfield->getBitWidth()->isTypeDependent() || 4481 Init->isValueDependent() || 4482 Init->isTypeDependent()) 4483 return false; 4484 4485 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 4486 4487 llvm::APSInt Value; 4488 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 4489 return false; 4490 4491 unsigned OriginalWidth = Value.getBitWidth(); 4492 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 4493 4494 if (OriginalWidth <= FieldWidth) 4495 return false; 4496 4497 // Compute the value which the bitfield will contain. 4498 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 4499 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 4500 4501 // Check whether the stored value is equal to the original value. 4502 TruncatedValue = TruncatedValue.extend(OriginalWidth); 4503 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 4504 return false; 4505 4506 // Special-case bitfields of width 1: booleans are naturally 0/1, and 4507 // therefore don't strictly fit into a signed bitfield of width 1. 4508 if (FieldWidth == 1 && Value == 1) 4509 return false; 4510 4511 std::string PrettyValue = Value.toString(10); 4512 std::string PrettyTrunc = TruncatedValue.toString(10); 4513 4514 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 4515 << PrettyValue << PrettyTrunc << OriginalInit->getType() 4516 << Init->getSourceRange(); 4517 4518 return true; 4519} 4520 4521/// Analyze the given simple or compound assignment for warning-worthy 4522/// operations. 4523static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 4524 // Just recurse on the LHS. 4525 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 4526 4527 // We want to recurse on the RHS as normal unless we're assigning to 4528 // a bitfield. 4529 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 4530 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 4531 E->getOperatorLoc())) { 4532 // Recurse, ignoring any implicit conversions on the RHS. 4533 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 4534 E->getOperatorLoc()); 4535 } 4536 } 4537 4538 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 4539} 4540 4541/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4542static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 4543 SourceLocation CContext, unsigned diag, 4544 bool pruneControlFlow = false) { 4545 if (pruneControlFlow) { 4546 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4547 S.PDiag(diag) 4548 << SourceType << T << E->getSourceRange() 4549 << SourceRange(CContext)); 4550 return; 4551 } 4552 S.Diag(E->getExprLoc(), diag) 4553 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 4554} 4555 4556/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 4557static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 4558 SourceLocation CContext, unsigned diag, 4559 bool pruneControlFlow = false) { 4560 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 4561} 4562 4563/// Diagnose an implicit cast from a literal expression. Does not warn when the 4564/// cast wouldn't lose information. 4565void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 4566 SourceLocation CContext) { 4567 // Try to convert the literal exactly to an integer. If we can, don't warn. 4568 bool isExact = false; 4569 const llvm::APFloat &Value = FL->getValue(); 4570 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 4571 T->hasUnsignedIntegerRepresentation()); 4572 if (Value.convertToInteger(IntegerValue, 4573 llvm::APFloat::rmTowardZero, &isExact) 4574 == llvm::APFloat::opOK && isExact) 4575 return; 4576 4577 SmallString<16> PrettySourceValue; 4578 Value.toString(PrettySourceValue); 4579 SmallString<16> PrettyTargetValue; 4580 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 4581 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 4582 else 4583 IntegerValue.toString(PrettyTargetValue); 4584 4585 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 4586 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 4587 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 4588} 4589 4590std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 4591 if (!Range.Width) return "0"; 4592 4593 llvm::APSInt ValueInRange = Value; 4594 ValueInRange.setIsSigned(!Range.NonNegative); 4595 ValueInRange = ValueInRange.trunc(Range.Width); 4596 return ValueInRange.toString(10); 4597} 4598 4599static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 4600 if (!isa<ImplicitCastExpr>(Ex)) 4601 return false; 4602 4603 Expr *InnerE = Ex->IgnoreParenImpCasts(); 4604 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 4605 const Type *Source = 4606 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 4607 if (Target->isDependentType()) 4608 return false; 4609 4610 const BuiltinType *FloatCandidateBT = 4611 dyn_cast<BuiltinType>(ToBool ? Source : Target); 4612 const Type *BoolCandidateType = ToBool ? Target : Source; 4613 4614 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 4615 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 4616} 4617 4618void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 4619 SourceLocation CC) { 4620 unsigned NumArgs = TheCall->getNumArgs(); 4621 for (unsigned i = 0; i < NumArgs; ++i) { 4622 Expr *CurrA = TheCall->getArg(i); 4623 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 4624 continue; 4625 4626 bool IsSwapped = ((i > 0) && 4627 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 4628 IsSwapped |= ((i < (NumArgs - 1)) && 4629 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 4630 if (IsSwapped) { 4631 // Warn on this floating-point to bool conversion. 4632 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 4633 CurrA->getType(), CC, 4634 diag::warn_impcast_floating_point_to_bool); 4635 } 4636 } 4637} 4638 4639void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 4640 SourceLocation CC, bool *ICContext = 0) { 4641 if (E->isTypeDependent() || E->isValueDependent()) return; 4642 4643 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 4644 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 4645 if (Source == Target) return; 4646 if (Target->isDependentType()) return; 4647 4648 // If the conversion context location is invalid don't complain. We also 4649 // don't want to emit a warning if the issue occurs from the expansion of 4650 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 4651 // delay this check as long as possible. Once we detect we are in that 4652 // scenario, we just return. 4653 if (CC.isInvalid()) 4654 return; 4655 4656 // Diagnose implicit casts to bool. 4657 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 4658 if (isa<StringLiteral>(E)) 4659 // Warn on string literal to bool. Checks for string literals in logical 4660 // expressions, for instances, assert(0 && "error here"), is prevented 4661 // by a check in AnalyzeImplicitConversions(). 4662 return DiagnoseImpCast(S, E, T, CC, 4663 diag::warn_impcast_string_literal_to_bool); 4664 if (Source->isFunctionType()) { 4665 // Warn on function to bool. Checks free functions and static member 4666 // functions. Weakly imported functions are excluded from the check, 4667 // since it's common to test their value to check whether the linker 4668 // found a definition for them. 4669 ValueDecl *D = 0; 4670 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 4671 D = R->getDecl(); 4672 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 4673 D = M->getMemberDecl(); 4674 } 4675 4676 if (D && !D->isWeak()) { 4677 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 4678 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 4679 << F << E->getSourceRange() << SourceRange(CC); 4680 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 4681 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 4682 QualType ReturnType; 4683 UnresolvedSet<4> NonTemplateOverloads; 4684 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 4685 if (!ReturnType.isNull() 4686 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 4687 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 4688 << FixItHint::CreateInsertion( 4689 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 4690 return; 4691 } 4692 } 4693 } 4694 } 4695 4696 // Strip vector types. 4697 if (isa<VectorType>(Source)) { 4698 if (!isa<VectorType>(Target)) { 4699 if (S.SourceMgr.isInSystemMacro(CC)) 4700 return; 4701 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 4702 } 4703 4704 // If the vector cast is cast between two vectors of the same size, it is 4705 // a bitcast, not a conversion. 4706 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 4707 return; 4708 4709 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 4710 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 4711 } 4712 4713 // Strip complex types. 4714 if (isa<ComplexType>(Source)) { 4715 if (!isa<ComplexType>(Target)) { 4716 if (S.SourceMgr.isInSystemMacro(CC)) 4717 return; 4718 4719 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 4720 } 4721 4722 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 4723 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 4724 } 4725 4726 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 4727 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 4728 4729 // If the source is floating point... 4730 if (SourceBT && SourceBT->isFloatingPoint()) { 4731 // ...and the target is floating point... 4732 if (TargetBT && TargetBT->isFloatingPoint()) { 4733 // ...then warn if we're dropping FP rank. 4734 4735 // Builtin FP kinds are ordered by increasing FP rank. 4736 if (SourceBT->getKind() > TargetBT->getKind()) { 4737 // Don't warn about float constants that are precisely 4738 // representable in the target type. 4739 Expr::EvalResult result; 4740 if (E->EvaluateAsRValue(result, S.Context)) { 4741 // Value might be a float, a float vector, or a float complex. 4742 if (IsSameFloatAfterCast(result.Val, 4743 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 4744 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 4745 return; 4746 } 4747 4748 if (S.SourceMgr.isInSystemMacro(CC)) 4749 return; 4750 4751 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 4752 } 4753 return; 4754 } 4755 4756 // If the target is integral, always warn. 4757 if (TargetBT && TargetBT->isInteger()) { 4758 if (S.SourceMgr.isInSystemMacro(CC)) 4759 return; 4760 4761 Expr *InnerE = E->IgnoreParenImpCasts(); 4762 // We also want to warn on, e.g., "int i = -1.234" 4763 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 4764 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 4765 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 4766 4767 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 4768 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 4769 } else { 4770 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 4771 } 4772 } 4773 4774 // If the target is bool, warn if expr is a function or method call. 4775 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 4776 isa<CallExpr>(E)) { 4777 // Check last argument of function call to see if it is an 4778 // implicit cast from a type matching the type the result 4779 // is being cast to. 4780 CallExpr *CEx = cast<CallExpr>(E); 4781 unsigned NumArgs = CEx->getNumArgs(); 4782 if (NumArgs > 0) { 4783 Expr *LastA = CEx->getArg(NumArgs - 1); 4784 Expr *InnerE = LastA->IgnoreParenImpCasts(); 4785 const Type *InnerType = 4786 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 4787 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 4788 // Warn on this floating-point to bool conversion 4789 DiagnoseImpCast(S, E, T, CC, 4790 diag::warn_impcast_floating_point_to_bool); 4791 } 4792 } 4793 } 4794 return; 4795 } 4796 4797 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 4798 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType() 4799 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) { 4800 SourceLocation Loc = E->getSourceRange().getBegin(); 4801 if (Loc.isMacroID()) 4802 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 4803 if (!Loc.isMacroID() || CC.isMacroID()) 4804 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 4805 << T << clang::SourceRange(CC) 4806 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T)); 4807 } 4808 4809 if (!Source->isIntegerType() || !Target->isIntegerType()) 4810 return; 4811 4812 // TODO: remove this early return once the false positives for constant->bool 4813 // in templates, macros, etc, are reduced or removed. 4814 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 4815 return; 4816 4817 IntRange SourceRange = GetExprRange(S.Context, E); 4818 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 4819 4820 if (SourceRange.Width > TargetRange.Width) { 4821 // If the source is a constant, use a default-on diagnostic. 4822 // TODO: this should happen for bitfield stores, too. 4823 llvm::APSInt Value(32); 4824 if (E->isIntegerConstantExpr(Value, S.Context)) { 4825 if (S.SourceMgr.isInSystemMacro(CC)) 4826 return; 4827 4828 std::string PrettySourceValue = Value.toString(10); 4829 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 4830 4831 S.DiagRuntimeBehavior(E->getExprLoc(), E, 4832 S.PDiag(diag::warn_impcast_integer_precision_constant) 4833 << PrettySourceValue << PrettyTargetValue 4834 << E->getType() << T << E->getSourceRange() 4835 << clang::SourceRange(CC)); 4836 return; 4837 } 4838 4839 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 4840 if (S.SourceMgr.isInSystemMacro(CC)) 4841 return; 4842 4843 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 4844 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 4845 /* pruneControlFlow */ true); 4846 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 4847 } 4848 4849 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 4850 (!TargetRange.NonNegative && SourceRange.NonNegative && 4851 SourceRange.Width == TargetRange.Width)) { 4852 4853 if (S.SourceMgr.isInSystemMacro(CC)) 4854 return; 4855 4856 unsigned DiagID = diag::warn_impcast_integer_sign; 4857 4858 // Traditionally, gcc has warned about this under -Wsign-compare. 4859 // We also want to warn about it in -Wconversion. 4860 // So if -Wconversion is off, use a completely identical diagnostic 4861 // in the sign-compare group. 4862 // The conditional-checking code will 4863 if (ICContext) { 4864 DiagID = diag::warn_impcast_integer_sign_conditional; 4865 *ICContext = true; 4866 } 4867 4868 return DiagnoseImpCast(S, E, T, CC, DiagID); 4869 } 4870 4871 // Diagnose conversions between different enumeration types. 4872 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 4873 // type, to give us better diagnostics. 4874 QualType SourceType = E->getType(); 4875 if (!S.getLangOpts().CPlusPlus) { 4876 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4877 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4878 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 4879 SourceType = S.Context.getTypeDeclType(Enum); 4880 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 4881 } 4882 } 4883 4884 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 4885 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 4886 if ((SourceEnum->getDecl()->getIdentifier() || 4887 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 4888 (TargetEnum->getDecl()->getIdentifier() || 4889 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 4890 SourceEnum != TargetEnum) { 4891 if (S.SourceMgr.isInSystemMacro(CC)) 4892 return; 4893 4894 return DiagnoseImpCast(S, E, SourceType, T, CC, 4895 diag::warn_impcast_different_enum_types); 4896 } 4897 4898 return; 4899} 4900 4901void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4902 SourceLocation CC, QualType T); 4903 4904void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 4905 SourceLocation CC, bool &ICContext) { 4906 E = E->IgnoreParenImpCasts(); 4907 4908 if (isa<ConditionalOperator>(E)) 4909 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 4910 4911 AnalyzeImplicitConversions(S, E, CC); 4912 if (E->getType() != T) 4913 return CheckImplicitConversion(S, E, T, CC, &ICContext); 4914 return; 4915} 4916 4917void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 4918 SourceLocation CC, QualType T) { 4919 AnalyzeImplicitConversions(S, E->getCond(), CC); 4920 4921 bool Suspicious = false; 4922 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 4923 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 4924 4925 // If -Wconversion would have warned about either of the candidates 4926 // for a signedness conversion to the context type... 4927 if (!Suspicious) return; 4928 4929 // ...but it's currently ignored... 4930 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4931 CC)) 4932 return; 4933 4934 // ...then check whether it would have warned about either of the 4935 // candidates for a signedness conversion to the condition type. 4936 if (E->getType() == T) return; 4937 4938 Suspicious = false; 4939 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4940 E->getType(), CC, &Suspicious); 4941 if (!Suspicious) 4942 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4943 E->getType(), CC, &Suspicious); 4944} 4945 4946/// AnalyzeImplicitConversions - Find and report any interesting 4947/// implicit conversions in the given expression. There are a couple 4948/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4949void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4950 QualType T = OrigE->getType(); 4951 Expr *E = OrigE->IgnoreParenImpCasts(); 4952 4953 if (E->isTypeDependent() || E->isValueDependent()) 4954 return; 4955 4956 // For conditional operators, we analyze the arguments as if they 4957 // were being fed directly into the output. 4958 if (isa<ConditionalOperator>(E)) { 4959 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4960 CheckConditionalOperator(S, CO, CC, T); 4961 return; 4962 } 4963 4964 // Check implicit argument conversions for function calls. 4965 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 4966 CheckImplicitArgumentConversions(S, Call, CC); 4967 4968 // Go ahead and check any implicit conversions we might have skipped. 4969 // The non-canonical typecheck is just an optimization; 4970 // CheckImplicitConversion will filter out dead implicit conversions. 4971 if (E->getType() != T) 4972 CheckImplicitConversion(S, E, T, CC); 4973 4974 // Now continue drilling into this expression. 4975 4976 // Skip past explicit casts. 4977 if (isa<ExplicitCastExpr>(E)) { 4978 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4979 return AnalyzeImplicitConversions(S, E, CC); 4980 } 4981 4982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4983 // Do a somewhat different check with comparison operators. 4984 if (BO->isComparisonOp()) 4985 return AnalyzeComparison(S, BO); 4986 4987 // And with simple assignments. 4988 if (BO->getOpcode() == BO_Assign) 4989 return AnalyzeAssignment(S, BO); 4990 } 4991 4992 // These break the otherwise-useful invariant below. Fortunately, 4993 // we don't really need to recurse into them, because any internal 4994 // expressions should have been analyzed already when they were 4995 // built into statements. 4996 if (isa<StmtExpr>(E)) return; 4997 4998 // Don't descend into unevaluated contexts. 4999 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 5000 5001 // Now just recurse over the expression's children. 5002 CC = E->getExprLoc(); 5003 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 5004 bool IsLogicalOperator = BO && BO->isLogicalOp(); 5005 for (Stmt::child_range I = E->children(); I; ++I) { 5006 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 5007 if (!ChildExpr) 5008 continue; 5009 5010 if (IsLogicalOperator && 5011 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 5012 // Ignore checking string literals that are in logical operators. 5013 continue; 5014 AnalyzeImplicitConversions(S, ChildExpr, CC); 5015 } 5016} 5017 5018} // end anonymous namespace 5019 5020/// Diagnoses "dangerous" implicit conversions within the given 5021/// expression (which is a full expression). Implements -Wconversion 5022/// and -Wsign-compare. 5023/// 5024/// \param CC the "context" location of the implicit conversion, i.e. 5025/// the most location of the syntactic entity requiring the implicit 5026/// conversion 5027void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 5028 // Don't diagnose in unevaluated contexts. 5029 if (isUnevaluatedContext()) 5030 return; 5031 5032 // Don't diagnose for value- or type-dependent expressions. 5033 if (E->isTypeDependent() || E->isValueDependent()) 5034 return; 5035 5036 // Check for array bounds violations in cases where the check isn't triggered 5037 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 5038 // ArraySubscriptExpr is on the RHS of a variable initialization. 5039 CheckArrayAccess(E); 5040 5041 // This is not the right CC for (e.g.) a variable initialization. 5042 AnalyzeImplicitConversions(*this, E, CC); 5043} 5044 5045void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 5046 FieldDecl *BitField, 5047 Expr *Init) { 5048 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 5049} 5050 5051/// CheckParmsForFunctionDef - Check that the parameters of the given 5052/// function are appropriate for the definition of a function. This 5053/// takes care of any checks that cannot be performed on the 5054/// declaration itself, e.g., that the types of each of the function 5055/// parameters are complete. 5056bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 5057 bool CheckParameterNames) { 5058 bool HasInvalidParm = false; 5059 for (; P != PEnd; ++P) { 5060 ParmVarDecl *Param = *P; 5061 5062 // C99 6.7.5.3p4: the parameters in a parameter type list in a 5063 // function declarator that is part of a function definition of 5064 // that function shall not have incomplete type. 5065 // 5066 // This is also C++ [dcl.fct]p6. 5067 if (!Param->isInvalidDecl() && 5068 RequireCompleteType(Param->getLocation(), Param->getType(), 5069 diag::err_typecheck_decl_incomplete_type)) { 5070 Param->setInvalidDecl(); 5071 HasInvalidParm = true; 5072 } 5073 5074 // C99 6.9.1p5: If the declarator includes a parameter type list, the 5075 // declaration of each parameter shall include an identifier. 5076 if (CheckParameterNames && 5077 Param->getIdentifier() == 0 && 5078 !Param->isImplicit() && 5079 !getLangOpts().CPlusPlus) 5080 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 5081 5082 // C99 6.7.5.3p12: 5083 // If the function declarator is not part of a definition of that 5084 // function, parameters may have incomplete type and may use the [*] 5085 // notation in their sequences of declarator specifiers to specify 5086 // variable length array types. 5087 QualType PType = Param->getOriginalType(); 5088 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 5089 if (AT->getSizeModifier() == ArrayType::Star) { 5090 // FIXME: This diagnosic should point the '[*]' if source-location 5091 // information is added for it. 5092 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 5093 } 5094 } 5095 } 5096 5097 return HasInvalidParm; 5098} 5099 5100/// CheckCastAlign - Implements -Wcast-align, which warns when a 5101/// pointer cast increases the alignment requirements. 5102void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 5103 // This is actually a lot of work to potentially be doing on every 5104 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 5105 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 5106 TRange.getBegin()) 5107 == DiagnosticsEngine::Ignored) 5108 return; 5109 5110 // Ignore dependent types. 5111 if (T->isDependentType() || Op->getType()->isDependentType()) 5112 return; 5113 5114 // Require that the destination be a pointer type. 5115 const PointerType *DestPtr = T->getAs<PointerType>(); 5116 if (!DestPtr) return; 5117 5118 // If the destination has alignment 1, we're done. 5119 QualType DestPointee = DestPtr->getPointeeType(); 5120 if (DestPointee->isIncompleteType()) return; 5121 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 5122 if (DestAlign.isOne()) return; 5123 5124 // Require that the source be a pointer type. 5125 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 5126 if (!SrcPtr) return; 5127 QualType SrcPointee = SrcPtr->getPointeeType(); 5128 5129 // Whitelist casts from cv void*. We already implicitly 5130 // whitelisted casts to cv void*, since they have alignment 1. 5131 // Also whitelist casts involving incomplete types, which implicitly 5132 // includes 'void'. 5133 if (SrcPointee->isIncompleteType()) return; 5134 5135 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 5136 if (SrcAlign >= DestAlign) return; 5137 5138 Diag(TRange.getBegin(), diag::warn_cast_align) 5139 << Op->getType() << T 5140 << static_cast<unsigned>(SrcAlign.getQuantity()) 5141 << static_cast<unsigned>(DestAlign.getQuantity()) 5142 << TRange << Op->getSourceRange(); 5143} 5144 5145static const Type* getElementType(const Expr *BaseExpr) { 5146 const Type* EltType = BaseExpr->getType().getTypePtr(); 5147 if (EltType->isAnyPointerType()) 5148 return EltType->getPointeeType().getTypePtr(); 5149 else if (EltType->isArrayType()) 5150 return EltType->getBaseElementTypeUnsafe(); 5151 return EltType; 5152} 5153 5154/// \brief Check whether this array fits the idiom of a size-one tail padded 5155/// array member of a struct. 5156/// 5157/// We avoid emitting out-of-bounds access warnings for such arrays as they are 5158/// commonly used to emulate flexible arrays in C89 code. 5159static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 5160 const NamedDecl *ND) { 5161 if (Size != 1 || !ND) return false; 5162 5163 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 5164 if (!FD) return false; 5165 5166 // Don't consider sizes resulting from macro expansions or template argument 5167 // substitution to form C89 tail-padded arrays. 5168 5169 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 5170 while (TInfo) { 5171 TypeLoc TL = TInfo->getTypeLoc(); 5172 // Look through typedefs. 5173 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL); 5174 if (TTL) { 5175 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl(); 5176 TInfo = TDL->getTypeSourceInfo(); 5177 continue; 5178 } 5179 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL); 5180 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 5181 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 5182 return false; 5183 break; 5184 } 5185 5186 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 5187 if (!RD) return false; 5188 if (RD->isUnion()) return false; 5189 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 5190 if (!CRD->isStandardLayout()) return false; 5191 } 5192 5193 // See if this is the last field decl in the record. 5194 const Decl *D = FD; 5195 while ((D = D->getNextDeclInContext())) 5196 if (isa<FieldDecl>(D)) 5197 return false; 5198 return true; 5199} 5200 5201void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 5202 const ArraySubscriptExpr *ASE, 5203 bool AllowOnePastEnd, bool IndexNegated) { 5204 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 5205 if (IndexExpr->isValueDependent()) 5206 return; 5207 5208 const Type *EffectiveType = getElementType(BaseExpr); 5209 BaseExpr = BaseExpr->IgnoreParenCasts(); 5210 const ConstantArrayType *ArrayTy = 5211 Context.getAsConstantArrayType(BaseExpr->getType()); 5212 if (!ArrayTy) 5213 return; 5214 5215 llvm::APSInt index; 5216 if (!IndexExpr->EvaluateAsInt(index, Context)) 5217 return; 5218 if (IndexNegated) 5219 index = -index; 5220 5221 const NamedDecl *ND = NULL; 5222 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 5223 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 5224 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 5225 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 5226 5227 if (index.isUnsigned() || !index.isNegative()) { 5228 llvm::APInt size = ArrayTy->getSize(); 5229 if (!size.isStrictlyPositive()) 5230 return; 5231 5232 const Type* BaseType = getElementType(BaseExpr); 5233 if (BaseType != EffectiveType) { 5234 // Make sure we're comparing apples to apples when comparing index to size 5235 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 5236 uint64_t array_typesize = Context.getTypeSize(BaseType); 5237 // Handle ptrarith_typesize being zero, such as when casting to void* 5238 if (!ptrarith_typesize) ptrarith_typesize = 1; 5239 if (ptrarith_typesize != array_typesize) { 5240 // There's a cast to a different size type involved 5241 uint64_t ratio = array_typesize / ptrarith_typesize; 5242 // TODO: Be smarter about handling cases where array_typesize is not a 5243 // multiple of ptrarith_typesize 5244 if (ptrarith_typesize * ratio == array_typesize) 5245 size *= llvm::APInt(size.getBitWidth(), ratio); 5246 } 5247 } 5248 5249 if (size.getBitWidth() > index.getBitWidth()) 5250 index = index.zext(size.getBitWidth()); 5251 else if (size.getBitWidth() < index.getBitWidth()) 5252 size = size.zext(index.getBitWidth()); 5253 5254 // For array subscripting the index must be less than size, but for pointer 5255 // arithmetic also allow the index (offset) to be equal to size since 5256 // computing the next address after the end of the array is legal and 5257 // commonly done e.g. in C++ iterators and range-based for loops. 5258 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 5259 return; 5260 5261 // Also don't warn for arrays of size 1 which are members of some 5262 // structure. These are often used to approximate flexible arrays in C89 5263 // code. 5264 if (IsTailPaddedMemberArray(*this, size, ND)) 5265 return; 5266 5267 // Suppress the warning if the subscript expression (as identified by the 5268 // ']' location) and the index expression are both from macro expansions 5269 // within a system header. 5270 if (ASE) { 5271 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 5272 ASE->getRBracketLoc()); 5273 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 5274 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 5275 IndexExpr->getLocStart()); 5276 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 5277 return; 5278 } 5279 } 5280 5281 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 5282 if (ASE) 5283 DiagID = diag::warn_array_index_exceeds_bounds; 5284 5285 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 5286 PDiag(DiagID) << index.toString(10, true) 5287 << size.toString(10, true) 5288 << (unsigned)size.getLimitedValue(~0U) 5289 << IndexExpr->getSourceRange()); 5290 } else { 5291 unsigned DiagID = diag::warn_array_index_precedes_bounds; 5292 if (!ASE) { 5293 DiagID = diag::warn_ptr_arith_precedes_bounds; 5294 if (index.isNegative()) index = -index; 5295 } 5296 5297 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 5298 PDiag(DiagID) << index.toString(10, true) 5299 << IndexExpr->getSourceRange()); 5300 } 5301 5302 if (!ND) { 5303 // Try harder to find a NamedDecl to point at in the note. 5304 while (const ArraySubscriptExpr *ASE = 5305 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 5306 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 5307 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 5308 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 5309 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 5310 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 5311 } 5312 5313 if (ND) 5314 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 5315 PDiag(diag::note_array_index_out_of_bounds) 5316 << ND->getDeclName()); 5317} 5318 5319void Sema::CheckArrayAccess(const Expr *expr) { 5320 int AllowOnePastEnd = 0; 5321 while (expr) { 5322 expr = expr->IgnoreParenImpCasts(); 5323 switch (expr->getStmtClass()) { 5324 case Stmt::ArraySubscriptExprClass: { 5325 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 5326 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 5327 AllowOnePastEnd > 0); 5328 return; 5329 } 5330 case Stmt::UnaryOperatorClass: { 5331 // Only unwrap the * and & unary operators 5332 const UnaryOperator *UO = cast<UnaryOperator>(expr); 5333 expr = UO->getSubExpr(); 5334 switch (UO->getOpcode()) { 5335 case UO_AddrOf: 5336 AllowOnePastEnd++; 5337 break; 5338 case UO_Deref: 5339 AllowOnePastEnd--; 5340 break; 5341 default: 5342 return; 5343 } 5344 break; 5345 } 5346 case Stmt::ConditionalOperatorClass: { 5347 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 5348 if (const Expr *lhs = cond->getLHS()) 5349 CheckArrayAccess(lhs); 5350 if (const Expr *rhs = cond->getRHS()) 5351 CheckArrayAccess(rhs); 5352 return; 5353 } 5354 default: 5355 return; 5356 } 5357 } 5358} 5359 5360//===--- CHECK: Objective-C retain cycles ----------------------------------// 5361 5362namespace { 5363 struct RetainCycleOwner { 5364 RetainCycleOwner() : Variable(0), Indirect(false) {} 5365 VarDecl *Variable; 5366 SourceRange Range; 5367 SourceLocation Loc; 5368 bool Indirect; 5369 5370 void setLocsFrom(Expr *e) { 5371 Loc = e->getExprLoc(); 5372 Range = e->getSourceRange(); 5373 } 5374 }; 5375} 5376 5377/// Consider whether capturing the given variable can possibly lead to 5378/// a retain cycle. 5379static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 5380 // In ARC, it's captured strongly iff the variable has __strong 5381 // lifetime. In MRR, it's captured strongly if the variable is 5382 // __block and has an appropriate type. 5383 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 5384 return false; 5385 5386 owner.Variable = var; 5387 if (ref) 5388 owner.setLocsFrom(ref); 5389 return true; 5390} 5391 5392static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 5393 while (true) { 5394 e = e->IgnoreParens(); 5395 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 5396 switch (cast->getCastKind()) { 5397 case CK_BitCast: 5398 case CK_LValueBitCast: 5399 case CK_LValueToRValue: 5400 case CK_ARCReclaimReturnedObject: 5401 e = cast->getSubExpr(); 5402 continue; 5403 5404 default: 5405 return false; 5406 } 5407 } 5408 5409 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 5410 ObjCIvarDecl *ivar = ref->getDecl(); 5411 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 5412 return false; 5413 5414 // Try to find a retain cycle in the base. 5415 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 5416 return false; 5417 5418 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 5419 owner.Indirect = true; 5420 return true; 5421 } 5422 5423 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 5424 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 5425 if (!var) return false; 5426 return considerVariable(var, ref, owner); 5427 } 5428 5429 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 5430 if (member->isArrow()) return false; 5431 5432 // Don't count this as an indirect ownership. 5433 e = member->getBase(); 5434 continue; 5435 } 5436 5437 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 5438 // Only pay attention to pseudo-objects on property references. 5439 ObjCPropertyRefExpr *pre 5440 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 5441 ->IgnoreParens()); 5442 if (!pre) return false; 5443 if (pre->isImplicitProperty()) return false; 5444 ObjCPropertyDecl *property = pre->getExplicitProperty(); 5445 if (!property->isRetaining() && 5446 !(property->getPropertyIvarDecl() && 5447 property->getPropertyIvarDecl()->getType() 5448 .getObjCLifetime() == Qualifiers::OCL_Strong)) 5449 return false; 5450 5451 owner.Indirect = true; 5452 if (pre->isSuperReceiver()) { 5453 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 5454 if (!owner.Variable) 5455 return false; 5456 owner.Loc = pre->getLocation(); 5457 owner.Range = pre->getSourceRange(); 5458 return true; 5459 } 5460 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 5461 ->getSourceExpr()); 5462 continue; 5463 } 5464 5465 // Array ivars? 5466 5467 return false; 5468 } 5469} 5470 5471namespace { 5472 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 5473 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 5474 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 5475 Variable(variable), Capturer(0) {} 5476 5477 VarDecl *Variable; 5478 Expr *Capturer; 5479 5480 void VisitDeclRefExpr(DeclRefExpr *ref) { 5481 if (ref->getDecl() == Variable && !Capturer) 5482 Capturer = ref; 5483 } 5484 5485 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 5486 if (Capturer) return; 5487 Visit(ref->getBase()); 5488 if (Capturer && ref->isFreeIvar()) 5489 Capturer = ref; 5490 } 5491 5492 void VisitBlockExpr(BlockExpr *block) { 5493 // Look inside nested blocks 5494 if (block->getBlockDecl()->capturesVariable(Variable)) 5495 Visit(block->getBlockDecl()->getBody()); 5496 } 5497 5498 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 5499 if (Capturer) return; 5500 if (OVE->getSourceExpr()) 5501 Visit(OVE->getSourceExpr()); 5502 } 5503 }; 5504} 5505 5506/// Check whether the given argument is a block which captures a 5507/// variable. 5508static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 5509 assert(owner.Variable && owner.Loc.isValid()); 5510 5511 e = e->IgnoreParenCasts(); 5512 5513 // Look through [^{...} copy] and Block_copy(^{...}). 5514 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 5515 Selector Cmd = ME->getSelector(); 5516 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 5517 e = ME->getInstanceReceiver(); 5518 if (!e) 5519 return 0; 5520 e = e->IgnoreParenCasts(); 5521 } 5522 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 5523 if (CE->getNumArgs() == 1) { 5524 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 5525 if (Fn) { 5526 const IdentifierInfo *FnI = Fn->getIdentifier(); 5527 if (FnI && FnI->isStr("_Block_copy")) { 5528 e = CE->getArg(0)->IgnoreParenCasts(); 5529 } 5530 } 5531 } 5532 } 5533 5534 BlockExpr *block = dyn_cast<BlockExpr>(e); 5535 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 5536 return 0; 5537 5538 FindCaptureVisitor visitor(S.Context, owner.Variable); 5539 visitor.Visit(block->getBlockDecl()->getBody()); 5540 return visitor.Capturer; 5541} 5542 5543static void diagnoseRetainCycle(Sema &S, Expr *capturer, 5544 RetainCycleOwner &owner) { 5545 assert(capturer); 5546 assert(owner.Variable && owner.Loc.isValid()); 5547 5548 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 5549 << owner.Variable << capturer->getSourceRange(); 5550 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 5551 << owner.Indirect << owner.Range; 5552} 5553 5554/// Check for a keyword selector that starts with the word 'add' or 5555/// 'set'. 5556static bool isSetterLikeSelector(Selector sel) { 5557 if (sel.isUnarySelector()) return false; 5558 5559 StringRef str = sel.getNameForSlot(0); 5560 while (!str.empty() && str.front() == '_') str = str.substr(1); 5561 if (str.startswith("set")) 5562 str = str.substr(3); 5563 else if (str.startswith("add")) { 5564 // Specially whitelist 'addOperationWithBlock:'. 5565 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 5566 return false; 5567 str = str.substr(3); 5568 } 5569 else 5570 return false; 5571 5572 if (str.empty()) return true; 5573 return !islower(str.front()); 5574} 5575 5576/// Check a message send to see if it's likely to cause a retain cycle. 5577void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 5578 // Only check instance methods whose selector looks like a setter. 5579 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 5580 return; 5581 5582 // Try to find a variable that the receiver is strongly owned by. 5583 RetainCycleOwner owner; 5584 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 5585 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 5586 return; 5587 } else { 5588 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 5589 owner.Variable = getCurMethodDecl()->getSelfDecl(); 5590 owner.Loc = msg->getSuperLoc(); 5591 owner.Range = msg->getSuperLoc(); 5592 } 5593 5594 // Check whether the receiver is captured by any of the arguments. 5595 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 5596 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 5597 return diagnoseRetainCycle(*this, capturer, owner); 5598} 5599 5600/// Check a property assign to see if it's likely to cause a retain cycle. 5601void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 5602 RetainCycleOwner owner; 5603 if (!findRetainCycleOwner(*this, receiver, owner)) 5604 return; 5605 5606 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 5607 diagnoseRetainCycle(*this, capturer, owner); 5608} 5609 5610void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 5611 RetainCycleOwner Owner; 5612 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner)) 5613 return; 5614 5615 // Because we don't have an expression for the variable, we have to set the 5616 // location explicitly here. 5617 Owner.Loc = Var->getLocation(); 5618 Owner.Range = Var->getSourceRange(); 5619 5620 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 5621 diagnoseRetainCycle(*this, Capturer, Owner); 5622} 5623 5624bool Sema::checkUnsafeAssigns(SourceLocation Loc, 5625 QualType LHS, Expr *RHS) { 5626 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 5627 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 5628 return false; 5629 // strip off any implicit cast added to get to the one arc-specific 5630 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5631 if (cast->getCastKind() == CK_ARCConsumeObject) { 5632 Diag(Loc, diag::warn_arc_retained_assign) 5633 << (LT == Qualifiers::OCL_ExplicitNone) << 1 5634 << RHS->getSourceRange(); 5635 return true; 5636 } 5637 RHS = cast->getSubExpr(); 5638 } 5639 return false; 5640} 5641 5642void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 5643 Expr *LHS, Expr *RHS) { 5644 QualType LHSType; 5645 // PropertyRef on LHS type need be directly obtained from 5646 // its declaration as it has a PsuedoType. 5647 ObjCPropertyRefExpr *PRE 5648 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 5649 if (PRE && !PRE->isImplicitProperty()) { 5650 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5651 if (PD) 5652 LHSType = PD->getType(); 5653 } 5654 5655 if (LHSType.isNull()) 5656 LHSType = LHS->getType(); 5657 5658 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 5659 5660 if (LT == Qualifiers::OCL_Weak) { 5661 DiagnosticsEngine::Level Level = 5662 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 5663 if (Level != DiagnosticsEngine::Ignored) 5664 getCurFunction()->markSafeWeakUse(LHS); 5665 } 5666 5667 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 5668 return; 5669 5670 // FIXME. Check for other life times. 5671 if (LT != Qualifiers::OCL_None) 5672 return; 5673 5674 if (PRE) { 5675 if (PRE->isImplicitProperty()) 5676 return; 5677 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 5678 if (!PD) 5679 return; 5680 5681 unsigned Attributes = PD->getPropertyAttributes(); 5682 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 5683 // when 'assign' attribute was not explicitly specified 5684 // by user, ignore it and rely on property type itself 5685 // for lifetime info. 5686 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 5687 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 5688 LHSType->isObjCRetainableType()) 5689 return; 5690 5691 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5692 if (cast->getCastKind() == CK_ARCConsumeObject) { 5693 Diag(Loc, diag::warn_arc_retained_property_assign) 5694 << RHS->getSourceRange(); 5695 return; 5696 } 5697 RHS = cast->getSubExpr(); 5698 } 5699 } 5700 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 5701 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 5702 if (cast->getCastKind() == CK_ARCConsumeObject) { 5703 Diag(Loc, diag::warn_arc_retained_assign) 5704 << 0 << 0<< RHS->getSourceRange(); 5705 return; 5706 } 5707 RHS = cast->getSubExpr(); 5708 } 5709 } 5710 } 5711} 5712 5713//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 5714 5715namespace { 5716bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 5717 SourceLocation StmtLoc, 5718 const NullStmt *Body) { 5719 // Do not warn if the body is a macro that expands to nothing, e.g: 5720 // 5721 // #define CALL(x) 5722 // if (condition) 5723 // CALL(0); 5724 // 5725 if (Body->hasLeadingEmptyMacro()) 5726 return false; 5727 5728 // Get line numbers of statement and body. 5729 bool StmtLineInvalid; 5730 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 5731 &StmtLineInvalid); 5732 if (StmtLineInvalid) 5733 return false; 5734 5735 bool BodyLineInvalid; 5736 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 5737 &BodyLineInvalid); 5738 if (BodyLineInvalid) 5739 return false; 5740 5741 // Warn if null statement and body are on the same line. 5742 if (StmtLine != BodyLine) 5743 return false; 5744 5745 return true; 5746} 5747} // Unnamed namespace 5748 5749void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5750 const Stmt *Body, 5751 unsigned DiagID) { 5752 // Since this is a syntactic check, don't emit diagnostic for template 5753 // instantiations, this just adds noise. 5754 if (CurrentInstantiationScope) 5755 return; 5756 5757 // The body should be a null statement. 5758 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5759 if (!NBody) 5760 return; 5761 5762 // Do the usual checks. 5763 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5764 return; 5765 5766 Diag(NBody->getSemiLoc(), DiagID); 5767 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5768} 5769 5770void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 5771 const Stmt *PossibleBody) { 5772 assert(!CurrentInstantiationScope); // Ensured by caller 5773 5774 SourceLocation StmtLoc; 5775 const Stmt *Body; 5776 unsigned DiagID; 5777 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 5778 StmtLoc = FS->getRParenLoc(); 5779 Body = FS->getBody(); 5780 DiagID = diag::warn_empty_for_body; 5781 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 5782 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 5783 Body = WS->getBody(); 5784 DiagID = diag::warn_empty_while_body; 5785 } else 5786 return; // Neither `for' nor `while'. 5787 5788 // The body should be a null statement. 5789 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 5790 if (!NBody) 5791 return; 5792 5793 // Skip expensive checks if diagnostic is disabled. 5794 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) == 5795 DiagnosticsEngine::Ignored) 5796 return; 5797 5798 // Do the usual checks. 5799 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 5800 return; 5801 5802 // `for(...);' and `while(...);' are popular idioms, so in order to keep 5803 // noise level low, emit diagnostics only if for/while is followed by a 5804 // CompoundStmt, e.g.: 5805 // for (int i = 0; i < n; i++); 5806 // { 5807 // a(i); 5808 // } 5809 // or if for/while is followed by a statement with more indentation 5810 // than for/while itself: 5811 // for (int i = 0; i < n; i++); 5812 // a(i); 5813 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 5814 if (!ProbableTypo) { 5815 bool BodyColInvalid; 5816 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 5817 PossibleBody->getLocStart(), 5818 &BodyColInvalid); 5819 if (BodyColInvalid) 5820 return; 5821 5822 bool StmtColInvalid; 5823 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 5824 S->getLocStart(), 5825 &StmtColInvalid); 5826 if (StmtColInvalid) 5827 return; 5828 5829 if (BodyCol > StmtCol) 5830 ProbableTypo = true; 5831 } 5832 5833 if (ProbableTypo) { 5834 Diag(NBody->getSemiLoc(), DiagID); 5835 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 5836 } 5837} 5838 5839//===--- Layout compatibility ----------------------------------------------// 5840 5841namespace { 5842 5843bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 5844 5845/// \brief Check if two enumeration types are layout-compatible. 5846bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 5847 // C++11 [dcl.enum] p8: 5848 // Two enumeration types are layout-compatible if they have the same 5849 // underlying type. 5850 return ED1->isComplete() && ED2->isComplete() && 5851 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 5852} 5853 5854/// \brief Check if two fields are layout-compatible. 5855bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 5856 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 5857 return false; 5858 5859 if (Field1->isBitField() != Field2->isBitField()) 5860 return false; 5861 5862 if (Field1->isBitField()) { 5863 // Make sure that the bit-fields are the same length. 5864 unsigned Bits1 = Field1->getBitWidthValue(C); 5865 unsigned Bits2 = Field2->getBitWidthValue(C); 5866 5867 if (Bits1 != Bits2) 5868 return false; 5869 } 5870 5871 return true; 5872} 5873 5874/// \brief Check if two standard-layout structs are layout-compatible. 5875/// (C++11 [class.mem] p17) 5876bool isLayoutCompatibleStruct(ASTContext &C, 5877 RecordDecl *RD1, 5878 RecordDecl *RD2) { 5879 // If both records are C++ classes, check that base classes match. 5880 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 5881 // If one of records is a CXXRecordDecl we are in C++ mode, 5882 // thus the other one is a CXXRecordDecl, too. 5883 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 5884 // Check number of base classes. 5885 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 5886 return false; 5887 5888 // Check the base classes. 5889 for (CXXRecordDecl::base_class_const_iterator 5890 Base1 = D1CXX->bases_begin(), 5891 BaseEnd1 = D1CXX->bases_end(), 5892 Base2 = D2CXX->bases_begin(); 5893 Base1 != BaseEnd1; 5894 ++Base1, ++Base2) { 5895 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 5896 return false; 5897 } 5898 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 5899 // If only RD2 is a C++ class, it should have zero base classes. 5900 if (D2CXX->getNumBases() > 0) 5901 return false; 5902 } 5903 5904 // Check the fields. 5905 RecordDecl::field_iterator Field2 = RD2->field_begin(), 5906 Field2End = RD2->field_end(), 5907 Field1 = RD1->field_begin(), 5908 Field1End = RD1->field_end(); 5909 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 5910 if (!isLayoutCompatible(C, *Field1, *Field2)) 5911 return false; 5912 } 5913 if (Field1 != Field1End || Field2 != Field2End) 5914 return false; 5915 5916 return true; 5917} 5918 5919/// \brief Check if two standard-layout unions are layout-compatible. 5920/// (C++11 [class.mem] p18) 5921bool isLayoutCompatibleUnion(ASTContext &C, 5922 RecordDecl *RD1, 5923 RecordDecl *RD2) { 5924 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 5925 for (RecordDecl::field_iterator Field2 = RD2->field_begin(), 5926 Field2End = RD2->field_end(); 5927 Field2 != Field2End; ++Field2) { 5928 UnmatchedFields.insert(*Field2); 5929 } 5930 5931 for (RecordDecl::field_iterator Field1 = RD1->field_begin(), 5932 Field1End = RD1->field_end(); 5933 Field1 != Field1End; ++Field1) { 5934 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 5935 I = UnmatchedFields.begin(), 5936 E = UnmatchedFields.end(); 5937 5938 for ( ; I != E; ++I) { 5939 if (isLayoutCompatible(C, *Field1, *I)) { 5940 bool Result = UnmatchedFields.erase(*I); 5941 (void) Result; 5942 assert(Result); 5943 break; 5944 } 5945 } 5946 if (I == E) 5947 return false; 5948 } 5949 5950 return UnmatchedFields.empty(); 5951} 5952 5953bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 5954 if (RD1->isUnion() != RD2->isUnion()) 5955 return false; 5956 5957 if (RD1->isUnion()) 5958 return isLayoutCompatibleUnion(C, RD1, RD2); 5959 else 5960 return isLayoutCompatibleStruct(C, RD1, RD2); 5961} 5962 5963/// \brief Check if two types are layout-compatible in C++11 sense. 5964bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 5965 if (T1.isNull() || T2.isNull()) 5966 return false; 5967 5968 // C++11 [basic.types] p11: 5969 // If two types T1 and T2 are the same type, then T1 and T2 are 5970 // layout-compatible types. 5971 if (C.hasSameType(T1, T2)) 5972 return true; 5973 5974 T1 = T1.getCanonicalType().getUnqualifiedType(); 5975 T2 = T2.getCanonicalType().getUnqualifiedType(); 5976 5977 const Type::TypeClass TC1 = T1->getTypeClass(); 5978 const Type::TypeClass TC2 = T2->getTypeClass(); 5979 5980 if (TC1 != TC2) 5981 return false; 5982 5983 if (TC1 == Type::Enum) { 5984 return isLayoutCompatible(C, 5985 cast<EnumType>(T1)->getDecl(), 5986 cast<EnumType>(T2)->getDecl()); 5987 } else if (TC1 == Type::Record) { 5988 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 5989 return false; 5990 5991 return isLayoutCompatible(C, 5992 cast<RecordType>(T1)->getDecl(), 5993 cast<RecordType>(T2)->getDecl()); 5994 } 5995 5996 return false; 5997} 5998} 5999 6000//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 6001 6002namespace { 6003/// \brief Given a type tag expression find the type tag itself. 6004/// 6005/// \param TypeExpr Type tag expression, as it appears in user's code. 6006/// 6007/// \param VD Declaration of an identifier that appears in a type tag. 6008/// 6009/// \param MagicValue Type tag magic value. 6010bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 6011 const ValueDecl **VD, uint64_t *MagicValue) { 6012 while(true) { 6013 if (!TypeExpr) 6014 return false; 6015 6016 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 6017 6018 switch (TypeExpr->getStmtClass()) { 6019 case Stmt::UnaryOperatorClass: { 6020 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 6021 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 6022 TypeExpr = UO->getSubExpr(); 6023 continue; 6024 } 6025 return false; 6026 } 6027 6028 case Stmt::DeclRefExprClass: { 6029 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 6030 *VD = DRE->getDecl(); 6031 return true; 6032 } 6033 6034 case Stmt::IntegerLiteralClass: { 6035 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 6036 llvm::APInt MagicValueAPInt = IL->getValue(); 6037 if (MagicValueAPInt.getActiveBits() <= 64) { 6038 *MagicValue = MagicValueAPInt.getZExtValue(); 6039 return true; 6040 } else 6041 return false; 6042 } 6043 6044 case Stmt::BinaryConditionalOperatorClass: 6045 case Stmt::ConditionalOperatorClass: { 6046 const AbstractConditionalOperator *ACO = 6047 cast<AbstractConditionalOperator>(TypeExpr); 6048 bool Result; 6049 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 6050 if (Result) 6051 TypeExpr = ACO->getTrueExpr(); 6052 else 6053 TypeExpr = ACO->getFalseExpr(); 6054 continue; 6055 } 6056 return false; 6057 } 6058 6059 case Stmt::BinaryOperatorClass: { 6060 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 6061 if (BO->getOpcode() == BO_Comma) { 6062 TypeExpr = BO->getRHS(); 6063 continue; 6064 } 6065 return false; 6066 } 6067 6068 default: 6069 return false; 6070 } 6071 } 6072} 6073 6074/// \brief Retrieve the C type corresponding to type tag TypeExpr. 6075/// 6076/// \param TypeExpr Expression that specifies a type tag. 6077/// 6078/// \param MagicValues Registered magic values. 6079/// 6080/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 6081/// kind. 6082/// 6083/// \param TypeInfo Information about the corresponding C type. 6084/// 6085/// \returns true if the corresponding C type was found. 6086bool GetMatchingCType( 6087 const IdentifierInfo *ArgumentKind, 6088 const Expr *TypeExpr, const ASTContext &Ctx, 6089 const llvm::DenseMap<Sema::TypeTagMagicValue, 6090 Sema::TypeTagData> *MagicValues, 6091 bool &FoundWrongKind, 6092 Sema::TypeTagData &TypeInfo) { 6093 FoundWrongKind = false; 6094 6095 // Variable declaration that has type_tag_for_datatype attribute. 6096 const ValueDecl *VD = NULL; 6097 6098 uint64_t MagicValue; 6099 6100 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 6101 return false; 6102 6103 if (VD) { 6104 for (specific_attr_iterator<TypeTagForDatatypeAttr> 6105 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(), 6106 E = VD->specific_attr_end<TypeTagForDatatypeAttr>(); 6107 I != E; ++I) { 6108 if (I->getArgumentKind() != ArgumentKind) { 6109 FoundWrongKind = true; 6110 return false; 6111 } 6112 TypeInfo.Type = I->getMatchingCType(); 6113 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 6114 TypeInfo.MustBeNull = I->getMustBeNull(); 6115 return true; 6116 } 6117 return false; 6118 } 6119 6120 if (!MagicValues) 6121 return false; 6122 6123 llvm::DenseMap<Sema::TypeTagMagicValue, 6124 Sema::TypeTagData>::const_iterator I = 6125 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 6126 if (I == MagicValues->end()) 6127 return false; 6128 6129 TypeInfo = I->second; 6130 return true; 6131} 6132} // unnamed namespace 6133 6134void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 6135 uint64_t MagicValue, QualType Type, 6136 bool LayoutCompatible, 6137 bool MustBeNull) { 6138 if (!TypeTagForDatatypeMagicValues) 6139 TypeTagForDatatypeMagicValues.reset( 6140 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 6141 6142 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 6143 (*TypeTagForDatatypeMagicValues)[Magic] = 6144 TypeTagData(Type, LayoutCompatible, MustBeNull); 6145} 6146 6147namespace { 6148bool IsSameCharType(QualType T1, QualType T2) { 6149 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 6150 if (!BT1) 6151 return false; 6152 6153 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 6154 if (!BT2) 6155 return false; 6156 6157 BuiltinType::Kind T1Kind = BT1->getKind(); 6158 BuiltinType::Kind T2Kind = BT2->getKind(); 6159 6160 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 6161 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 6162 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 6163 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 6164} 6165} // unnamed namespace 6166 6167void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 6168 const Expr * const *ExprArgs) { 6169 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 6170 bool IsPointerAttr = Attr->getIsPointer(); 6171 6172 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 6173 bool FoundWrongKind; 6174 TypeTagData TypeInfo; 6175 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 6176 TypeTagForDatatypeMagicValues.get(), 6177 FoundWrongKind, TypeInfo)) { 6178 if (FoundWrongKind) 6179 Diag(TypeTagExpr->getExprLoc(), 6180 diag::warn_type_tag_for_datatype_wrong_kind) 6181 << TypeTagExpr->getSourceRange(); 6182 return; 6183 } 6184 6185 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 6186 if (IsPointerAttr) { 6187 // Skip implicit cast of pointer to `void *' (as a function argument). 6188 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 6189 if (ICE->getType()->isVoidPointerType()) 6190 ArgumentExpr = ICE->getSubExpr(); 6191 } 6192 QualType ArgumentType = ArgumentExpr->getType(); 6193 6194 // Passing a `void*' pointer shouldn't trigger a warning. 6195 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 6196 return; 6197 6198 if (TypeInfo.MustBeNull) { 6199 // Type tag with matching void type requires a null pointer. 6200 if (!ArgumentExpr->isNullPointerConstant(Context, 6201 Expr::NPC_ValueDependentIsNotNull)) { 6202 Diag(ArgumentExpr->getExprLoc(), 6203 diag::warn_type_safety_null_pointer_required) 6204 << ArgumentKind->getName() 6205 << ArgumentExpr->getSourceRange() 6206 << TypeTagExpr->getSourceRange(); 6207 } 6208 return; 6209 } 6210 6211 QualType RequiredType = TypeInfo.Type; 6212 if (IsPointerAttr) 6213 RequiredType = Context.getPointerType(RequiredType); 6214 6215 bool mismatch = false; 6216 if (!TypeInfo.LayoutCompatible) { 6217 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 6218 6219 // C++11 [basic.fundamental] p1: 6220 // Plain char, signed char, and unsigned char are three distinct types. 6221 // 6222 // But we treat plain `char' as equivalent to `signed char' or `unsigned 6223 // char' depending on the current char signedness mode. 6224 if (mismatch) 6225 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 6226 RequiredType->getPointeeType())) || 6227 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 6228 mismatch = false; 6229 } else 6230 if (IsPointerAttr) 6231 mismatch = !isLayoutCompatible(Context, 6232 ArgumentType->getPointeeType(), 6233 RequiredType->getPointeeType()); 6234 else 6235 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 6236 6237 if (mismatch) 6238 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 6239 << ArgumentType << ArgumentKind->getName() 6240 << TypeInfo.LayoutCompatible << RequiredType 6241 << ArgumentExpr->getSourceRange() 6242 << TypeTagExpr->getSourceRange(); 6243} 6244