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