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