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