SemaChecking.cpp revision 29c3f814b64808c6dac4597b61a50ceecdf141fc
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements extra semantic analysis beyond what is enforced 11// by the C type system. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/Initialization.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/Analysis/Analyses/FormatString.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/DeclCXX.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/EvaluatedExprVisitor.h" 28#include "clang/AST/DeclObjC.h" 29#include "clang/AST/StmtCXX.h" 30#include "clang/AST/StmtObjC.h" 31#include "clang/Lex/Preprocessor.h" 32#include "llvm/ADT/BitVector.h" 33#include "llvm/ADT/STLExtras.h" 34#include "llvm/Support/raw_ostream.h" 35#include "clang/Basic/TargetBuiltins.h" 36#include "clang/Basic/TargetInfo.h" 37#include "clang/Basic/ConvertUTF.h" 38#include <limits> 39using namespace clang; 40using namespace sema; 41 42SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 43 unsigned ByteNo) const { 44 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 45 PP.getLangOptions(), PP.getTargetInfo()); 46} 47 48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, Expr **Args, 49 unsigned NumArgs, bool IsCXXMemberCall) { 50 StringRef Type = Format->getType(); 51 // FIXME: add support for "CFString" Type. They are not string literal though, 52 // so they need special handling. 53 if (Type == "printf" || Type == "NSString") return true; 54 if (Type == "printf0") { 55 // printf0 allows null "format" string; if so don't check format/args 56 unsigned format_idx = Format->getFormatIdx() - 1; 57 // Does the index refer to the implicit object argument? 58 if (IsCXXMemberCall) { 59 if (format_idx == 0) 60 return false; 61 --format_idx; 62 } 63 if (format_idx < NumArgs) { 64 Expr *Format = Args[format_idx]->IgnoreParenCasts(); 65 if (!Format->isNullPointerConstant(Context, 66 Expr::NPC_ValueDependentIsNull)) 67 return true; 68 } 69 } 70 return false; 71} 72 73/// Checks that a call expression's argument count is the desired number. 74/// This is useful when doing custom type-checking. Returns true on error. 75static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 76 unsigned argCount = call->getNumArgs(); 77 if (argCount == desiredArgCount) return false; 78 79 if (argCount < desiredArgCount) 80 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 81 << 0 /*function call*/ << desiredArgCount << argCount 82 << call->getSourceRange(); 83 84 // Highlight all the excess arguments. 85 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 86 call->getArg(argCount - 1)->getLocEnd()); 87 88 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 89 << 0 /*function call*/ << desiredArgCount << argCount 90 << call->getArg(1)->getSourceRange(); 91} 92 93/// CheckBuiltinAnnotationString - Checks that string argument to the builtin 94/// annotation is a non wide string literal. 95static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) { 96 Arg = Arg->IgnoreParenCasts(); 97 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 98 if (!Literal || !Literal->isAscii()) { 99 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant) 100 << Arg->getSourceRange(); 101 return true; 102 } 103 return false; 104} 105 106ExprResult 107Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 108 ExprResult TheCallResult(Owned(TheCall)); 109 110 // Find out if any arguments are required to be integer constant expressions. 111 unsigned ICEArguments = 0; 112 ASTContext::GetBuiltinTypeError Error; 113 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 114 if (Error != ASTContext::GE_None) 115 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 116 117 // If any arguments are required to be ICE's, check and diagnose. 118 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 119 // Skip arguments not required to be ICE's. 120 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 121 122 llvm::APSInt Result; 123 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 124 return true; 125 ICEArguments &= ~(1 << ArgNo); 126 } 127 128 switch (BuiltinID) { 129 case Builtin::BI__builtin___CFStringMakeConstantString: 130 assert(TheCall->getNumArgs() == 1 && 131 "Wrong # arguments to builtin CFStringMakeConstantString"); 132 if (CheckObjCString(TheCall->getArg(0))) 133 return ExprError(); 134 break; 135 case Builtin::BI__builtin_stdarg_start: 136 case Builtin::BI__builtin_va_start: 137 if (SemaBuiltinVAStart(TheCall)) 138 return ExprError(); 139 break; 140 case Builtin::BI__builtin_isgreater: 141 case Builtin::BI__builtin_isgreaterequal: 142 case Builtin::BI__builtin_isless: 143 case Builtin::BI__builtin_islessequal: 144 case Builtin::BI__builtin_islessgreater: 145 case Builtin::BI__builtin_isunordered: 146 if (SemaBuiltinUnorderedCompare(TheCall)) 147 return ExprError(); 148 break; 149 case Builtin::BI__builtin_fpclassify: 150 if (SemaBuiltinFPClassification(TheCall, 6)) 151 return ExprError(); 152 break; 153 case Builtin::BI__builtin_isfinite: 154 case Builtin::BI__builtin_isinf: 155 case Builtin::BI__builtin_isinf_sign: 156 case Builtin::BI__builtin_isnan: 157 case Builtin::BI__builtin_isnormal: 158 if (SemaBuiltinFPClassification(TheCall, 1)) 159 return ExprError(); 160 break; 161 case Builtin::BI__builtin_shufflevector: 162 return SemaBuiltinShuffleVector(TheCall); 163 // TheCall will be freed by the smart pointer here, but that's fine, since 164 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 165 case Builtin::BI__builtin_prefetch: 166 if (SemaBuiltinPrefetch(TheCall)) 167 return ExprError(); 168 break; 169 case Builtin::BI__builtin_object_size: 170 if (SemaBuiltinObjectSize(TheCall)) 171 return ExprError(); 172 break; 173 case Builtin::BI__builtin_longjmp: 174 if (SemaBuiltinLongjmp(TheCall)) 175 return ExprError(); 176 break; 177 178 case Builtin::BI__builtin_classify_type: 179 if (checkArgCount(*this, TheCall, 1)) return true; 180 TheCall->setType(Context.IntTy); 181 break; 182 case Builtin::BI__builtin_constant_p: 183 if (checkArgCount(*this, TheCall, 1)) return true; 184 TheCall->setType(Context.IntTy); 185 break; 186 case Builtin::BI__sync_fetch_and_add: 187 case Builtin::BI__sync_fetch_and_add_1: 188 case Builtin::BI__sync_fetch_and_add_2: 189 case Builtin::BI__sync_fetch_and_add_4: 190 case Builtin::BI__sync_fetch_and_add_8: 191 case Builtin::BI__sync_fetch_and_add_16: 192 case Builtin::BI__sync_fetch_and_sub: 193 case Builtin::BI__sync_fetch_and_sub_1: 194 case Builtin::BI__sync_fetch_and_sub_2: 195 case Builtin::BI__sync_fetch_and_sub_4: 196 case Builtin::BI__sync_fetch_and_sub_8: 197 case Builtin::BI__sync_fetch_and_sub_16: 198 case Builtin::BI__sync_fetch_and_or: 199 case Builtin::BI__sync_fetch_and_or_1: 200 case Builtin::BI__sync_fetch_and_or_2: 201 case Builtin::BI__sync_fetch_and_or_4: 202 case Builtin::BI__sync_fetch_and_or_8: 203 case Builtin::BI__sync_fetch_and_or_16: 204 case Builtin::BI__sync_fetch_and_and: 205 case Builtin::BI__sync_fetch_and_and_1: 206 case Builtin::BI__sync_fetch_and_and_2: 207 case Builtin::BI__sync_fetch_and_and_4: 208 case Builtin::BI__sync_fetch_and_and_8: 209 case Builtin::BI__sync_fetch_and_and_16: 210 case Builtin::BI__sync_fetch_and_xor: 211 case Builtin::BI__sync_fetch_and_xor_1: 212 case Builtin::BI__sync_fetch_and_xor_2: 213 case Builtin::BI__sync_fetch_and_xor_4: 214 case Builtin::BI__sync_fetch_and_xor_8: 215 case Builtin::BI__sync_fetch_and_xor_16: 216 case Builtin::BI__sync_add_and_fetch: 217 case Builtin::BI__sync_add_and_fetch_1: 218 case Builtin::BI__sync_add_and_fetch_2: 219 case Builtin::BI__sync_add_and_fetch_4: 220 case Builtin::BI__sync_add_and_fetch_8: 221 case Builtin::BI__sync_add_and_fetch_16: 222 case Builtin::BI__sync_sub_and_fetch: 223 case Builtin::BI__sync_sub_and_fetch_1: 224 case Builtin::BI__sync_sub_and_fetch_2: 225 case Builtin::BI__sync_sub_and_fetch_4: 226 case Builtin::BI__sync_sub_and_fetch_8: 227 case Builtin::BI__sync_sub_and_fetch_16: 228 case Builtin::BI__sync_and_and_fetch: 229 case Builtin::BI__sync_and_and_fetch_1: 230 case Builtin::BI__sync_and_and_fetch_2: 231 case Builtin::BI__sync_and_and_fetch_4: 232 case Builtin::BI__sync_and_and_fetch_8: 233 case Builtin::BI__sync_and_and_fetch_16: 234 case Builtin::BI__sync_or_and_fetch: 235 case Builtin::BI__sync_or_and_fetch_1: 236 case Builtin::BI__sync_or_and_fetch_2: 237 case Builtin::BI__sync_or_and_fetch_4: 238 case Builtin::BI__sync_or_and_fetch_8: 239 case Builtin::BI__sync_or_and_fetch_16: 240 case Builtin::BI__sync_xor_and_fetch: 241 case Builtin::BI__sync_xor_and_fetch_1: 242 case Builtin::BI__sync_xor_and_fetch_2: 243 case Builtin::BI__sync_xor_and_fetch_4: 244 case Builtin::BI__sync_xor_and_fetch_8: 245 case Builtin::BI__sync_xor_and_fetch_16: 246 case Builtin::BI__sync_val_compare_and_swap: 247 case Builtin::BI__sync_val_compare_and_swap_1: 248 case Builtin::BI__sync_val_compare_and_swap_2: 249 case Builtin::BI__sync_val_compare_and_swap_4: 250 case Builtin::BI__sync_val_compare_and_swap_8: 251 case Builtin::BI__sync_val_compare_and_swap_16: 252 case Builtin::BI__sync_bool_compare_and_swap: 253 case Builtin::BI__sync_bool_compare_and_swap_1: 254 case Builtin::BI__sync_bool_compare_and_swap_2: 255 case Builtin::BI__sync_bool_compare_and_swap_4: 256 case Builtin::BI__sync_bool_compare_and_swap_8: 257 case Builtin::BI__sync_bool_compare_and_swap_16: 258 case Builtin::BI__sync_lock_test_and_set: 259 case Builtin::BI__sync_lock_test_and_set_1: 260 case Builtin::BI__sync_lock_test_and_set_2: 261 case Builtin::BI__sync_lock_test_and_set_4: 262 case Builtin::BI__sync_lock_test_and_set_8: 263 case Builtin::BI__sync_lock_test_and_set_16: 264 case Builtin::BI__sync_lock_release: 265 case Builtin::BI__sync_lock_release_1: 266 case Builtin::BI__sync_lock_release_2: 267 case Builtin::BI__sync_lock_release_4: 268 case Builtin::BI__sync_lock_release_8: 269 case Builtin::BI__sync_lock_release_16: 270 case Builtin::BI__sync_swap: 271 case Builtin::BI__sync_swap_1: 272 case Builtin::BI__sync_swap_2: 273 case Builtin::BI__sync_swap_4: 274 case Builtin::BI__sync_swap_8: 275 case Builtin::BI__sync_swap_16: 276 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 277 case Builtin::BI__atomic_load: 278 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load); 279 case Builtin::BI__atomic_store: 280 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store); 281 case Builtin::BI__atomic_init: 282 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init); 283 case Builtin::BI__atomic_exchange: 284 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg); 285 case Builtin::BI__atomic_compare_exchange_strong: 286 return SemaAtomicOpsOverloaded(move(TheCallResult), 287 AtomicExpr::CmpXchgStrong); 288 case Builtin::BI__atomic_compare_exchange_weak: 289 return SemaAtomicOpsOverloaded(move(TheCallResult), 290 AtomicExpr::CmpXchgWeak); 291 case Builtin::BI__atomic_fetch_add: 292 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add); 293 case Builtin::BI__atomic_fetch_sub: 294 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub); 295 case Builtin::BI__atomic_fetch_and: 296 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And); 297 case Builtin::BI__atomic_fetch_or: 298 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or); 299 case Builtin::BI__atomic_fetch_xor: 300 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor); 301 case Builtin::BI__builtin_annotation: 302 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1))) 303 return ExprError(); 304 break; 305 } 306 307 // Since the target specific builtins for each arch overlap, only check those 308 // of the arch we are compiling for. 309 if (BuiltinID >= Builtin::FirstTSBuiltin) { 310 switch (Context.getTargetInfo().getTriple().getArch()) { 311 case llvm::Triple::arm: 312 case llvm::Triple::thumb: 313 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 314 return ExprError(); 315 break; 316 default: 317 break; 318 } 319 } 320 321 return move(TheCallResult); 322} 323 324// Get the valid immediate range for the specified NEON type code. 325static unsigned RFT(unsigned t, bool shift = false) { 326 NeonTypeFlags Type(t); 327 int IsQuad = Type.isQuad(); 328 switch (Type.getEltType()) { 329 case NeonTypeFlags::Int8: 330 case NeonTypeFlags::Poly8: 331 return shift ? 7 : (8 << IsQuad) - 1; 332 case NeonTypeFlags::Int16: 333 case NeonTypeFlags::Poly16: 334 return shift ? 15 : (4 << IsQuad) - 1; 335 case NeonTypeFlags::Int32: 336 return shift ? 31 : (2 << IsQuad) - 1; 337 case NeonTypeFlags::Int64: 338 return shift ? 63 : (1 << IsQuad) - 1; 339 case NeonTypeFlags::Float16: 340 assert(!shift && "cannot shift float types!"); 341 return (4 << IsQuad) - 1; 342 case NeonTypeFlags::Float32: 343 assert(!shift && "cannot shift float types!"); 344 return (2 << IsQuad) - 1; 345 } 346 llvm_unreachable("Invalid NeonTypeFlag!"); 347} 348 349/// getNeonEltType - Return the QualType corresponding to the elements of 350/// the vector type specified by the NeonTypeFlags. This is used to check 351/// the pointer arguments for Neon load/store intrinsics. 352static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 353 switch (Flags.getEltType()) { 354 case NeonTypeFlags::Int8: 355 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 356 case NeonTypeFlags::Int16: 357 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 358 case NeonTypeFlags::Int32: 359 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 360 case NeonTypeFlags::Int64: 361 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 362 case NeonTypeFlags::Poly8: 363 return Context.SignedCharTy; 364 case NeonTypeFlags::Poly16: 365 return Context.ShortTy; 366 case NeonTypeFlags::Float16: 367 return Context.UnsignedShortTy; 368 case NeonTypeFlags::Float32: 369 return Context.FloatTy; 370 } 371 llvm_unreachable("Invalid NeonTypeFlag!"); 372} 373 374bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 375 llvm::APSInt Result; 376 377 unsigned mask = 0; 378 unsigned TV = 0; 379 int PtrArgNum = -1; 380 bool HasConstPtr = false; 381 switch (BuiltinID) { 382#define GET_NEON_OVERLOAD_CHECK 383#include "clang/Basic/arm_neon.inc" 384#undef GET_NEON_OVERLOAD_CHECK 385 } 386 387 // For NEON intrinsics which are overloaded on vector element type, validate 388 // the immediate which specifies which variant to emit. 389 unsigned ImmArg = TheCall->getNumArgs()-1; 390 if (mask) { 391 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 392 return true; 393 394 TV = Result.getLimitedValue(64); 395 if ((TV > 63) || (mask & (1 << TV)) == 0) 396 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 397 << TheCall->getArg(ImmArg)->getSourceRange(); 398 } 399 400 if (PtrArgNum >= 0) { 401 // Check that pointer arguments have the specified type. 402 Expr *Arg = TheCall->getArg(PtrArgNum); 403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 404 Arg = ICE->getSubExpr(); 405 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 406 QualType RHSTy = RHS.get()->getType(); 407 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 408 if (HasConstPtr) 409 EltTy = EltTy.withConst(); 410 QualType LHSTy = Context.getPointerType(EltTy); 411 AssignConvertType ConvTy; 412 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 413 if (RHS.isInvalid()) 414 return true; 415 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 416 RHS.get(), AA_Assigning)) 417 return true; 418 } 419 420 // For NEON intrinsics which take an immediate value as part of the 421 // instruction, range check them here. 422 unsigned i = 0, l = 0, u = 0; 423 switch (BuiltinID) { 424 default: return false; 425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 427 case ARM::BI__builtin_arm_vcvtr_f: 428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 429#define GET_NEON_IMMEDIATE_CHECK 430#include "clang/Basic/arm_neon.inc" 431#undef GET_NEON_IMMEDIATE_CHECK 432 }; 433 434 // Check that the immediate argument is actually a constant. 435 if (SemaBuiltinConstantArg(TheCall, i, Result)) 436 return true; 437 438 // Range check against the upper/lower values for this isntruction. 439 unsigned Val = Result.getZExtValue(); 440 if (Val < l || Val > (u + l)) 441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 442 << l << u+l << TheCall->getArg(i)->getSourceRange(); 443 444 // FIXME: VFP Intrinsics should error if VFP not present. 445 return false; 446} 447 448/// CheckFunctionCall - Check a direct function call for various correctness 449/// and safety properties not strictly enforced by the C type system. 450bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 451 // Get the IdentifierInfo* for the called function. 452 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 453 454 // None of the checks below are needed for functions that don't have 455 // simple names (e.g., C++ conversion functions). 456 if (!FnInfo) 457 return false; 458 459 // FIXME: This mechanism should be abstracted to be less fragile and 460 // more efficient. For example, just map function ids to custom 461 // handlers. 462 463 // Printf and scanf checking. 464 for (specific_attr_iterator<FormatAttr> 465 i = FDecl->specific_attr_begin<FormatAttr>(), 466 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 467 CheckFormatArguments(*i, TheCall); 468 } 469 470 for (specific_attr_iterator<NonNullAttr> 471 i = FDecl->specific_attr_begin<NonNullAttr>(), 472 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 473 CheckNonNullArguments(*i, TheCall->getArgs(), 474 TheCall->getCallee()->getLocStart()); 475 } 476 477 unsigned CMId = FDecl->getMemoryFunctionKind(); 478 if (CMId == 0) 479 return false; 480 481 // Handle memory setting and copying functions. 482 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 483 CheckStrlcpycatArguments(TheCall, FnInfo); 484 else 485 CheckMemaccessArguments(TheCall, CMId, FnInfo); 486 487 return false; 488} 489 490bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 491 Expr **Args, unsigned NumArgs) { 492 for (specific_attr_iterator<FormatAttr> 493 i = Method->specific_attr_begin<FormatAttr>(), 494 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) { 495 496 CheckFormatArguments(*i, Args, NumArgs, false, lbrac, 497 Method->getSourceRange()); 498 } 499 500 // diagnose nonnull arguments. 501 for (specific_attr_iterator<NonNullAttr> 502 i = Method->specific_attr_begin<NonNullAttr>(), 503 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) { 504 CheckNonNullArguments(*i, Args, lbrac); 505 } 506 507 return false; 508} 509 510bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 511 // Printf checking. 512 const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 513 if (!Format) 514 return false; 515 516 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 517 if (!V) 518 return false; 519 520 QualType Ty = V->getType(); 521 if (!Ty->isBlockPointerType()) 522 return false; 523 524 CheckFormatArguments(Format, TheCall); 525 526 return false; 527} 528 529ExprResult 530Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) { 531 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 532 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 533 534 // All these operations take one of the following four forms: 535 // T __atomic_load(_Atomic(T)*, int) (loads) 536 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub) 537 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int) 538 // (cmpxchg) 539 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else) 540 // where T is an appropriate type, and the int paremeterss are for orderings. 541 unsigned NumVals = 1; 542 unsigned NumOrders = 1; 543 if (Op == AtomicExpr::Load) { 544 NumVals = 0; 545 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) { 546 NumVals = 2; 547 NumOrders = 2; 548 } 549 if (Op == AtomicExpr::Init) 550 NumOrders = 0; 551 552 if (TheCall->getNumArgs() < NumVals+NumOrders+1) { 553 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 555 << TheCall->getCallee()->getSourceRange(); 556 return ExprError(); 557 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) { 558 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(), 559 diag::err_typecheck_call_too_many_args) 560 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 561 << TheCall->getCallee()->getSourceRange(); 562 return ExprError(); 563 } 564 565 // Inspect the first argument of the atomic operation. This should always be 566 // a pointer to an _Atomic type. 567 Expr *Ptr = TheCall->getArg(0); 568 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 569 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 570 if (!pointerType) { 571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 572 << Ptr->getType() << Ptr->getSourceRange(); 573 return ExprError(); 574 } 575 576 QualType AtomTy = pointerType->getPointeeType(); 577 if (!AtomTy->isAtomicType()) { 578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 579 << Ptr->getType() << Ptr->getSourceRange(); 580 return ExprError(); 581 } 582 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType(); 583 584 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) && 585 !ValType->isIntegerType() && !ValType->isPointerType()) { 586 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 587 << Ptr->getType() << Ptr->getSourceRange(); 588 return ExprError(); 589 } 590 591 if (!ValType->isIntegerType() && 592 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){ 593 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int) 594 << Ptr->getType() << Ptr->getSourceRange(); 595 return ExprError(); 596 } 597 598 switch (ValType.getObjCLifetime()) { 599 case Qualifiers::OCL_None: 600 case Qualifiers::OCL_ExplicitNone: 601 // okay 602 break; 603 604 case Qualifiers::OCL_Weak: 605 case Qualifiers::OCL_Strong: 606 case Qualifiers::OCL_Autoreleasing: 607 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 608 << ValType << Ptr->getSourceRange(); 609 return ExprError(); 610 } 611 612 QualType ResultType = ValType; 613 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init) 614 ResultType = Context.VoidTy; 615 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) 616 ResultType = Context.BoolTy; 617 618 // The first argument --- the pointer --- has a fixed type; we 619 // deduce the types of the rest of the arguments accordingly. Walk 620 // the remaining arguments, converting them to the deduced value type. 621 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) { 622 ExprResult Arg = TheCall->getArg(i); 623 QualType Ty; 624 if (i < NumVals+1) { 625 // The second argument to a cmpxchg is a pointer to the data which will 626 // be exchanged. The second argument to a pointer add/subtract is the 627 // amount to add/subtract, which must be a ptrdiff_t. The third 628 // argument to a cmpxchg and the second argument in all other cases 629 // is the type of the value. 630 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak || 631 Op == AtomicExpr::CmpXchgStrong)) 632 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 633 else if (!ValType->isIntegerType() && 634 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub)) 635 Ty = Context.getPointerDiffType(); 636 else 637 Ty = ValType; 638 } else { 639 // The order(s) are always converted to int. 640 Ty = Context.IntTy; 641 } 642 InitializedEntity Entity = 643 InitializedEntity::InitializeParameter(Context, Ty, false); 644 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 645 if (Arg.isInvalid()) 646 return true; 647 TheCall->setArg(i, Arg.get()); 648 } 649 650 SmallVector<Expr*, 5> SubExprs; 651 SubExprs.push_back(Ptr); 652 if (Op == AtomicExpr::Load) { 653 SubExprs.push_back(TheCall->getArg(1)); // Order 654 } else if (Op == AtomicExpr::Init) { 655 SubExprs.push_back(TheCall->getArg(1)); // Val1 656 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) { 657 SubExprs.push_back(TheCall->getArg(2)); // Order 658 SubExprs.push_back(TheCall->getArg(1)); // Val1 659 } else { 660 SubExprs.push_back(TheCall->getArg(3)); // Order 661 SubExprs.push_back(TheCall->getArg(1)); // Val1 662 SubExprs.push_back(TheCall->getArg(2)); // Val2 663 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 664 } 665 666 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 667 SubExprs.data(), SubExprs.size(), 668 ResultType, Op, 669 TheCall->getRParenLoc())); 670} 671 672 673/// checkBuiltinArgument - Given a call to a builtin function, perform 674/// normal type-checking on the given argument, updating the call in 675/// place. This is useful when a builtin function requires custom 676/// type-checking for some of its arguments but not necessarily all of 677/// them. 678/// 679/// Returns true on error. 680static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 681 FunctionDecl *Fn = E->getDirectCallee(); 682 assert(Fn && "builtin call without direct callee!"); 683 684 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 685 InitializedEntity Entity = 686 InitializedEntity::InitializeParameter(S.Context, Param); 687 688 ExprResult Arg = E->getArg(0); 689 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 690 if (Arg.isInvalid()) 691 return true; 692 693 E->setArg(ArgIndex, Arg.take()); 694 return false; 695} 696 697/// SemaBuiltinAtomicOverloaded - We have a call to a function like 698/// __sync_fetch_and_add, which is an overloaded function based on the pointer 699/// type of its first argument. The main ActOnCallExpr routines have already 700/// promoted the types of arguments because all of these calls are prototyped as 701/// void(...). 702/// 703/// This function goes through and does final semantic checking for these 704/// builtins, 705ExprResult 706Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 707 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 708 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 709 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 710 711 // Ensure that we have at least one argument to do type inference from. 712 if (TheCall->getNumArgs() < 1) { 713 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 714 << 0 << 1 << TheCall->getNumArgs() 715 << TheCall->getCallee()->getSourceRange(); 716 return ExprError(); 717 } 718 719 // Inspect the first argument of the atomic builtin. This should always be 720 // a pointer type, whose element is an integral scalar or pointer type. 721 // Because it is a pointer type, we don't have to worry about any implicit 722 // casts here. 723 // FIXME: We don't allow floating point scalars as input. 724 Expr *FirstArg = TheCall->getArg(0); 725 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 726 if (!pointerType) { 727 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 728 << FirstArg->getType() << FirstArg->getSourceRange(); 729 return ExprError(); 730 } 731 732 QualType ValType = pointerType->getPointeeType(); 733 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 734 !ValType->isBlockPointerType()) { 735 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 736 << FirstArg->getType() << FirstArg->getSourceRange(); 737 return ExprError(); 738 } 739 740 switch (ValType.getObjCLifetime()) { 741 case Qualifiers::OCL_None: 742 case Qualifiers::OCL_ExplicitNone: 743 // okay 744 break; 745 746 case Qualifiers::OCL_Weak: 747 case Qualifiers::OCL_Strong: 748 case Qualifiers::OCL_Autoreleasing: 749 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 750 << ValType << FirstArg->getSourceRange(); 751 return ExprError(); 752 } 753 754 // Strip any qualifiers off ValType. 755 ValType = ValType.getUnqualifiedType(); 756 757 // The majority of builtins return a value, but a few have special return 758 // types, so allow them to override appropriately below. 759 QualType ResultType = ValType; 760 761 // We need to figure out which concrete builtin this maps onto. For example, 762 // __sync_fetch_and_add with a 2 byte object turns into 763 // __sync_fetch_and_add_2. 764#define BUILTIN_ROW(x) \ 765 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 766 Builtin::BI##x##_8, Builtin::BI##x##_16 } 767 768 static const unsigned BuiltinIndices[][5] = { 769 BUILTIN_ROW(__sync_fetch_and_add), 770 BUILTIN_ROW(__sync_fetch_and_sub), 771 BUILTIN_ROW(__sync_fetch_and_or), 772 BUILTIN_ROW(__sync_fetch_and_and), 773 BUILTIN_ROW(__sync_fetch_and_xor), 774 775 BUILTIN_ROW(__sync_add_and_fetch), 776 BUILTIN_ROW(__sync_sub_and_fetch), 777 BUILTIN_ROW(__sync_and_and_fetch), 778 BUILTIN_ROW(__sync_or_and_fetch), 779 BUILTIN_ROW(__sync_xor_and_fetch), 780 781 BUILTIN_ROW(__sync_val_compare_and_swap), 782 BUILTIN_ROW(__sync_bool_compare_and_swap), 783 BUILTIN_ROW(__sync_lock_test_and_set), 784 BUILTIN_ROW(__sync_lock_release), 785 BUILTIN_ROW(__sync_swap) 786 }; 787#undef BUILTIN_ROW 788 789 // Determine the index of the size. 790 unsigned SizeIndex; 791 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 792 case 1: SizeIndex = 0; break; 793 case 2: SizeIndex = 1; break; 794 case 4: SizeIndex = 2; break; 795 case 8: SizeIndex = 3; break; 796 case 16: SizeIndex = 4; break; 797 default: 798 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 799 << FirstArg->getType() << FirstArg->getSourceRange(); 800 return ExprError(); 801 } 802 803 // Each of these builtins has one pointer argument, followed by some number of 804 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 805 // that we ignore. Find out which row of BuiltinIndices to read from as well 806 // as the number of fixed args. 807 unsigned BuiltinID = FDecl->getBuiltinID(); 808 unsigned BuiltinIndex, NumFixed = 1; 809 switch (BuiltinID) { 810 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 811 case Builtin::BI__sync_fetch_and_add: 812 case Builtin::BI__sync_fetch_and_add_1: 813 case Builtin::BI__sync_fetch_and_add_2: 814 case Builtin::BI__sync_fetch_and_add_4: 815 case Builtin::BI__sync_fetch_and_add_8: 816 case Builtin::BI__sync_fetch_and_add_16: 817 BuiltinIndex = 0; 818 break; 819 820 case Builtin::BI__sync_fetch_and_sub: 821 case Builtin::BI__sync_fetch_and_sub_1: 822 case Builtin::BI__sync_fetch_and_sub_2: 823 case Builtin::BI__sync_fetch_and_sub_4: 824 case Builtin::BI__sync_fetch_and_sub_8: 825 case Builtin::BI__sync_fetch_and_sub_16: 826 BuiltinIndex = 1; 827 break; 828 829 case Builtin::BI__sync_fetch_and_or: 830 case Builtin::BI__sync_fetch_and_or_1: 831 case Builtin::BI__sync_fetch_and_or_2: 832 case Builtin::BI__sync_fetch_and_or_4: 833 case Builtin::BI__sync_fetch_and_or_8: 834 case Builtin::BI__sync_fetch_and_or_16: 835 BuiltinIndex = 2; 836 break; 837 838 case Builtin::BI__sync_fetch_and_and: 839 case Builtin::BI__sync_fetch_and_and_1: 840 case Builtin::BI__sync_fetch_and_and_2: 841 case Builtin::BI__sync_fetch_and_and_4: 842 case Builtin::BI__sync_fetch_and_and_8: 843 case Builtin::BI__sync_fetch_and_and_16: 844 BuiltinIndex = 3; 845 break; 846 847 case Builtin::BI__sync_fetch_and_xor: 848 case Builtin::BI__sync_fetch_and_xor_1: 849 case Builtin::BI__sync_fetch_and_xor_2: 850 case Builtin::BI__sync_fetch_and_xor_4: 851 case Builtin::BI__sync_fetch_and_xor_8: 852 case Builtin::BI__sync_fetch_and_xor_16: 853 BuiltinIndex = 4; 854 break; 855 856 case Builtin::BI__sync_add_and_fetch: 857 case Builtin::BI__sync_add_and_fetch_1: 858 case Builtin::BI__sync_add_and_fetch_2: 859 case Builtin::BI__sync_add_and_fetch_4: 860 case Builtin::BI__sync_add_and_fetch_8: 861 case Builtin::BI__sync_add_and_fetch_16: 862 BuiltinIndex = 5; 863 break; 864 865 case Builtin::BI__sync_sub_and_fetch: 866 case Builtin::BI__sync_sub_and_fetch_1: 867 case Builtin::BI__sync_sub_and_fetch_2: 868 case Builtin::BI__sync_sub_and_fetch_4: 869 case Builtin::BI__sync_sub_and_fetch_8: 870 case Builtin::BI__sync_sub_and_fetch_16: 871 BuiltinIndex = 6; 872 break; 873 874 case Builtin::BI__sync_and_and_fetch: 875 case Builtin::BI__sync_and_and_fetch_1: 876 case Builtin::BI__sync_and_and_fetch_2: 877 case Builtin::BI__sync_and_and_fetch_4: 878 case Builtin::BI__sync_and_and_fetch_8: 879 case Builtin::BI__sync_and_and_fetch_16: 880 BuiltinIndex = 7; 881 break; 882 883 case Builtin::BI__sync_or_and_fetch: 884 case Builtin::BI__sync_or_and_fetch_1: 885 case Builtin::BI__sync_or_and_fetch_2: 886 case Builtin::BI__sync_or_and_fetch_4: 887 case Builtin::BI__sync_or_and_fetch_8: 888 case Builtin::BI__sync_or_and_fetch_16: 889 BuiltinIndex = 8; 890 break; 891 892 case Builtin::BI__sync_xor_and_fetch: 893 case Builtin::BI__sync_xor_and_fetch_1: 894 case Builtin::BI__sync_xor_and_fetch_2: 895 case Builtin::BI__sync_xor_and_fetch_4: 896 case Builtin::BI__sync_xor_and_fetch_8: 897 case Builtin::BI__sync_xor_and_fetch_16: 898 BuiltinIndex = 9; 899 break; 900 901 case Builtin::BI__sync_val_compare_and_swap: 902 case Builtin::BI__sync_val_compare_and_swap_1: 903 case Builtin::BI__sync_val_compare_and_swap_2: 904 case Builtin::BI__sync_val_compare_and_swap_4: 905 case Builtin::BI__sync_val_compare_and_swap_8: 906 case Builtin::BI__sync_val_compare_and_swap_16: 907 BuiltinIndex = 10; 908 NumFixed = 2; 909 break; 910 911 case Builtin::BI__sync_bool_compare_and_swap: 912 case Builtin::BI__sync_bool_compare_and_swap_1: 913 case Builtin::BI__sync_bool_compare_and_swap_2: 914 case Builtin::BI__sync_bool_compare_and_swap_4: 915 case Builtin::BI__sync_bool_compare_and_swap_8: 916 case Builtin::BI__sync_bool_compare_and_swap_16: 917 BuiltinIndex = 11; 918 NumFixed = 2; 919 ResultType = Context.BoolTy; 920 break; 921 922 case Builtin::BI__sync_lock_test_and_set: 923 case Builtin::BI__sync_lock_test_and_set_1: 924 case Builtin::BI__sync_lock_test_and_set_2: 925 case Builtin::BI__sync_lock_test_and_set_4: 926 case Builtin::BI__sync_lock_test_and_set_8: 927 case Builtin::BI__sync_lock_test_and_set_16: 928 BuiltinIndex = 12; 929 break; 930 931 case Builtin::BI__sync_lock_release: 932 case Builtin::BI__sync_lock_release_1: 933 case Builtin::BI__sync_lock_release_2: 934 case Builtin::BI__sync_lock_release_4: 935 case Builtin::BI__sync_lock_release_8: 936 case Builtin::BI__sync_lock_release_16: 937 BuiltinIndex = 13; 938 NumFixed = 0; 939 ResultType = Context.VoidTy; 940 break; 941 942 case Builtin::BI__sync_swap: 943 case Builtin::BI__sync_swap_1: 944 case Builtin::BI__sync_swap_2: 945 case Builtin::BI__sync_swap_4: 946 case Builtin::BI__sync_swap_8: 947 case Builtin::BI__sync_swap_16: 948 BuiltinIndex = 14; 949 break; 950 } 951 952 // Now that we know how many fixed arguments we expect, first check that we 953 // have at least that many. 954 if (TheCall->getNumArgs() < 1+NumFixed) { 955 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 1+NumFixed << TheCall->getNumArgs() 957 << TheCall->getCallee()->getSourceRange(); 958 return ExprError(); 959 } 960 961 // Get the decl for the concrete builtin from this, we can tell what the 962 // concrete integer type we should convert to is. 963 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 964 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 965 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 966 FunctionDecl *NewBuiltinDecl = 967 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 968 TUScope, false, DRE->getLocStart())); 969 970 // The first argument --- the pointer --- has a fixed type; we 971 // deduce the types of the rest of the arguments accordingly. Walk 972 // the remaining arguments, converting them to the deduced value type. 973 for (unsigned i = 0; i != NumFixed; ++i) { 974 ExprResult Arg = TheCall->getArg(i+1); 975 976 // GCC does an implicit conversion to the pointer or integer ValType. This 977 // can fail in some cases (1i -> int**), check for this error case now. 978 // Initialize the argument. 979 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 980 ValType, /*consume*/ false); 981 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 982 if (Arg.isInvalid()) 983 return ExprError(); 984 985 // Okay, we have something that *can* be converted to the right type. Check 986 // to see if there is a potentially weird extension going on here. This can 987 // happen when you do an atomic operation on something like an char* and 988 // pass in 42. The 42 gets converted to char. This is even more strange 989 // for things like 45.123 -> char, etc. 990 // FIXME: Do this check. 991 TheCall->setArg(i+1, Arg.take()); 992 } 993 994 ASTContext& Context = this->getASTContext(); 995 996 // Create a new DeclRefExpr to refer to the new decl. 997 DeclRefExpr* NewDRE = DeclRefExpr::Create( 998 Context, 999 DRE->getQualifierLoc(), 1000 NewBuiltinDecl, 1001 DRE->getLocation(), 1002 NewBuiltinDecl->getType(), 1003 DRE->getValueKind()); 1004 1005 // Set the callee in the CallExpr. 1006 // FIXME: This leaks the original parens and implicit casts. 1007 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1008 if (PromotedCall.isInvalid()) 1009 return ExprError(); 1010 TheCall->setCallee(PromotedCall.take()); 1011 1012 // Change the result type of the call to match the original value type. This 1013 // is arbitrary, but the codegen for these builtins ins design to handle it 1014 // gracefully. 1015 TheCall->setType(ResultType); 1016 1017 return move(TheCallResult); 1018} 1019 1020/// CheckObjCString - Checks that the argument to the builtin 1021/// CFString constructor is correct 1022/// Note: It might also make sense to do the UTF-16 conversion here (would 1023/// simplify the backend). 1024bool Sema::CheckObjCString(Expr *Arg) { 1025 Arg = Arg->IgnoreParenCasts(); 1026 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1027 1028 if (!Literal || !Literal->isAscii()) { 1029 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1030 << Arg->getSourceRange(); 1031 return true; 1032 } 1033 1034 if (Literal->containsNonAsciiOrNull()) { 1035 StringRef String = Literal->getString(); 1036 unsigned NumBytes = String.size(); 1037 SmallVector<UTF16, 128> ToBuf(NumBytes); 1038 const UTF8 *FromPtr = (UTF8 *)String.data(); 1039 UTF16 *ToPtr = &ToBuf[0]; 1040 1041 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1042 &ToPtr, ToPtr + NumBytes, 1043 strictConversion); 1044 // Check for conversion failure. 1045 if (Result != conversionOK) 1046 Diag(Arg->getLocStart(), 1047 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1048 } 1049 return false; 1050} 1051 1052/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1053/// Emit an error and return true on failure, return false on success. 1054bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1055 Expr *Fn = TheCall->getCallee(); 1056 if (TheCall->getNumArgs() > 2) { 1057 Diag(TheCall->getArg(2)->getLocStart(), 1058 diag::err_typecheck_call_too_many_args) 1059 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1060 << Fn->getSourceRange() 1061 << SourceRange(TheCall->getArg(2)->getLocStart(), 1062 (*(TheCall->arg_end()-1))->getLocEnd()); 1063 return true; 1064 } 1065 1066 if (TheCall->getNumArgs() < 2) { 1067 return Diag(TheCall->getLocEnd(), 1068 diag::err_typecheck_call_too_few_args_at_least) 1069 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1070 } 1071 1072 // Type-check the first argument normally. 1073 if (checkBuiltinArgument(*this, TheCall, 0)) 1074 return true; 1075 1076 // Determine whether the current function is variadic or not. 1077 BlockScopeInfo *CurBlock = getCurBlock(); 1078 bool isVariadic; 1079 if (CurBlock) 1080 isVariadic = CurBlock->TheDecl->isVariadic(); 1081 else if (FunctionDecl *FD = getCurFunctionDecl()) 1082 isVariadic = FD->isVariadic(); 1083 else 1084 isVariadic = getCurMethodDecl()->isVariadic(); 1085 1086 if (!isVariadic) { 1087 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1088 return true; 1089 } 1090 1091 // Verify that the second argument to the builtin is the last argument of the 1092 // current function or method. 1093 bool SecondArgIsLastNamedArgument = false; 1094 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1095 1096 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1097 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1098 // FIXME: This isn't correct for methods (results in bogus warning). 1099 // Get the last formal in the current function. 1100 const ParmVarDecl *LastArg; 1101 if (CurBlock) 1102 LastArg = *(CurBlock->TheDecl->param_end()-1); 1103 else if (FunctionDecl *FD = getCurFunctionDecl()) 1104 LastArg = *(FD->param_end()-1); 1105 else 1106 LastArg = *(getCurMethodDecl()->param_end()-1); 1107 SecondArgIsLastNamedArgument = PV == LastArg; 1108 } 1109 } 1110 1111 if (!SecondArgIsLastNamedArgument) 1112 Diag(TheCall->getArg(1)->getLocStart(), 1113 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1114 return false; 1115} 1116 1117/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1118/// friends. This is declared to take (...), so we have to check everything. 1119bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1120 if (TheCall->getNumArgs() < 2) 1121 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1122 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1123 if (TheCall->getNumArgs() > 2) 1124 return Diag(TheCall->getArg(2)->getLocStart(), 1125 diag::err_typecheck_call_too_many_args) 1126 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1127 << SourceRange(TheCall->getArg(2)->getLocStart(), 1128 (*(TheCall->arg_end()-1))->getLocEnd()); 1129 1130 ExprResult OrigArg0 = TheCall->getArg(0); 1131 ExprResult OrigArg1 = TheCall->getArg(1); 1132 1133 // Do standard promotions between the two arguments, returning their common 1134 // type. 1135 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1136 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1137 return true; 1138 1139 // Make sure any conversions are pushed back into the call; this is 1140 // type safe since unordered compare builtins are declared as "_Bool 1141 // foo(...)". 1142 TheCall->setArg(0, OrigArg0.get()); 1143 TheCall->setArg(1, OrigArg1.get()); 1144 1145 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1146 return false; 1147 1148 // If the common type isn't a real floating type, then the arguments were 1149 // invalid for this operation. 1150 if (!Res->isRealFloatingType()) 1151 return Diag(OrigArg0.get()->getLocStart(), 1152 diag::err_typecheck_call_invalid_ordered_compare) 1153 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1154 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1155 1156 return false; 1157} 1158 1159/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1160/// __builtin_isnan and friends. This is declared to take (...), so we have 1161/// to check everything. We expect the last argument to be a floating point 1162/// value. 1163bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1164 if (TheCall->getNumArgs() < NumArgs) 1165 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1166 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1167 if (TheCall->getNumArgs() > NumArgs) 1168 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1169 diag::err_typecheck_call_too_many_args) 1170 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1171 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1172 (*(TheCall->arg_end()-1))->getLocEnd()); 1173 1174 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1175 1176 if (OrigArg->isTypeDependent()) 1177 return false; 1178 1179 // This operation requires a non-_Complex floating-point number. 1180 if (!OrigArg->getType()->isRealFloatingType()) 1181 return Diag(OrigArg->getLocStart(), 1182 diag::err_typecheck_call_invalid_unary_fp) 1183 << OrigArg->getType() << OrigArg->getSourceRange(); 1184 1185 // If this is an implicit conversion from float -> double, remove it. 1186 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1187 Expr *CastArg = Cast->getSubExpr(); 1188 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1189 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1190 "promotion from float to double is the only expected cast here"); 1191 Cast->setSubExpr(0); 1192 TheCall->setArg(NumArgs-1, CastArg); 1193 OrigArg = CastArg; 1194 } 1195 } 1196 1197 return false; 1198} 1199 1200/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1201// This is declared to take (...), so we have to check everything. 1202ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1203 if (TheCall->getNumArgs() < 2) 1204 return ExprError(Diag(TheCall->getLocEnd(), 1205 diag::err_typecheck_call_too_few_args_at_least) 1206 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1207 << TheCall->getSourceRange()); 1208 1209 // Determine which of the following types of shufflevector we're checking: 1210 // 1) unary, vector mask: (lhs, mask) 1211 // 2) binary, vector mask: (lhs, rhs, mask) 1212 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1213 QualType resType = TheCall->getArg(0)->getType(); 1214 unsigned numElements = 0; 1215 1216 if (!TheCall->getArg(0)->isTypeDependent() && 1217 !TheCall->getArg(1)->isTypeDependent()) { 1218 QualType LHSType = TheCall->getArg(0)->getType(); 1219 QualType RHSType = TheCall->getArg(1)->getType(); 1220 1221 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1222 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1223 << SourceRange(TheCall->getArg(0)->getLocStart(), 1224 TheCall->getArg(1)->getLocEnd()); 1225 return ExprError(); 1226 } 1227 1228 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1229 unsigned numResElements = TheCall->getNumArgs() - 2; 1230 1231 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1232 // with mask. If so, verify that RHS is an integer vector type with the 1233 // same number of elts as lhs. 1234 if (TheCall->getNumArgs() == 2) { 1235 if (!RHSType->hasIntegerRepresentation() || 1236 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1237 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1238 << SourceRange(TheCall->getArg(1)->getLocStart(), 1239 TheCall->getArg(1)->getLocEnd()); 1240 numResElements = numElements; 1241 } 1242 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1243 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1244 << SourceRange(TheCall->getArg(0)->getLocStart(), 1245 TheCall->getArg(1)->getLocEnd()); 1246 return ExprError(); 1247 } else if (numElements != numResElements) { 1248 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1249 resType = Context.getVectorType(eltType, numResElements, 1250 VectorType::GenericVector); 1251 } 1252 } 1253 1254 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1255 if (TheCall->getArg(i)->isTypeDependent() || 1256 TheCall->getArg(i)->isValueDependent()) 1257 continue; 1258 1259 llvm::APSInt Result(32); 1260 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1261 return ExprError(Diag(TheCall->getLocStart(), 1262 diag::err_shufflevector_nonconstant_argument) 1263 << TheCall->getArg(i)->getSourceRange()); 1264 1265 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1266 return ExprError(Diag(TheCall->getLocStart(), 1267 diag::err_shufflevector_argument_too_large) 1268 << TheCall->getArg(i)->getSourceRange()); 1269 } 1270 1271 SmallVector<Expr*, 32> exprs; 1272 1273 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1274 exprs.push_back(TheCall->getArg(i)); 1275 TheCall->setArg(i, 0); 1276 } 1277 1278 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 1279 exprs.size(), resType, 1280 TheCall->getCallee()->getLocStart(), 1281 TheCall->getRParenLoc())); 1282} 1283 1284/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1285// This is declared to take (const void*, ...) and can take two 1286// optional constant int args. 1287bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1288 unsigned NumArgs = TheCall->getNumArgs(); 1289 1290 if (NumArgs > 3) 1291 return Diag(TheCall->getLocEnd(), 1292 diag::err_typecheck_call_too_many_args_at_most) 1293 << 0 /*function call*/ << 3 << NumArgs 1294 << TheCall->getSourceRange(); 1295 1296 // Argument 0 is checked for us and the remaining arguments must be 1297 // constant integers. 1298 for (unsigned i = 1; i != NumArgs; ++i) { 1299 Expr *Arg = TheCall->getArg(i); 1300 1301 llvm::APSInt Result; 1302 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1303 return true; 1304 1305 // FIXME: gcc issues a warning and rewrites these to 0. These 1306 // seems especially odd for the third argument since the default 1307 // is 3. 1308 if (i == 1) { 1309 if (Result.getLimitedValue() > 1) 1310 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1311 << "0" << "1" << Arg->getSourceRange(); 1312 } else { 1313 if (Result.getLimitedValue() > 3) 1314 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1315 << "0" << "3" << Arg->getSourceRange(); 1316 } 1317 } 1318 1319 return false; 1320} 1321 1322/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1323/// TheCall is a constant expression. 1324bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1325 llvm::APSInt &Result) { 1326 Expr *Arg = TheCall->getArg(ArgNum); 1327 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1328 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1329 1330 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1331 1332 if (!Arg->isIntegerConstantExpr(Result, Context)) 1333 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1334 << FDecl->getDeclName() << Arg->getSourceRange(); 1335 1336 return false; 1337} 1338 1339/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1340/// int type). This simply type checks that type is one of the defined 1341/// constants (0-3). 1342// For compatibility check 0-3, llvm only handles 0 and 2. 1343bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1344 llvm::APSInt Result; 1345 1346 // Check constant-ness first. 1347 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1348 return true; 1349 1350 Expr *Arg = TheCall->getArg(1); 1351 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1352 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1353 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1354 } 1355 1356 return false; 1357} 1358 1359/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1360/// This checks that val is a constant 1. 1361bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1362 Expr *Arg = TheCall->getArg(1); 1363 llvm::APSInt Result; 1364 1365 // TODO: This is less than ideal. Overload this to take a value. 1366 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1367 return true; 1368 1369 if (Result != 1) 1370 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1371 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1372 1373 return false; 1374} 1375 1376// Handle i > 1 ? "x" : "y", recursively. 1377bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args, 1378 unsigned NumArgs, bool HasVAListArg, 1379 unsigned format_idx, unsigned firstDataArg, 1380 bool isPrintf, bool inFunctionCall) { 1381 tryAgain: 1382 if (E->isTypeDependent() || E->isValueDependent()) 1383 return false; 1384 1385 E = E->IgnoreParens(); 1386 1387 switch (E->getStmtClass()) { 1388 case Stmt::BinaryConditionalOperatorClass: 1389 case Stmt::ConditionalOperatorClass: { 1390 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1391 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg, 1392 format_idx, firstDataArg, isPrintf, 1393 inFunctionCall) 1394 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg, 1395 format_idx, firstDataArg, isPrintf, 1396 inFunctionCall); 1397 } 1398 1399 case Stmt::IntegerLiteralClass: 1400 // Technically -Wformat-nonliteral does not warn about this case. 1401 // The behavior of printf and friends in this case is implementation 1402 // dependent. Ideally if the format string cannot be null then 1403 // it should have a 'nonnull' attribute in the function prototype. 1404 return true; 1405 1406 case Stmt::ImplicitCastExprClass: { 1407 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1408 goto tryAgain; 1409 } 1410 1411 case Stmt::OpaqueValueExprClass: 1412 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1413 E = src; 1414 goto tryAgain; 1415 } 1416 return false; 1417 1418 case Stmt::PredefinedExprClass: 1419 // While __func__, etc., are technically not string literals, they 1420 // cannot contain format specifiers and thus are not a security 1421 // liability. 1422 return true; 1423 1424 case Stmt::DeclRefExprClass: { 1425 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1426 1427 // As an exception, do not flag errors for variables binding to 1428 // const string literals. 1429 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1430 bool isConstant = false; 1431 QualType T = DR->getType(); 1432 1433 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1434 isConstant = AT->getElementType().isConstant(Context); 1435 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1436 isConstant = T.isConstant(Context) && 1437 PT->getPointeeType().isConstant(Context); 1438 } 1439 1440 if (isConstant) { 1441 if (const Expr *Init = VD->getAnyInitializer()) 1442 return SemaCheckStringLiteral(Init, Args, NumArgs, 1443 HasVAListArg, format_idx, firstDataArg, 1444 isPrintf, /*inFunctionCall*/false); 1445 } 1446 1447 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1448 // special check to see if the format string is a function parameter 1449 // of the function calling the printf function. If the function 1450 // has an attribute indicating it is a printf-like function, then we 1451 // should suppress warnings concerning non-literals being used in a call 1452 // to a vprintf function. For example: 1453 // 1454 // void 1455 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1456 // va_list ap; 1457 // va_start(ap, fmt); 1458 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1459 // ... 1460 // 1461 // 1462 // FIXME: We don't have full attribute support yet, so just check to see 1463 // if the argument is a DeclRefExpr that references a parameter. We'll 1464 // add proper support for checking the attribute later. 1465 if (HasVAListArg) 1466 if (isa<ParmVarDecl>(VD)) 1467 return true; 1468 } 1469 1470 return false; 1471 } 1472 1473 case Stmt::CallExprClass: { 1474 const CallExpr *CE = cast<CallExpr>(E); 1475 if (const ImplicitCastExpr *ICE 1476 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 1477 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1478 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1479 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 1480 unsigned ArgIndex = FA->getFormatIdx(); 1481 const Expr *Arg = CE->getArg(ArgIndex - 1); 1482 1483 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg, 1484 format_idx, firstDataArg, isPrintf, 1485 inFunctionCall); 1486 } 1487 } 1488 } 1489 } 1490 1491 return false; 1492 } 1493 case Stmt::ObjCStringLiteralClass: 1494 case Stmt::StringLiteralClass: { 1495 const StringLiteral *StrE = NULL; 1496 1497 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1498 StrE = ObjCFExpr->getString(); 1499 else 1500 StrE = cast<StringLiteral>(E); 1501 1502 if (StrE) { 1503 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1504 firstDataArg, isPrintf, inFunctionCall); 1505 return true; 1506 } 1507 1508 return false; 1509 } 1510 1511 default: 1512 return false; 1513 } 1514} 1515 1516void 1517Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1518 const Expr * const *ExprArgs, 1519 SourceLocation CallSiteLoc) { 1520 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1521 e = NonNull->args_end(); 1522 i != e; ++i) { 1523 const Expr *ArgExpr = ExprArgs[*i]; 1524 if (ArgExpr->isNullPointerConstant(Context, 1525 Expr::NPC_ValueDependentIsNotNull)) 1526 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1527 } 1528} 1529 1530/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1531/// functions) for correct use of format strings. 1532void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) { 1533 bool IsCXXMember = false; 1534 // The way the format attribute works in GCC, the implicit this argument 1535 // of member functions is counted. However, it doesn't appear in our own 1536 // lists, so decrement format_idx in that case. 1537 if (isa<CXXMemberCallExpr>(TheCall)) { 1538 const CXXMethodDecl *method_decl = 1539 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1540 IsCXXMember = method_decl && method_decl->isInstance(); 1541 } 1542 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(), 1543 IsCXXMember, TheCall->getRParenLoc(), 1544 TheCall->getCallee()->getSourceRange()); 1545} 1546 1547void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1548 unsigned NumArgs, bool IsCXXMember, 1549 SourceLocation Loc, SourceRange Range) { 1550 const bool b = Format->getType() == "scanf"; 1551 if (b || CheckablePrintfAttr(Format, Args, NumArgs, IsCXXMember)) { 1552 bool HasVAListArg = Format->getFirstArg() == 0; 1553 unsigned format_idx = Format->getFormatIdx() - 1; 1554 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1; 1555 if (IsCXXMember) { 1556 if (format_idx == 0) 1557 return; 1558 --format_idx; 1559 if(firstDataArg != 0) 1560 --firstDataArg; 1561 } 1562 CheckPrintfScanfArguments(Args, NumArgs, HasVAListArg, format_idx, 1563 firstDataArg, !b, Loc, Range); 1564 } 1565} 1566 1567void Sema::CheckPrintfScanfArguments(Expr **Args, unsigned NumArgs, 1568 bool HasVAListArg, unsigned format_idx, 1569 unsigned firstDataArg, bool isPrintf, 1570 SourceLocation Loc, SourceRange Range) { 1571 // CHECK: printf/scanf-like function is called with no format string. 1572 if (format_idx >= NumArgs) { 1573 Diag(Loc, diag::warn_missing_format_string) << Range; 1574 return; 1575 } 1576 1577 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1578 1579 // CHECK: format string is not a string literal. 1580 // 1581 // Dynamically generated format strings are difficult to 1582 // automatically vet at compile time. Requiring that format strings 1583 // are string literals: (1) permits the checking of format strings by 1584 // the compiler and thereby (2) can practically remove the source of 1585 // many format string exploits. 1586 1587 // Format string can be either ObjC string (e.g. @"%d") or 1588 // C string (e.g. "%d") 1589 // ObjC string uses the same format specifiers as C string, so we can use 1590 // the same format string checking logic for both ObjC and C strings. 1591 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1592 format_idx, firstDataArg, isPrintf)) 1593 return; // Literal format string found, check done! 1594 1595 // If there are no arguments specified, warn with -Wformat-security, otherwise 1596 // warn only with -Wformat-nonliteral. 1597 if (NumArgs == format_idx+1) 1598 Diag(Args[format_idx]->getLocStart(), 1599 diag::warn_format_nonliteral_noargs) 1600 << OrigFormatExpr->getSourceRange(); 1601 else 1602 Diag(Args[format_idx]->getLocStart(), 1603 diag::warn_format_nonliteral) 1604 << OrigFormatExpr->getSourceRange(); 1605} 1606 1607namespace { 1608class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1609protected: 1610 Sema &S; 1611 const StringLiteral *FExpr; 1612 const Expr *OrigFormatExpr; 1613 const unsigned FirstDataArg; 1614 const unsigned NumDataArgs; 1615 const bool IsObjCLiteral; 1616 const char *Beg; // Start of format string. 1617 const bool HasVAListArg; 1618 const Expr * const *Args; 1619 const unsigned NumArgs; 1620 unsigned FormatIdx; 1621 llvm::BitVector CoveredArgs; 1622 bool usesPositionalArgs; 1623 bool atFirstArg; 1624 bool inFunctionCall; 1625public: 1626 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1627 const Expr *origFormatExpr, unsigned firstDataArg, 1628 unsigned numDataArgs, bool isObjCLiteral, 1629 const char *beg, bool hasVAListArg, 1630 Expr **args, unsigned numArgs, 1631 unsigned formatIdx, bool inFunctionCall) 1632 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1633 FirstDataArg(firstDataArg), 1634 NumDataArgs(numDataArgs), 1635 IsObjCLiteral(isObjCLiteral), Beg(beg), 1636 HasVAListArg(hasVAListArg), 1637 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1638 usesPositionalArgs(false), atFirstArg(true), 1639 inFunctionCall(inFunctionCall) { 1640 CoveredArgs.resize(numDataArgs); 1641 CoveredArgs.reset(); 1642 } 1643 1644 void DoneProcessing(); 1645 1646 void HandleIncompleteSpecifier(const char *startSpecifier, 1647 unsigned specifierLen); 1648 1649 virtual void HandleInvalidPosition(const char *startSpecifier, 1650 unsigned specifierLen, 1651 analyze_format_string::PositionContext p); 1652 1653 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1654 1655 void HandleNullChar(const char *nullCharacter); 1656 1657 template <typename Range> 1658 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1659 const Expr *ArgumentExpr, 1660 PartialDiagnostic PDiag, 1661 SourceLocation StringLoc, 1662 bool IsStringLocation, Range StringRange, 1663 FixItHint Fixit = FixItHint()); 1664 1665protected: 1666 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1667 const char *startSpec, 1668 unsigned specifierLen, 1669 const char *csStart, unsigned csLen); 1670 1671 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1672 const char *startSpec, 1673 unsigned specifierLen); 1674 1675 SourceRange getFormatStringRange(); 1676 CharSourceRange getSpecifierRange(const char *startSpecifier, 1677 unsigned specifierLen); 1678 SourceLocation getLocationOfByte(const char *x); 1679 1680 const Expr *getDataArg(unsigned i) const; 1681 1682 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1683 const analyze_format_string::ConversionSpecifier &CS, 1684 const char *startSpecifier, unsigned specifierLen, 1685 unsigned argIndex); 1686 1687 template <typename Range> 1688 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1689 bool IsStringLocation, Range StringRange, 1690 FixItHint Fixit = FixItHint()); 1691 1692 void CheckPositionalAndNonpositionalArgs( 1693 const analyze_format_string::FormatSpecifier *FS); 1694}; 1695} 1696 1697SourceRange CheckFormatHandler::getFormatStringRange() { 1698 return OrigFormatExpr->getSourceRange(); 1699} 1700 1701CharSourceRange CheckFormatHandler:: 1702getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1703 SourceLocation Start = getLocationOfByte(startSpecifier); 1704 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1705 1706 // Advance the end SourceLocation by one due to half-open ranges. 1707 End = End.getLocWithOffset(1); 1708 1709 return CharSourceRange::getCharRange(Start, End); 1710} 1711 1712SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1713 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1714} 1715 1716void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1717 unsigned specifierLen){ 1718 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1719 getLocationOfByte(startSpecifier), 1720 /*IsStringLocation*/true, 1721 getSpecifierRange(startSpecifier, specifierLen)); 1722} 1723 1724void 1725CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1726 analyze_format_string::PositionContext p) { 1727 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1728 << (unsigned) p, 1729 getLocationOfByte(startPos), /*IsStringLocation*/true, 1730 getSpecifierRange(startPos, posLen)); 1731} 1732 1733void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1734 unsigned posLen) { 1735 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1736 getLocationOfByte(startPos), 1737 /*IsStringLocation*/true, 1738 getSpecifierRange(startPos, posLen)); 1739} 1740 1741void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1742 if (!IsObjCLiteral) { 1743 // The presence of a null character is likely an error. 1744 EmitFormatDiagnostic( 1745 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1746 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1747 getFormatStringRange()); 1748 } 1749} 1750 1751const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1752 return Args[FirstDataArg + i]; 1753} 1754 1755void CheckFormatHandler::DoneProcessing() { 1756 // Does the number of data arguments exceed the number of 1757 // format conversions in the format string? 1758 if (!HasVAListArg) { 1759 // Find any arguments that weren't covered. 1760 CoveredArgs.flip(); 1761 signed notCoveredArg = CoveredArgs.find_first(); 1762 if (notCoveredArg >= 0) { 1763 assert((unsigned)notCoveredArg < NumDataArgs); 1764 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1765 getDataArg((unsigned) notCoveredArg)->getLocStart(), 1766 /*IsStringLocation*/false, getFormatStringRange()); 1767 } 1768 } 1769} 1770 1771bool 1772CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1773 SourceLocation Loc, 1774 const char *startSpec, 1775 unsigned specifierLen, 1776 const char *csStart, 1777 unsigned csLen) { 1778 1779 bool keepGoing = true; 1780 if (argIndex < NumDataArgs) { 1781 // Consider the argument coverered, even though the specifier doesn't 1782 // make sense. 1783 CoveredArgs.set(argIndex); 1784 } 1785 else { 1786 // If argIndex exceeds the number of data arguments we 1787 // don't issue a warning because that is just a cascade of warnings (and 1788 // they may have intended '%%' anyway). We don't want to continue processing 1789 // the format string after this point, however, as we will like just get 1790 // gibberish when trying to match arguments. 1791 keepGoing = false; 1792 } 1793 1794 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 1795 << StringRef(csStart, csLen), 1796 Loc, /*IsStringLocation*/true, 1797 getSpecifierRange(startSpec, specifierLen)); 1798 1799 return keepGoing; 1800} 1801 1802void 1803CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 1804 const char *startSpec, 1805 unsigned specifierLen) { 1806 EmitFormatDiagnostic( 1807 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 1808 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 1809} 1810 1811bool 1812CheckFormatHandler::CheckNumArgs( 1813 const analyze_format_string::FormatSpecifier &FS, 1814 const analyze_format_string::ConversionSpecifier &CS, 1815 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1816 1817 if (argIndex >= NumDataArgs) { 1818 PartialDiagnostic PDiag = FS.usesPositionalArg() 1819 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 1820 << (argIndex+1) << NumDataArgs) 1821 : S.PDiag(diag::warn_printf_insufficient_data_args); 1822 EmitFormatDiagnostic( 1823 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 1824 getSpecifierRange(startSpecifier, specifierLen)); 1825 return false; 1826 } 1827 return true; 1828} 1829 1830template<typename Range> 1831void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 1832 SourceLocation Loc, 1833 bool IsStringLocation, 1834 Range StringRange, 1835 FixItHint FixIt) { 1836 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 1837 Loc, IsStringLocation, StringRange, FixIt); 1838} 1839 1840/// \brief If the format string is not within the funcion call, emit a note 1841/// so that the function call and string are in diagnostic messages. 1842/// 1843/// \param inFunctionCall if true, the format string is within the function 1844/// call and only one diagnostic message will be produced. Otherwise, an 1845/// extra note will be emitted pointing to location of the format string. 1846/// 1847/// \param ArgumentExpr the expression that is passed as the format string 1848/// argument in the function call. Used for getting locations when two 1849/// diagnostics are emitted. 1850/// 1851/// \param PDiag the callee should already have provided any strings for the 1852/// diagnostic message. This function only adds locations and fixits 1853/// to diagnostics. 1854/// 1855/// \param Loc primary location for diagnostic. If two diagnostics are 1856/// required, one will be at Loc and a new SourceLocation will be created for 1857/// the other one. 1858/// 1859/// \param IsStringLocation if true, Loc points to the format string should be 1860/// used for the note. Otherwise, Loc points to the argument list and will 1861/// be used with PDiag. 1862/// 1863/// \param StringRange some or all of the string to highlight. This is 1864/// templated so it can accept either a CharSourceRange or a SourceRange. 1865/// 1866/// \param Fixit optional fix it hint for the format string. 1867template<typename Range> 1868void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 1869 const Expr *ArgumentExpr, 1870 PartialDiagnostic PDiag, 1871 SourceLocation Loc, 1872 bool IsStringLocation, 1873 Range StringRange, 1874 FixItHint FixIt) { 1875 if (InFunctionCall) 1876 S.Diag(Loc, PDiag) << StringRange << FixIt; 1877 else { 1878 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 1879 << ArgumentExpr->getSourceRange(); 1880 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 1881 diag::note_format_string_defined) 1882 << StringRange << FixIt; 1883 } 1884} 1885 1886//===--- CHECK: Printf format string checking ------------------------------===// 1887 1888namespace { 1889class CheckPrintfHandler : public CheckFormatHandler { 1890public: 1891 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1892 const Expr *origFormatExpr, unsigned firstDataArg, 1893 unsigned numDataArgs, bool isObjCLiteral, 1894 const char *beg, bool hasVAListArg, 1895 Expr **Args, unsigned NumArgs, 1896 unsigned formatIdx, bool inFunctionCall) 1897 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1898 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1899 Args, NumArgs, formatIdx, inFunctionCall) {} 1900 1901 1902 bool HandleInvalidPrintfConversionSpecifier( 1903 const analyze_printf::PrintfSpecifier &FS, 1904 const char *startSpecifier, 1905 unsigned specifierLen); 1906 1907 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1908 const char *startSpecifier, 1909 unsigned specifierLen); 1910 1911 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1912 const char *startSpecifier, unsigned specifierLen); 1913 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1914 const analyze_printf::OptionalAmount &Amt, 1915 unsigned type, 1916 const char *startSpecifier, unsigned specifierLen); 1917 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1918 const analyze_printf::OptionalFlag &flag, 1919 const char *startSpecifier, unsigned specifierLen); 1920 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1921 const analyze_printf::OptionalFlag &ignoredFlag, 1922 const analyze_printf::OptionalFlag &flag, 1923 const char *startSpecifier, unsigned specifierLen); 1924}; 1925} 1926 1927bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1928 const analyze_printf::PrintfSpecifier &FS, 1929 const char *startSpecifier, 1930 unsigned specifierLen) { 1931 const analyze_printf::PrintfConversionSpecifier &CS = 1932 FS.getConversionSpecifier(); 1933 1934 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1935 getLocationOfByte(CS.getStart()), 1936 startSpecifier, specifierLen, 1937 CS.getStart(), CS.getLength()); 1938} 1939 1940bool CheckPrintfHandler::HandleAmount( 1941 const analyze_format_string::OptionalAmount &Amt, 1942 unsigned k, const char *startSpecifier, 1943 unsigned specifierLen) { 1944 1945 if (Amt.hasDataArgument()) { 1946 if (!HasVAListArg) { 1947 unsigned argIndex = Amt.getArgIndex(); 1948 if (argIndex >= NumDataArgs) { 1949 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 1950 << k, 1951 getLocationOfByte(Amt.getStart()), 1952 /*IsStringLocation*/true, 1953 getSpecifierRange(startSpecifier, specifierLen)); 1954 // Don't do any more checking. We will just emit 1955 // spurious errors. 1956 return false; 1957 } 1958 1959 // Type check the data argument. It should be an 'int'. 1960 // Although not in conformance with C99, we also allow the argument to be 1961 // an 'unsigned int' as that is a reasonably safe case. GCC also 1962 // doesn't emit a warning for that case. 1963 CoveredArgs.set(argIndex); 1964 const Expr *Arg = getDataArg(argIndex); 1965 QualType T = Arg->getType(); 1966 1967 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1968 assert(ATR.isValid()); 1969 1970 if (!ATR.matchesType(S.Context, T)) { 1971 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 1972 << k << ATR.getRepresentativeTypeName(S.Context) 1973 << T << Arg->getSourceRange(), 1974 getLocationOfByte(Amt.getStart()), 1975 /*IsStringLocation*/true, 1976 getSpecifierRange(startSpecifier, specifierLen)); 1977 // Don't do any more checking. We will just emit 1978 // spurious errors. 1979 return false; 1980 } 1981 } 1982 } 1983 return true; 1984} 1985 1986void CheckPrintfHandler::HandleInvalidAmount( 1987 const analyze_printf::PrintfSpecifier &FS, 1988 const analyze_printf::OptionalAmount &Amt, 1989 unsigned type, 1990 const char *startSpecifier, 1991 unsigned specifierLen) { 1992 const analyze_printf::PrintfConversionSpecifier &CS = 1993 FS.getConversionSpecifier(); 1994 1995 FixItHint fixit = 1996 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 1997 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 1998 Amt.getConstantLength())) 1999 : FixItHint(); 2000 2001 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2002 << type << CS.toString(), 2003 getLocationOfByte(Amt.getStart()), 2004 /*IsStringLocation*/true, 2005 getSpecifierRange(startSpecifier, specifierLen), 2006 fixit); 2007} 2008 2009void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2010 const analyze_printf::OptionalFlag &flag, 2011 const char *startSpecifier, 2012 unsigned specifierLen) { 2013 // Warn about pointless flag with a fixit removal. 2014 const analyze_printf::PrintfConversionSpecifier &CS = 2015 FS.getConversionSpecifier(); 2016 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2017 << flag.toString() << CS.toString(), 2018 getLocationOfByte(flag.getPosition()), 2019 /*IsStringLocation*/true, 2020 getSpecifierRange(startSpecifier, specifierLen), 2021 FixItHint::CreateRemoval( 2022 getSpecifierRange(flag.getPosition(), 1))); 2023} 2024 2025void CheckPrintfHandler::HandleIgnoredFlag( 2026 const analyze_printf::PrintfSpecifier &FS, 2027 const analyze_printf::OptionalFlag &ignoredFlag, 2028 const analyze_printf::OptionalFlag &flag, 2029 const char *startSpecifier, 2030 unsigned specifierLen) { 2031 // Warn about ignored flag with a fixit removal. 2032 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2033 << ignoredFlag.toString() << flag.toString(), 2034 getLocationOfByte(ignoredFlag.getPosition()), 2035 /*IsStringLocation*/true, 2036 getSpecifierRange(startSpecifier, specifierLen), 2037 FixItHint::CreateRemoval( 2038 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2039} 2040 2041bool 2042CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2043 &FS, 2044 const char *startSpecifier, 2045 unsigned specifierLen) { 2046 2047 using namespace analyze_format_string; 2048 using namespace analyze_printf; 2049 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2050 2051 if (FS.consumesDataArgument()) { 2052 if (atFirstArg) { 2053 atFirstArg = false; 2054 usesPositionalArgs = FS.usesPositionalArg(); 2055 } 2056 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2057 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2058 startSpecifier, specifierLen); 2059 return false; 2060 } 2061 } 2062 2063 // First check if the field width, precision, and conversion specifier 2064 // have matching data arguments. 2065 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2066 startSpecifier, specifierLen)) { 2067 return false; 2068 } 2069 2070 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2071 startSpecifier, specifierLen)) { 2072 return false; 2073 } 2074 2075 if (!CS.consumesDataArgument()) { 2076 // FIXME: Technically specifying a precision or field width here 2077 // makes no sense. Worth issuing a warning at some point. 2078 return true; 2079 } 2080 2081 // Consume the argument. 2082 unsigned argIndex = FS.getArgIndex(); 2083 if (argIndex < NumDataArgs) { 2084 // The check to see if the argIndex is valid will come later. 2085 // We set the bit here because we may exit early from this 2086 // function if we encounter some other error. 2087 CoveredArgs.set(argIndex); 2088 } 2089 2090 // Check for using an Objective-C specific conversion specifier 2091 // in a non-ObjC literal. 2092 if (!IsObjCLiteral && CS.isObjCArg()) { 2093 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2094 specifierLen); 2095 } 2096 2097 // Check for invalid use of field width 2098 if (!FS.hasValidFieldWidth()) { 2099 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2100 startSpecifier, specifierLen); 2101 } 2102 2103 // Check for invalid use of precision 2104 if (!FS.hasValidPrecision()) { 2105 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2106 startSpecifier, specifierLen); 2107 } 2108 2109 // Check each flag does not conflict with any other component. 2110 if (!FS.hasValidThousandsGroupingPrefix()) 2111 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2112 if (!FS.hasValidLeadingZeros()) 2113 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2114 if (!FS.hasValidPlusPrefix()) 2115 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2116 if (!FS.hasValidSpacePrefix()) 2117 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2118 if (!FS.hasValidAlternativeForm()) 2119 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2120 if (!FS.hasValidLeftJustified()) 2121 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2122 2123 // Check that flags are not ignored by another flag 2124 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2125 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2126 startSpecifier, specifierLen); 2127 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2128 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2129 startSpecifier, specifierLen); 2130 2131 // Check the length modifier is valid with the given conversion specifier. 2132 const LengthModifier &LM = FS.getLengthModifier(); 2133 if (!FS.hasValidLengthModifier()) 2134 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2135 << LM.toString() << CS.toString(), 2136 getLocationOfByte(LM.getStart()), 2137 /*IsStringLocation*/true, 2138 getSpecifierRange(startSpecifier, specifierLen), 2139 FixItHint::CreateRemoval( 2140 getSpecifierRange(LM.getStart(), 2141 LM.getLength()))); 2142 2143 // Are we using '%n'? 2144 if (CS.getKind() == ConversionSpecifier::nArg) { 2145 // Issue a warning about this being a possible security issue. 2146 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2147 getLocationOfByte(CS.getStart()), 2148 /*IsStringLocation*/true, 2149 getSpecifierRange(startSpecifier, specifierLen)); 2150 // Continue checking the other format specifiers. 2151 return true; 2152 } 2153 2154 // The remaining checks depend on the data arguments. 2155 if (HasVAListArg) 2156 return true; 2157 2158 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2159 return false; 2160 2161 // Now type check the data expression that matches the 2162 // format specifier. 2163 const Expr *Ex = getDataArg(argIndex); 2164 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 2165 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2166 // Check if we didn't match because of an implicit cast from a 'char' 2167 // or 'short' to an 'int'. This is done because printf is a varargs 2168 // function. 2169 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 2170 if (ICE->getType() == S.Context.IntTy) { 2171 // All further checking is done on the subexpression. 2172 Ex = ICE->getSubExpr(); 2173 if (ATR.matchesType(S.Context, Ex->getType())) 2174 return true; 2175 } 2176 2177 // We may be able to offer a FixItHint if it is a supported type. 2178 PrintfSpecifier fixedFS = FS; 2179 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions()); 2180 2181 if (success) { 2182 // Get the fix string from the fixed format specifier 2183 llvm::SmallString<128> buf; 2184 llvm::raw_svector_ostream os(buf); 2185 fixedFS.toString(os); 2186 2187 EmitFormatDiagnostic( 2188 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2189 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2190 << Ex->getSourceRange(), 2191 getLocationOfByte(CS.getStart()), 2192 /*IsStringLocation*/true, 2193 getSpecifierRange(startSpecifier, specifierLen), 2194 FixItHint::CreateReplacement( 2195 getSpecifierRange(startSpecifier, specifierLen), 2196 os.str())); 2197 } 2198 else { 2199 S.Diag(getLocationOfByte(CS.getStart()), 2200 diag::warn_printf_conversion_argument_type_mismatch) 2201 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2202 << getSpecifierRange(startSpecifier, specifierLen) 2203 << Ex->getSourceRange(); 2204 } 2205 } 2206 2207 return true; 2208} 2209 2210//===--- CHECK: Scanf format string checking ------------------------------===// 2211 2212namespace { 2213class CheckScanfHandler : public CheckFormatHandler { 2214public: 2215 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2216 const Expr *origFormatExpr, unsigned firstDataArg, 2217 unsigned numDataArgs, bool isObjCLiteral, 2218 const char *beg, bool hasVAListArg, 2219 Expr **Args, unsigned NumArgs, 2220 unsigned formatIdx, bool inFunctionCall) 2221 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2222 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2223 Args, NumArgs, formatIdx, inFunctionCall) {} 2224 2225 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2226 const char *startSpecifier, 2227 unsigned specifierLen); 2228 2229 bool HandleInvalidScanfConversionSpecifier( 2230 const analyze_scanf::ScanfSpecifier &FS, 2231 const char *startSpecifier, 2232 unsigned specifierLen); 2233 2234 void HandleIncompleteScanList(const char *start, const char *end); 2235}; 2236} 2237 2238void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2239 const char *end) { 2240 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2241 getLocationOfByte(end), /*IsStringLocation*/true, 2242 getSpecifierRange(start, end - start)); 2243} 2244 2245bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2246 const analyze_scanf::ScanfSpecifier &FS, 2247 const char *startSpecifier, 2248 unsigned specifierLen) { 2249 2250 const analyze_scanf::ScanfConversionSpecifier &CS = 2251 FS.getConversionSpecifier(); 2252 2253 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2254 getLocationOfByte(CS.getStart()), 2255 startSpecifier, specifierLen, 2256 CS.getStart(), CS.getLength()); 2257} 2258 2259bool CheckScanfHandler::HandleScanfSpecifier( 2260 const analyze_scanf::ScanfSpecifier &FS, 2261 const char *startSpecifier, 2262 unsigned specifierLen) { 2263 2264 using namespace analyze_scanf; 2265 using namespace analyze_format_string; 2266 2267 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2268 2269 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2270 // be used to decide if we are using positional arguments consistently. 2271 if (FS.consumesDataArgument()) { 2272 if (atFirstArg) { 2273 atFirstArg = false; 2274 usesPositionalArgs = FS.usesPositionalArg(); 2275 } 2276 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2277 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2278 startSpecifier, specifierLen); 2279 return false; 2280 } 2281 } 2282 2283 // Check if the field with is non-zero. 2284 const OptionalAmount &Amt = FS.getFieldWidth(); 2285 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2286 if (Amt.getConstantAmount() == 0) { 2287 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2288 Amt.getConstantLength()); 2289 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2290 getLocationOfByte(Amt.getStart()), 2291 /*IsStringLocation*/true, R, 2292 FixItHint::CreateRemoval(R)); 2293 } 2294 } 2295 2296 if (!FS.consumesDataArgument()) { 2297 // FIXME: Technically specifying a precision or field width here 2298 // makes no sense. Worth issuing a warning at some point. 2299 return true; 2300 } 2301 2302 // Consume the argument. 2303 unsigned argIndex = FS.getArgIndex(); 2304 if (argIndex < NumDataArgs) { 2305 // The check to see if the argIndex is valid will come later. 2306 // We set the bit here because we may exit early from this 2307 // function if we encounter some other error. 2308 CoveredArgs.set(argIndex); 2309 } 2310 2311 // Check the length modifier is valid with the given conversion specifier. 2312 const LengthModifier &LM = FS.getLengthModifier(); 2313 if (!FS.hasValidLengthModifier()) { 2314 S.Diag(getLocationOfByte(LM.getStart()), 2315 diag::warn_format_nonsensical_length) 2316 << LM.toString() << CS.toString() 2317 << getSpecifierRange(startSpecifier, specifierLen) 2318 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 2319 LM.getLength())); 2320 } 2321 2322 // The remaining checks depend on the data arguments. 2323 if (HasVAListArg) 2324 return true; 2325 2326 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2327 return false; 2328 2329 // Check that the argument type matches the format specifier. 2330 const Expr *Ex = getDataArg(argIndex); 2331 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context); 2332 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2333 ScanfSpecifier fixedFS = FS; 2334 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions()); 2335 2336 if (success) { 2337 // Get the fix string from the fixed format specifier. 2338 llvm::SmallString<128> buf; 2339 llvm::raw_svector_ostream os(buf); 2340 fixedFS.toString(os); 2341 2342 EmitFormatDiagnostic( 2343 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2344 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2345 << Ex->getSourceRange(), 2346 getLocationOfByte(CS.getStart()), 2347 /*IsStringLocation*/true, 2348 getSpecifierRange(startSpecifier, specifierLen), 2349 FixItHint::CreateReplacement( 2350 getSpecifierRange(startSpecifier, specifierLen), 2351 os.str())); 2352 } else { 2353 S.Diag(getLocationOfByte(CS.getStart()), 2354 diag::warn_printf_conversion_argument_type_mismatch) 2355 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2356 << getSpecifierRange(startSpecifier, specifierLen) 2357 << Ex->getSourceRange(); 2358 } 2359 } 2360 2361 return true; 2362} 2363 2364void Sema::CheckFormatString(const StringLiteral *FExpr, 2365 const Expr *OrigFormatExpr, 2366 Expr **Args, unsigned NumArgs, 2367 bool HasVAListArg, unsigned format_idx, 2368 unsigned firstDataArg, bool isPrintf, 2369 bool inFunctionCall) { 2370 2371 // CHECK: is the format string a wide literal? 2372 if (!FExpr->isAscii()) { 2373 CheckFormatHandler::EmitFormatDiagnostic( 2374 *this, inFunctionCall, Args[format_idx], 2375 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2376 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2377 return; 2378 } 2379 2380 // Str - The format string. NOTE: this is NOT null-terminated! 2381 StringRef StrRef = FExpr->getString(); 2382 const char *Str = StrRef.data(); 2383 unsigned StrLen = StrRef.size(); 2384 const unsigned numDataArgs = NumArgs - firstDataArg; 2385 2386 // CHECK: empty format string? 2387 if (StrLen == 0 && numDataArgs > 0) { 2388 CheckFormatHandler::EmitFormatDiagnostic( 2389 *this, inFunctionCall, Args[format_idx], 2390 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2391 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2392 return; 2393 } 2394 2395 if (isPrintf) { 2396 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2397 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2398 Str, HasVAListArg, Args, NumArgs, format_idx, 2399 inFunctionCall); 2400 2401 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2402 getLangOptions())) 2403 H.DoneProcessing(); 2404 } 2405 else { 2406 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2407 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2408 Str, HasVAListArg, Args, NumArgs, format_idx, 2409 inFunctionCall); 2410 2411 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2412 getLangOptions())) 2413 H.DoneProcessing(); 2414 } 2415} 2416 2417//===--- CHECK: Standard memory functions ---------------------------------===// 2418 2419/// \brief Determine whether the given type is a dynamic class type (e.g., 2420/// whether it has a vtable). 2421static bool isDynamicClassType(QualType T) { 2422 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2423 if (CXXRecordDecl *Definition = Record->getDefinition()) 2424 if (Definition->isDynamicClass()) 2425 return true; 2426 2427 return false; 2428} 2429 2430/// \brief If E is a sizeof expression, returns its argument expression, 2431/// otherwise returns NULL. 2432static const Expr *getSizeOfExprArg(const Expr* E) { 2433 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2434 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2435 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2436 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2437 2438 return 0; 2439} 2440 2441/// \brief If E is a sizeof expression, returns its argument type. 2442static QualType getSizeOfArgType(const Expr* E) { 2443 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2444 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2445 if (SizeOf->getKind() == clang::UETT_SizeOf) 2446 return SizeOf->getTypeOfArgument(); 2447 2448 return QualType(); 2449} 2450 2451/// \brief Check for dangerous or invalid arguments to memset(). 2452/// 2453/// This issues warnings on known problematic, dangerous or unspecified 2454/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2455/// function calls. 2456/// 2457/// \param Call The call expression to diagnose. 2458void Sema::CheckMemaccessArguments(const CallExpr *Call, 2459 unsigned BId, 2460 IdentifierInfo *FnName) { 2461 assert(BId != 0); 2462 2463 // It is possible to have a non-standard definition of memset. Validate 2464 // we have enough arguments, and if not, abort further checking. 2465 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2466 if (Call->getNumArgs() < ExpectedNumArgs) 2467 return; 2468 2469 unsigned LastArg = (BId == Builtin::BImemset || 2470 BId == Builtin::BIstrndup ? 1 : 2); 2471 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2472 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2473 2474 // We have special checking when the length is a sizeof expression. 2475 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2476 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2477 llvm::FoldingSetNodeID SizeOfArgID; 2478 2479 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2480 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2481 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2482 2483 QualType DestTy = Dest->getType(); 2484 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2485 QualType PointeeTy = DestPtrTy->getPointeeType(); 2486 2487 // Never warn about void type pointers. This can be used to suppress 2488 // false positives. 2489 if (PointeeTy->isVoidType()) 2490 continue; 2491 2492 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2493 // actually comparing the expressions for equality. Because computing the 2494 // expression IDs can be expensive, we only do this if the diagnostic is 2495 // enabled. 2496 if (SizeOfArg && 2497 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2498 SizeOfArg->getExprLoc())) { 2499 // We only compute IDs for expressions if the warning is enabled, and 2500 // cache the sizeof arg's ID. 2501 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2502 SizeOfArg->Profile(SizeOfArgID, Context, true); 2503 llvm::FoldingSetNodeID DestID; 2504 Dest->Profile(DestID, Context, true); 2505 if (DestID == SizeOfArgID) { 2506 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2507 // over sizeof(src) as well. 2508 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2509 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2510 if (UnaryOp->getOpcode() == UO_AddrOf) 2511 ActionIdx = 1; // If its an address-of operator, just remove it. 2512 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2513 ActionIdx = 2; // If the pointee's size is sizeof(char), 2514 // suggest an explicit length. 2515 unsigned DestSrcSelect = 2516 (BId == Builtin::BIstrndup ? 1 : ArgIdx); 2517 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest, 2518 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 2519 << FnName << DestSrcSelect << ActionIdx 2520 << Dest->getSourceRange() 2521 << SizeOfArg->getSourceRange()); 2522 break; 2523 } 2524 } 2525 2526 // Also check for cases where the sizeof argument is the exact same 2527 // type as the memory argument, and where it points to a user-defined 2528 // record type. 2529 if (SizeOfArgTy != QualType()) { 2530 if (PointeeTy->isRecordType() && 2531 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 2532 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 2533 PDiag(diag::warn_sizeof_pointer_type_memaccess) 2534 << FnName << SizeOfArgTy << ArgIdx 2535 << PointeeTy << Dest->getSourceRange() 2536 << LenExpr->getSourceRange()); 2537 break; 2538 } 2539 } 2540 2541 // Always complain about dynamic classes. 2542 if (isDynamicClassType(PointeeTy)) { 2543 2544 unsigned OperationType = 0; 2545 // "overwritten" if we're warning about the destination for any call 2546 // but memcmp; otherwise a verb appropriate to the call. 2547 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 2548 if (BId == Builtin::BImemcpy) 2549 OperationType = 1; 2550 else if(BId == Builtin::BImemmove) 2551 OperationType = 2; 2552 else if (BId == Builtin::BImemcmp) 2553 OperationType = 3; 2554 } 2555 2556 DiagRuntimeBehavior( 2557 Dest->getExprLoc(), Dest, 2558 PDiag(diag::warn_dyn_class_memaccess) 2559 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 2560 << FnName << PointeeTy 2561 << OperationType 2562 << Call->getCallee()->getSourceRange()); 2563 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 2564 BId != Builtin::BImemset) 2565 DiagRuntimeBehavior( 2566 Dest->getExprLoc(), Dest, 2567 PDiag(diag::warn_arc_object_memaccess) 2568 << ArgIdx << FnName << PointeeTy 2569 << Call->getCallee()->getSourceRange()); 2570 else 2571 continue; 2572 2573 DiagRuntimeBehavior( 2574 Dest->getExprLoc(), Dest, 2575 PDiag(diag::note_bad_memaccess_silence) 2576 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2577 break; 2578 } 2579 } 2580} 2581 2582// A little helper routine: ignore addition and subtraction of integer literals. 2583// This intentionally does not ignore all integer constant expressions because 2584// we don't want to remove sizeof(). 2585static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2586 Ex = Ex->IgnoreParenCasts(); 2587 2588 for (;;) { 2589 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2590 if (!BO || !BO->isAdditiveOp()) 2591 break; 2592 2593 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2594 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2595 2596 if (isa<IntegerLiteral>(RHS)) 2597 Ex = LHS; 2598 else if (isa<IntegerLiteral>(LHS)) 2599 Ex = RHS; 2600 else 2601 break; 2602 } 2603 2604 return Ex; 2605} 2606 2607// Warn if the user has made the 'size' argument to strlcpy or strlcat 2608// be the size of the source, instead of the destination. 2609void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2610 IdentifierInfo *FnName) { 2611 2612 // Don't crash if the user has the wrong number of arguments 2613 if (Call->getNumArgs() != 3) 2614 return; 2615 2616 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2617 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2618 const Expr *CompareWithSrc = NULL; 2619 2620 // Look for 'strlcpy(dst, x, sizeof(x))' 2621 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2622 CompareWithSrc = Ex; 2623 else { 2624 // Look for 'strlcpy(dst, x, strlen(x))' 2625 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2626 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2627 && SizeCall->getNumArgs() == 1) 2628 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2629 } 2630 } 2631 2632 if (!CompareWithSrc) 2633 return; 2634 2635 // Determine if the argument to sizeof/strlen is equal to the source 2636 // argument. In principle there's all kinds of things you could do 2637 // here, for instance creating an == expression and evaluating it with 2638 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2639 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2640 if (!SrcArgDRE) 2641 return; 2642 2643 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2644 if (!CompareWithSrcDRE || 2645 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2646 return; 2647 2648 const Expr *OriginalSizeArg = Call->getArg(2); 2649 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2650 << OriginalSizeArg->getSourceRange() << FnName; 2651 2652 // Output a FIXIT hint if the destination is an array (rather than a 2653 // pointer to an array). This could be enhanced to handle some 2654 // pointers if we know the actual size, like if DstArg is 'array+2' 2655 // we could say 'sizeof(array)-2'. 2656 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2657 QualType DstArgTy = DstArg->getType(); 2658 2659 // Only handle constant-sized or VLAs, but not flexible members. 2660 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2661 // Only issue the FIXIT for arrays of size > 1. 2662 if (CAT->getSize().getSExtValue() <= 1) 2663 return; 2664 } else if (!DstArgTy->isVariableArrayType()) { 2665 return; 2666 } 2667 2668 llvm::SmallString<128> sizeString; 2669 llvm::raw_svector_ostream OS(sizeString); 2670 OS << "sizeof("; 2671 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2672 OS << ")"; 2673 2674 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2675 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2676 OS.str()); 2677} 2678 2679//===--- CHECK: Return Address of Stack Variable --------------------------===// 2680 2681static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars); 2682static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars); 2683 2684/// CheckReturnStackAddr - Check if a return statement returns the address 2685/// of a stack variable. 2686void 2687Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 2688 SourceLocation ReturnLoc) { 2689 2690 Expr *stackE = 0; 2691 SmallVector<DeclRefExpr *, 8> refVars; 2692 2693 // Perform checking for returned stack addresses, local blocks, 2694 // label addresses or references to temporaries. 2695 if (lhsType->isPointerType() || 2696 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 2697 stackE = EvalAddr(RetValExp, refVars); 2698 } else if (lhsType->isReferenceType()) { 2699 stackE = EvalVal(RetValExp, refVars); 2700 } 2701 2702 if (stackE == 0) 2703 return; // Nothing suspicious was found. 2704 2705 SourceLocation diagLoc; 2706 SourceRange diagRange; 2707 if (refVars.empty()) { 2708 diagLoc = stackE->getLocStart(); 2709 diagRange = stackE->getSourceRange(); 2710 } else { 2711 // We followed through a reference variable. 'stackE' contains the 2712 // problematic expression but we will warn at the return statement pointing 2713 // at the reference variable. We will later display the "trail" of 2714 // reference variables using notes. 2715 diagLoc = refVars[0]->getLocStart(); 2716 diagRange = refVars[0]->getSourceRange(); 2717 } 2718 2719 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 2720 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 2721 : diag::warn_ret_stack_addr) 2722 << DR->getDecl()->getDeclName() << diagRange; 2723 } else if (isa<BlockExpr>(stackE)) { // local block. 2724 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 2725 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 2726 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 2727 } else { // local temporary. 2728 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 2729 : diag::warn_ret_local_temp_addr) 2730 << diagRange; 2731 } 2732 2733 // Display the "trail" of reference variables that we followed until we 2734 // found the problematic expression using notes. 2735 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 2736 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 2737 // If this var binds to another reference var, show the range of the next 2738 // var, otherwise the var binds to the problematic expression, in which case 2739 // show the range of the expression. 2740 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 2741 : stackE->getSourceRange(); 2742 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 2743 << VD->getDeclName() << range; 2744 } 2745} 2746 2747/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 2748/// check if the expression in a return statement evaluates to an address 2749/// to a location on the stack, a local block, an address of a label, or a 2750/// reference to local temporary. The recursion is used to traverse the 2751/// AST of the return expression, with recursion backtracking when we 2752/// encounter a subexpression that (1) clearly does not lead to one of the 2753/// above problematic expressions (2) is something we cannot determine leads to 2754/// a problematic expression based on such local checking. 2755/// 2756/// Both EvalAddr and EvalVal follow through reference variables to evaluate 2757/// the expression that they point to. Such variables are added to the 2758/// 'refVars' vector so that we know what the reference variable "trail" was. 2759/// 2760/// EvalAddr processes expressions that are pointers that are used as 2761/// references (and not L-values). EvalVal handles all other values. 2762/// At the base case of the recursion is a check for the above problematic 2763/// expressions. 2764/// 2765/// This implementation handles: 2766/// 2767/// * pointer-to-pointer casts 2768/// * implicit conversions from array references to pointers 2769/// * taking the address of fields 2770/// * arbitrary interplay between "&" and "*" operators 2771/// * pointer arithmetic from an address of a stack variable 2772/// * taking the address of an array element where the array is on the stack 2773static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2774 if (E->isTypeDependent()) 2775 return NULL; 2776 2777 // We should only be called for evaluating pointer expressions. 2778 assert((E->getType()->isAnyPointerType() || 2779 E->getType()->isBlockPointerType() || 2780 E->getType()->isObjCQualifiedIdType()) && 2781 "EvalAddr only works on pointers"); 2782 2783 E = E->IgnoreParens(); 2784 2785 // Our "symbolic interpreter" is just a dispatch off the currently 2786 // viewed AST node. We then recursively traverse the AST by calling 2787 // EvalAddr and EvalVal appropriately. 2788 switch (E->getStmtClass()) { 2789 case Stmt::DeclRefExprClass: { 2790 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2791 2792 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2793 // If this is a reference variable, follow through to the expression that 2794 // it points to. 2795 if (V->hasLocalStorage() && 2796 V->getType()->isReferenceType() && V->hasInit()) { 2797 // Add the reference variable to the "trail". 2798 refVars.push_back(DR); 2799 return EvalAddr(V->getInit(), refVars); 2800 } 2801 2802 return NULL; 2803 } 2804 2805 case Stmt::UnaryOperatorClass: { 2806 // The only unary operator that make sense to handle here 2807 // is AddrOf. All others don't make sense as pointers. 2808 UnaryOperator *U = cast<UnaryOperator>(E); 2809 2810 if (U->getOpcode() == UO_AddrOf) 2811 return EvalVal(U->getSubExpr(), refVars); 2812 else 2813 return NULL; 2814 } 2815 2816 case Stmt::BinaryOperatorClass: { 2817 // Handle pointer arithmetic. All other binary operators are not valid 2818 // in this context. 2819 BinaryOperator *B = cast<BinaryOperator>(E); 2820 BinaryOperatorKind op = B->getOpcode(); 2821 2822 if (op != BO_Add && op != BO_Sub) 2823 return NULL; 2824 2825 Expr *Base = B->getLHS(); 2826 2827 // Determine which argument is the real pointer base. It could be 2828 // the RHS argument instead of the LHS. 2829 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 2830 2831 assert (Base->getType()->isPointerType()); 2832 return EvalAddr(Base, refVars); 2833 } 2834 2835 // For conditional operators we need to see if either the LHS or RHS are 2836 // valid DeclRefExpr*s. If one of them is valid, we return it. 2837 case Stmt::ConditionalOperatorClass: { 2838 ConditionalOperator *C = cast<ConditionalOperator>(E); 2839 2840 // Handle the GNU extension for missing LHS. 2841 if (Expr *lhsExpr = C->getLHS()) { 2842 // In C++, we can have a throw-expression, which has 'void' type. 2843 if (!lhsExpr->getType()->isVoidType()) 2844 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 2845 return LHS; 2846 } 2847 2848 // In C++, we can have a throw-expression, which has 'void' type. 2849 if (C->getRHS()->getType()->isVoidType()) 2850 return NULL; 2851 2852 return EvalAddr(C->getRHS(), refVars); 2853 } 2854 2855 case Stmt::BlockExprClass: 2856 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 2857 return E; // local block. 2858 return NULL; 2859 2860 case Stmt::AddrLabelExprClass: 2861 return E; // address of label. 2862 2863 case Stmt::ExprWithCleanupsClass: 2864 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2865 2866 // For casts, we need to handle conversions from arrays to 2867 // pointer values, and pointer-to-pointer conversions. 2868 case Stmt::ImplicitCastExprClass: 2869 case Stmt::CStyleCastExprClass: 2870 case Stmt::CXXFunctionalCastExprClass: 2871 case Stmt::ObjCBridgedCastExprClass: { 2872 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2873 QualType T = SubExpr->getType(); 2874 2875 if (SubExpr->getType()->isPointerType() || 2876 SubExpr->getType()->isBlockPointerType() || 2877 SubExpr->getType()->isObjCQualifiedIdType()) 2878 return EvalAddr(SubExpr, refVars); 2879 else if (T->isArrayType()) 2880 return EvalVal(SubExpr, refVars); 2881 else 2882 return 0; 2883 } 2884 2885 // C++ casts. For dynamic casts, static casts, and const casts, we 2886 // are always converting from a pointer-to-pointer, so we just blow 2887 // through the cast. In the case the dynamic cast doesn't fail (and 2888 // return NULL), we take the conservative route and report cases 2889 // where we return the address of a stack variable. For Reinterpre 2890 // FIXME: The comment about is wrong; we're not always converting 2891 // from pointer to pointer. I'm guessing that this code should also 2892 // handle references to objects. 2893 case Stmt::CXXStaticCastExprClass: 2894 case Stmt::CXXDynamicCastExprClass: 2895 case Stmt::CXXConstCastExprClass: 2896 case Stmt::CXXReinterpretCastExprClass: { 2897 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2898 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2899 return EvalAddr(S, refVars); 2900 else 2901 return NULL; 2902 } 2903 2904 case Stmt::MaterializeTemporaryExprClass: 2905 if (Expr *Result = EvalAddr( 2906 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 2907 refVars)) 2908 return Result; 2909 2910 return E; 2911 2912 // Everything else: we simply don't reason about them. 2913 default: 2914 return NULL; 2915 } 2916} 2917 2918 2919/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2920/// See the comments for EvalAddr for more details. 2921static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2922do { 2923 // We should only be called for evaluating non-pointer expressions, or 2924 // expressions with a pointer type that are not used as references but instead 2925 // are l-values (e.g., DeclRefExpr with a pointer type). 2926 2927 // Our "symbolic interpreter" is just a dispatch off the currently 2928 // viewed AST node. We then recursively traverse the AST by calling 2929 // EvalAddr and EvalVal appropriately. 2930 2931 E = E->IgnoreParens(); 2932 switch (E->getStmtClass()) { 2933 case Stmt::ImplicitCastExprClass: { 2934 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2935 if (IE->getValueKind() == VK_LValue) { 2936 E = IE->getSubExpr(); 2937 continue; 2938 } 2939 return NULL; 2940 } 2941 2942 case Stmt::ExprWithCleanupsClass: 2943 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2944 2945 case Stmt::DeclRefExprClass: { 2946 // When we hit a DeclRefExpr we are looking at code that refers to a 2947 // variable's name. If it's not a reference variable we check if it has 2948 // local storage within the function, and if so, return the expression. 2949 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2950 2951 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2952 if (V->hasLocalStorage()) { 2953 if (!V->getType()->isReferenceType()) 2954 return DR; 2955 2956 // Reference variable, follow through to the expression that 2957 // it points to. 2958 if (V->hasInit()) { 2959 // Add the reference variable to the "trail". 2960 refVars.push_back(DR); 2961 return EvalVal(V->getInit(), refVars); 2962 } 2963 } 2964 2965 return NULL; 2966 } 2967 2968 case Stmt::UnaryOperatorClass: { 2969 // The only unary operator that make sense to handle here 2970 // is Deref. All others don't resolve to a "name." This includes 2971 // handling all sorts of rvalues passed to a unary operator. 2972 UnaryOperator *U = cast<UnaryOperator>(E); 2973 2974 if (U->getOpcode() == UO_Deref) 2975 return EvalAddr(U->getSubExpr(), refVars); 2976 2977 return NULL; 2978 } 2979 2980 case Stmt::ArraySubscriptExprClass: { 2981 // Array subscripts are potential references to data on the stack. We 2982 // retrieve the DeclRefExpr* for the array variable if it indeed 2983 // has local storage. 2984 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2985 } 2986 2987 case Stmt::ConditionalOperatorClass: { 2988 // For conditional operators we need to see if either the LHS or RHS are 2989 // non-NULL Expr's. If one is non-NULL, we return it. 2990 ConditionalOperator *C = cast<ConditionalOperator>(E); 2991 2992 // Handle the GNU extension for missing LHS. 2993 if (Expr *lhsExpr = C->getLHS()) 2994 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 2995 return LHS; 2996 2997 return EvalVal(C->getRHS(), refVars); 2998 } 2999 3000 // Accesses to members are potential references to data on the stack. 3001 case Stmt::MemberExprClass: { 3002 MemberExpr *M = cast<MemberExpr>(E); 3003 3004 // Check for indirect access. We only want direct field accesses. 3005 if (M->isArrow()) 3006 return NULL; 3007 3008 // Check whether the member type is itself a reference, in which case 3009 // we're not going to refer to the member, but to what the member refers to. 3010 if (M->getMemberDecl()->getType()->isReferenceType()) 3011 return NULL; 3012 3013 return EvalVal(M->getBase(), refVars); 3014 } 3015 3016 case Stmt::MaterializeTemporaryExprClass: 3017 if (Expr *Result = EvalVal( 3018 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3019 refVars)) 3020 return Result; 3021 3022 return E; 3023 3024 default: 3025 // Check that we don't return or take the address of a reference to a 3026 // temporary. This is only useful in C++. 3027 if (!E->isTypeDependent() && E->isRValue()) 3028 return E; 3029 3030 // Everything else: we simply don't reason about them. 3031 return NULL; 3032 } 3033} while (true); 3034} 3035 3036//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3037 3038/// Check for comparisons of floating point operands using != and ==. 3039/// Issue a warning if these are no self-comparisons, as they are not likely 3040/// to do what the programmer intended. 3041void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3042 bool EmitWarning = true; 3043 3044 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3045 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3046 3047 // Special case: check for x == x (which is OK). 3048 // Do not emit warnings for such cases. 3049 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3050 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3051 if (DRL->getDecl() == DRR->getDecl()) 3052 EmitWarning = false; 3053 3054 3055 // Special case: check for comparisons against literals that can be exactly 3056 // represented by APFloat. In such cases, do not emit a warning. This 3057 // is a heuristic: often comparison against such literals are used to 3058 // detect if a value in a variable has not changed. This clearly can 3059 // lead to false negatives. 3060 if (EmitWarning) { 3061 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3062 if (FLL->isExact()) 3063 EmitWarning = false; 3064 } else 3065 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3066 if (FLR->isExact()) 3067 EmitWarning = false; 3068 } 3069 } 3070 3071 // Check for comparisons with builtin types. 3072 if (EmitWarning) 3073 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3074 if (CL->isBuiltinCall()) 3075 EmitWarning = false; 3076 3077 if (EmitWarning) 3078 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3079 if (CR->isBuiltinCall()) 3080 EmitWarning = false; 3081 3082 // Emit the diagnostic. 3083 if (EmitWarning) 3084 Diag(Loc, diag::warn_floatingpoint_eq) 3085 << LHS->getSourceRange() << RHS->getSourceRange(); 3086} 3087 3088//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3089//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3090 3091namespace { 3092 3093/// Structure recording the 'active' range of an integer-valued 3094/// expression. 3095struct IntRange { 3096 /// The number of bits active in the int. 3097 unsigned Width; 3098 3099 /// True if the int is known not to have negative values. 3100 bool NonNegative; 3101 3102 IntRange(unsigned Width, bool NonNegative) 3103 : Width(Width), NonNegative(NonNegative) 3104 {} 3105 3106 /// Returns the range of the bool type. 3107 static IntRange forBoolType() { 3108 return IntRange(1, true); 3109 } 3110 3111 /// Returns the range of an opaque value of the given integral type. 3112 static IntRange forValueOfType(ASTContext &C, QualType T) { 3113 return forValueOfCanonicalType(C, 3114 T->getCanonicalTypeInternal().getTypePtr()); 3115 } 3116 3117 /// Returns the range of an opaque value of a canonical integral type. 3118 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3119 assert(T->isCanonicalUnqualified()); 3120 3121 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3122 T = VT->getElementType().getTypePtr(); 3123 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3124 T = CT->getElementType().getTypePtr(); 3125 3126 // For enum types, use the known bit width of the enumerators. 3127 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3128 EnumDecl *Enum = ET->getDecl(); 3129 if (!Enum->isCompleteDefinition()) 3130 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3131 3132 unsigned NumPositive = Enum->getNumPositiveBits(); 3133 unsigned NumNegative = Enum->getNumNegativeBits(); 3134 3135 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3136 } 3137 3138 const BuiltinType *BT = cast<BuiltinType>(T); 3139 assert(BT->isInteger()); 3140 3141 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3142 } 3143 3144 /// Returns the "target" range of a canonical integral type, i.e. 3145 /// the range of values expressible in the type. 3146 /// 3147 /// This matches forValueOfCanonicalType except that enums have the 3148 /// full range of their type, not the range of their enumerators. 3149 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3150 assert(T->isCanonicalUnqualified()); 3151 3152 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3153 T = VT->getElementType().getTypePtr(); 3154 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3155 T = CT->getElementType().getTypePtr(); 3156 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3157 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3158 3159 const BuiltinType *BT = cast<BuiltinType>(T); 3160 assert(BT->isInteger()); 3161 3162 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3163 } 3164 3165 /// Returns the supremum of two ranges: i.e. their conservative merge. 3166 static IntRange join(IntRange L, IntRange R) { 3167 return IntRange(std::max(L.Width, R.Width), 3168 L.NonNegative && R.NonNegative); 3169 } 3170 3171 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3172 static IntRange meet(IntRange L, IntRange R) { 3173 return IntRange(std::min(L.Width, R.Width), 3174 L.NonNegative || R.NonNegative); 3175 } 3176}; 3177 3178IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 3179 if (value.isSigned() && value.isNegative()) 3180 return IntRange(value.getMinSignedBits(), false); 3181 3182 if (value.getBitWidth() > MaxWidth) 3183 value = value.trunc(MaxWidth); 3184 3185 // isNonNegative() just checks the sign bit without considering 3186 // signedness. 3187 return IntRange(value.getActiveBits(), true); 3188} 3189 3190IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3191 unsigned MaxWidth) { 3192 if (result.isInt()) 3193 return GetValueRange(C, result.getInt(), MaxWidth); 3194 3195 if (result.isVector()) { 3196 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3197 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3198 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3199 R = IntRange::join(R, El); 3200 } 3201 return R; 3202 } 3203 3204 if (result.isComplexInt()) { 3205 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3206 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3207 return IntRange::join(R, I); 3208 } 3209 3210 // This can happen with lossless casts to intptr_t of "based" lvalues. 3211 // Assume it might use arbitrary bits. 3212 // FIXME: The only reason we need to pass the type in here is to get 3213 // the sign right on this one case. It would be nice if APValue 3214 // preserved this. 3215 assert(result.isLValue() || result.isAddrLabelDiff()); 3216 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3217} 3218 3219/// Pseudo-evaluate the given integer expression, estimating the 3220/// range of values it might take. 3221/// 3222/// \param MaxWidth - the width to which the value will be truncated 3223IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3224 E = E->IgnoreParens(); 3225 3226 // Try a full evaluation first. 3227 Expr::EvalResult result; 3228 if (E->EvaluateAsRValue(result, C)) 3229 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3230 3231 // I think we only want to look through implicit casts here; if the 3232 // user has an explicit widening cast, we should treat the value as 3233 // being of the new, wider type. 3234 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3235 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3236 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3237 3238 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3239 3240 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3241 3242 // Assume that non-integer casts can span the full range of the type. 3243 if (!isIntegerCast) 3244 return OutputTypeRange; 3245 3246 IntRange SubRange 3247 = GetExprRange(C, CE->getSubExpr(), 3248 std::min(MaxWidth, OutputTypeRange.Width)); 3249 3250 // Bail out if the subexpr's range is as wide as the cast type. 3251 if (SubRange.Width >= OutputTypeRange.Width) 3252 return OutputTypeRange; 3253 3254 // Otherwise, we take the smaller width, and we're non-negative if 3255 // either the output type or the subexpr is. 3256 return IntRange(SubRange.Width, 3257 SubRange.NonNegative || OutputTypeRange.NonNegative); 3258 } 3259 3260 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3261 // If we can fold the condition, just take that operand. 3262 bool CondResult; 3263 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3264 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3265 : CO->getFalseExpr(), 3266 MaxWidth); 3267 3268 // Otherwise, conservatively merge. 3269 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3270 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3271 return IntRange::join(L, R); 3272 } 3273 3274 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3275 switch (BO->getOpcode()) { 3276 3277 // Boolean-valued operations are single-bit and positive. 3278 case BO_LAnd: 3279 case BO_LOr: 3280 case BO_LT: 3281 case BO_GT: 3282 case BO_LE: 3283 case BO_GE: 3284 case BO_EQ: 3285 case BO_NE: 3286 return IntRange::forBoolType(); 3287 3288 // The type of the assignments is the type of the LHS, so the RHS 3289 // is not necessarily the same type. 3290 case BO_MulAssign: 3291 case BO_DivAssign: 3292 case BO_RemAssign: 3293 case BO_AddAssign: 3294 case BO_SubAssign: 3295 case BO_XorAssign: 3296 case BO_OrAssign: 3297 // TODO: bitfields? 3298 return IntRange::forValueOfType(C, E->getType()); 3299 3300 // Simple assignments just pass through the RHS, which will have 3301 // been coerced to the LHS type. 3302 case BO_Assign: 3303 // TODO: bitfields? 3304 return GetExprRange(C, BO->getRHS(), MaxWidth); 3305 3306 // Operations with opaque sources are black-listed. 3307 case BO_PtrMemD: 3308 case BO_PtrMemI: 3309 return IntRange::forValueOfType(C, E->getType()); 3310 3311 // Bitwise-and uses the *infinum* of the two source ranges. 3312 case BO_And: 3313 case BO_AndAssign: 3314 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3315 GetExprRange(C, BO->getRHS(), MaxWidth)); 3316 3317 // Left shift gets black-listed based on a judgement call. 3318 case BO_Shl: 3319 // ...except that we want to treat '1 << (blah)' as logically 3320 // positive. It's an important idiom. 3321 if (IntegerLiteral *I 3322 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3323 if (I->getValue() == 1) { 3324 IntRange R = IntRange::forValueOfType(C, E->getType()); 3325 return IntRange(R.Width, /*NonNegative*/ true); 3326 } 3327 } 3328 // fallthrough 3329 3330 case BO_ShlAssign: 3331 return IntRange::forValueOfType(C, E->getType()); 3332 3333 // Right shift by a constant can narrow its left argument. 3334 case BO_Shr: 3335 case BO_ShrAssign: { 3336 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3337 3338 // If the shift amount is a positive constant, drop the width by 3339 // that much. 3340 llvm::APSInt shift; 3341 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3342 shift.isNonNegative()) { 3343 unsigned zext = shift.getZExtValue(); 3344 if (zext >= L.Width) 3345 L.Width = (L.NonNegative ? 0 : 1); 3346 else 3347 L.Width -= zext; 3348 } 3349 3350 return L; 3351 } 3352 3353 // Comma acts as its right operand. 3354 case BO_Comma: 3355 return GetExprRange(C, BO->getRHS(), MaxWidth); 3356 3357 // Black-list pointer subtractions. 3358 case BO_Sub: 3359 if (BO->getLHS()->getType()->isPointerType()) 3360 return IntRange::forValueOfType(C, E->getType()); 3361 break; 3362 3363 // The width of a division result is mostly determined by the size 3364 // of the LHS. 3365 case BO_Div: { 3366 // Don't 'pre-truncate' the operands. 3367 unsigned opWidth = C.getIntWidth(E->getType()); 3368 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3369 3370 // If the divisor is constant, use that. 3371 llvm::APSInt divisor; 3372 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3373 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3374 if (log2 >= L.Width) 3375 L.Width = (L.NonNegative ? 0 : 1); 3376 else 3377 L.Width = std::min(L.Width - log2, MaxWidth); 3378 return L; 3379 } 3380 3381 // Otherwise, just use the LHS's width. 3382 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3383 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3384 } 3385 3386 // The result of a remainder can't be larger than the result of 3387 // either side. 3388 case BO_Rem: { 3389 // Don't 'pre-truncate' the operands. 3390 unsigned opWidth = C.getIntWidth(E->getType()); 3391 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3392 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3393 3394 IntRange meet = IntRange::meet(L, R); 3395 meet.Width = std::min(meet.Width, MaxWidth); 3396 return meet; 3397 } 3398 3399 // The default behavior is okay for these. 3400 case BO_Mul: 3401 case BO_Add: 3402 case BO_Xor: 3403 case BO_Or: 3404 break; 3405 } 3406 3407 // The default case is to treat the operation as if it were closed 3408 // on the narrowest type that encompasses both operands. 3409 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3410 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3411 return IntRange::join(L, R); 3412 } 3413 3414 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3415 switch (UO->getOpcode()) { 3416 // Boolean-valued operations are white-listed. 3417 case UO_LNot: 3418 return IntRange::forBoolType(); 3419 3420 // Operations with opaque sources are black-listed. 3421 case UO_Deref: 3422 case UO_AddrOf: // should be impossible 3423 return IntRange::forValueOfType(C, E->getType()); 3424 3425 default: 3426 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3427 } 3428 } 3429 3430 if (dyn_cast<OffsetOfExpr>(E)) { 3431 IntRange::forValueOfType(C, E->getType()); 3432 } 3433 3434 if (FieldDecl *BitField = E->getBitField()) 3435 return IntRange(BitField->getBitWidthValue(C), 3436 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3437 3438 return IntRange::forValueOfType(C, E->getType()); 3439} 3440 3441IntRange GetExprRange(ASTContext &C, Expr *E) { 3442 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3443} 3444 3445/// Checks whether the given value, which currently has the given 3446/// source semantics, has the same value when coerced through the 3447/// target semantics. 3448bool IsSameFloatAfterCast(const llvm::APFloat &value, 3449 const llvm::fltSemantics &Src, 3450 const llvm::fltSemantics &Tgt) { 3451 llvm::APFloat truncated = value; 3452 3453 bool ignored; 3454 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3455 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3456 3457 return truncated.bitwiseIsEqual(value); 3458} 3459 3460/// Checks whether the given value, which currently has the given 3461/// source semantics, has the same value when coerced through the 3462/// target semantics. 3463/// 3464/// The value might be a vector of floats (or a complex number). 3465bool IsSameFloatAfterCast(const APValue &value, 3466 const llvm::fltSemantics &Src, 3467 const llvm::fltSemantics &Tgt) { 3468 if (value.isFloat()) 3469 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3470 3471 if (value.isVector()) { 3472 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3473 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3474 return false; 3475 return true; 3476 } 3477 3478 assert(value.isComplexFloat()); 3479 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3480 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3481} 3482 3483void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3484 3485static bool IsZero(Sema &S, Expr *E) { 3486 // Suppress cases where we are comparing against an enum constant. 3487 if (const DeclRefExpr *DR = 3488 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3489 if (isa<EnumConstantDecl>(DR->getDecl())) 3490 return false; 3491 3492 // Suppress cases where the '0' value is expanded from a macro. 3493 if (E->getLocStart().isMacroID()) 3494 return false; 3495 3496 llvm::APSInt Value; 3497 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3498} 3499 3500static bool HasEnumType(Expr *E) { 3501 // Strip off implicit integral promotions. 3502 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3503 if (ICE->getCastKind() != CK_IntegralCast && 3504 ICE->getCastKind() != CK_NoOp) 3505 break; 3506 E = ICE->getSubExpr(); 3507 } 3508 3509 return E->getType()->isEnumeralType(); 3510} 3511 3512void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3513 BinaryOperatorKind op = E->getOpcode(); 3514 if (E->isValueDependent()) 3515 return; 3516 3517 if (op == BO_LT && IsZero(S, E->getRHS())) { 3518 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3519 << "< 0" << "false" << HasEnumType(E->getLHS()) 3520 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3521 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3522 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3523 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3524 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3525 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3526 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3527 << "0 >" << "false" << HasEnumType(E->getRHS()) 3528 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3529 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3530 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3531 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3532 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3533 } 3534} 3535 3536/// Analyze the operands of the given comparison. Implements the 3537/// fallback case from AnalyzeComparison. 3538void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3539 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3540 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3541} 3542 3543/// \brief Implements -Wsign-compare. 3544/// 3545/// \param E the binary operator to check for warnings 3546void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3547 // The type the comparison is being performed in. 3548 QualType T = E->getLHS()->getType(); 3549 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3550 && "comparison with mismatched types"); 3551 3552 // We don't do anything special if this isn't an unsigned integral 3553 // comparison: we're only interested in integral comparisons, and 3554 // signed comparisons only happen in cases we don't care to warn about. 3555 // 3556 // We also don't care about value-dependent expressions or expressions 3557 // whose result is a constant. 3558 if (!T->hasUnsignedIntegerRepresentation() 3559 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3560 return AnalyzeImpConvsInComparison(S, E); 3561 3562 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3563 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3564 3565 // Check to see if one of the (unmodified) operands is of different 3566 // signedness. 3567 Expr *signedOperand, *unsignedOperand; 3568 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3569 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3570 "unsigned comparison between two signed integer expressions?"); 3571 signedOperand = LHS; 3572 unsignedOperand = RHS; 3573 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3574 signedOperand = RHS; 3575 unsignedOperand = LHS; 3576 } else { 3577 CheckTrivialUnsignedComparison(S, E); 3578 return AnalyzeImpConvsInComparison(S, E); 3579 } 3580 3581 // Otherwise, calculate the effective range of the signed operand. 3582 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3583 3584 // Go ahead and analyze implicit conversions in the operands. Note 3585 // that we skip the implicit conversions on both sides. 3586 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3587 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3588 3589 // If the signed range is non-negative, -Wsign-compare won't fire, 3590 // but we should still check for comparisons which are always true 3591 // or false. 3592 if (signedRange.NonNegative) 3593 return CheckTrivialUnsignedComparison(S, E); 3594 3595 // For (in)equality comparisons, if the unsigned operand is a 3596 // constant which cannot collide with a overflowed signed operand, 3597 // then reinterpreting the signed operand as unsigned will not 3598 // change the result of the comparison. 3599 if (E->isEqualityOp()) { 3600 unsigned comparisonWidth = S.Context.getIntWidth(T); 3601 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3602 3603 // We should never be unable to prove that the unsigned operand is 3604 // non-negative. 3605 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3606 3607 if (unsignedRange.Width < comparisonWidth) 3608 return; 3609 } 3610 3611 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 3612 << LHS->getType() << RHS->getType() 3613 << LHS->getSourceRange() << RHS->getSourceRange(); 3614} 3615 3616/// Analyzes an attempt to assign the given value to a bitfield. 3617/// 3618/// Returns true if there was something fishy about the attempt. 3619bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 3620 SourceLocation InitLoc) { 3621 assert(Bitfield->isBitField()); 3622 if (Bitfield->isInvalidDecl()) 3623 return false; 3624 3625 // White-list bool bitfields. 3626 if (Bitfield->getType()->isBooleanType()) 3627 return false; 3628 3629 // Ignore value- or type-dependent expressions. 3630 if (Bitfield->getBitWidth()->isValueDependent() || 3631 Bitfield->getBitWidth()->isTypeDependent() || 3632 Init->isValueDependent() || 3633 Init->isTypeDependent()) 3634 return false; 3635 3636 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 3637 3638 llvm::APSInt Value; 3639 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 3640 return false; 3641 3642 unsigned OriginalWidth = Value.getBitWidth(); 3643 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 3644 3645 if (OriginalWidth <= FieldWidth) 3646 return false; 3647 3648 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 3649 3650 // It's fairly common to write values into signed bitfields 3651 // that, if sign-extended, would end up becoming a different 3652 // value. We don't want to warn about that. 3653 if (Value.isSigned() && Value.isNegative()) 3654 TruncatedValue = TruncatedValue.sext(OriginalWidth); 3655 else 3656 TruncatedValue = TruncatedValue.zext(OriginalWidth); 3657 3658 if (Value == TruncatedValue) 3659 return false; 3660 3661 std::string PrettyValue = Value.toString(10); 3662 std::string PrettyTrunc = TruncatedValue.toString(10); 3663 3664 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 3665 << PrettyValue << PrettyTrunc << OriginalInit->getType() 3666 << Init->getSourceRange(); 3667 3668 return true; 3669} 3670 3671/// Analyze the given simple or compound assignment for warning-worthy 3672/// operations. 3673void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 3674 // Just recurse on the LHS. 3675 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3676 3677 // We want to recurse on the RHS as normal unless we're assigning to 3678 // a bitfield. 3679 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 3680 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 3681 E->getOperatorLoc())) { 3682 // Recurse, ignoring any implicit conversions on the RHS. 3683 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 3684 E->getOperatorLoc()); 3685 } 3686 } 3687 3688 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3689} 3690 3691/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3692void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 3693 SourceLocation CContext, unsigned diag) { 3694 S.Diag(E->getExprLoc(), diag) 3695 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 3696} 3697 3698/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3699void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 3700 unsigned diag) { 3701 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag); 3702} 3703 3704/// Diagnose an implicit cast from a literal expression. Does not warn when the 3705/// cast wouldn't lose information. 3706void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 3707 SourceLocation CContext) { 3708 // Try to convert the literal exactly to an integer. If we can, don't warn. 3709 bool isExact = false; 3710 const llvm::APFloat &Value = FL->getValue(); 3711 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 3712 T->hasUnsignedIntegerRepresentation()); 3713 if (Value.convertToInteger(IntegerValue, 3714 llvm::APFloat::rmTowardZero, &isExact) 3715 == llvm::APFloat::opOK && isExact) 3716 return; 3717 3718 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 3719 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext); 3720} 3721 3722std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 3723 if (!Range.Width) return "0"; 3724 3725 llvm::APSInt ValueInRange = Value; 3726 ValueInRange.setIsSigned(!Range.NonNegative); 3727 ValueInRange = ValueInRange.trunc(Range.Width); 3728 return ValueInRange.toString(10); 3729} 3730 3731void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 3732 SourceLocation CC, bool *ICContext = 0) { 3733 if (E->isTypeDependent() || E->isValueDependent()) return; 3734 3735 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 3736 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 3737 if (Source == Target) return; 3738 if (Target->isDependentType()) return; 3739 3740 // If the conversion context location is invalid don't complain. We also 3741 // don't want to emit a warning if the issue occurs from the expansion of 3742 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 3743 // delay this check as long as possible. Once we detect we are in that 3744 // scenario, we just return. 3745 if (CC.isInvalid()) 3746 return; 3747 3748 // Diagnose implicit casts to bool. 3749 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 3750 if (isa<StringLiteral>(E)) 3751 // Warn on string literal to bool. Checks for string literals in logical 3752 // expressions, for instances, assert(0 && "error here"), is prevented 3753 // by a check in AnalyzeImplicitConversions(). 3754 return DiagnoseImpCast(S, E, T, CC, 3755 diag::warn_impcast_string_literal_to_bool); 3756 if (Source->isFunctionType()) { 3757 // Warn on function to bool. Checks free functions and static member 3758 // functions. Weakly imported functions are excluded from the check, 3759 // since it's common to test their value to check whether the linker 3760 // found a definition for them. 3761 ValueDecl *D = 0; 3762 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 3763 D = R->getDecl(); 3764 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 3765 D = M->getMemberDecl(); 3766 } 3767 3768 if (D && !D->isWeak()) { 3769 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 3770 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 3771 << F << E->getSourceRange() << SourceRange(CC); 3772 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 3773 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 3774 QualType ReturnType; 3775 UnresolvedSet<4> NonTemplateOverloads; 3776 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 3777 if (!ReturnType.isNull() 3778 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 3779 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 3780 << FixItHint::CreateInsertion( 3781 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 3782 return; 3783 } 3784 } 3785 } 3786 return; // Other casts to bool are not checked. 3787 } 3788 3789 // Strip vector types. 3790 if (isa<VectorType>(Source)) { 3791 if (!isa<VectorType>(Target)) { 3792 if (S.SourceMgr.isInSystemMacro(CC)) 3793 return; 3794 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 3795 } 3796 3797 // If the vector cast is cast between two vectors of the same size, it is 3798 // a bitcast, not a conversion. 3799 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 3800 return; 3801 3802 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 3803 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 3804 } 3805 3806 // Strip complex types. 3807 if (isa<ComplexType>(Source)) { 3808 if (!isa<ComplexType>(Target)) { 3809 if (S.SourceMgr.isInSystemMacro(CC)) 3810 return; 3811 3812 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 3813 } 3814 3815 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 3816 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 3817 } 3818 3819 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 3820 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 3821 3822 // If the source is floating point... 3823 if (SourceBT && SourceBT->isFloatingPoint()) { 3824 // ...and the target is floating point... 3825 if (TargetBT && TargetBT->isFloatingPoint()) { 3826 // ...then warn if we're dropping FP rank. 3827 3828 // Builtin FP kinds are ordered by increasing FP rank. 3829 if (SourceBT->getKind() > TargetBT->getKind()) { 3830 // Don't warn about float constants that are precisely 3831 // representable in the target type. 3832 Expr::EvalResult result; 3833 if (E->EvaluateAsRValue(result, S.Context)) { 3834 // Value might be a float, a float vector, or a float complex. 3835 if (IsSameFloatAfterCast(result.Val, 3836 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 3837 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 3838 return; 3839 } 3840 3841 if (S.SourceMgr.isInSystemMacro(CC)) 3842 return; 3843 3844 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 3845 } 3846 return; 3847 } 3848 3849 // If the target is integral, always warn. 3850 if ((TargetBT && TargetBT->isInteger())) { 3851 if (S.SourceMgr.isInSystemMacro(CC)) 3852 return; 3853 3854 Expr *InnerE = E->IgnoreParenImpCasts(); 3855 // We also want to warn on, e.g., "int i = -1.234" 3856 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 3857 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 3858 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 3859 3860 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 3861 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 3862 } else { 3863 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 3864 } 3865 } 3866 3867 return; 3868 } 3869 3870 if (!Source->isIntegerType() || !Target->isIntegerType()) 3871 return; 3872 3873 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 3874 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 3875 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer) 3876 << E->getSourceRange() << clang::SourceRange(CC); 3877 return; 3878 } 3879 3880 IntRange SourceRange = GetExprRange(S.Context, E); 3881 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 3882 3883 if (SourceRange.Width > TargetRange.Width) { 3884 // If the source is a constant, use a default-on diagnostic. 3885 // TODO: this should happen for bitfield stores, too. 3886 llvm::APSInt Value(32); 3887 if (E->isIntegerConstantExpr(Value, S.Context)) { 3888 if (S.SourceMgr.isInSystemMacro(CC)) 3889 return; 3890 3891 std::string PrettySourceValue = Value.toString(10); 3892 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 3893 3894 S.DiagRuntimeBehavior(E->getExprLoc(), E, 3895 S.PDiag(diag::warn_impcast_integer_precision_constant) 3896 << PrettySourceValue << PrettyTargetValue 3897 << E->getType() << T << E->getSourceRange() 3898 << clang::SourceRange(CC)); 3899 return; 3900 } 3901 3902 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 3903 if (S.SourceMgr.isInSystemMacro(CC)) 3904 return; 3905 3906 if (SourceRange.Width == 64 && TargetRange.Width == 32) 3907 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 3908 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 3909 } 3910 3911 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 3912 (!TargetRange.NonNegative && SourceRange.NonNegative && 3913 SourceRange.Width == TargetRange.Width)) { 3914 3915 if (S.SourceMgr.isInSystemMacro(CC)) 3916 return; 3917 3918 unsigned DiagID = diag::warn_impcast_integer_sign; 3919 3920 // Traditionally, gcc has warned about this under -Wsign-compare. 3921 // We also want to warn about it in -Wconversion. 3922 // So if -Wconversion is off, use a completely identical diagnostic 3923 // in the sign-compare group. 3924 // The conditional-checking code will 3925 if (ICContext) { 3926 DiagID = diag::warn_impcast_integer_sign_conditional; 3927 *ICContext = true; 3928 } 3929 3930 return DiagnoseImpCast(S, E, T, CC, DiagID); 3931 } 3932 3933 // Diagnose conversions between different enumeration types. 3934 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 3935 // type, to give us better diagnostics. 3936 QualType SourceType = E->getType(); 3937 if (!S.getLangOptions().CPlusPlus) { 3938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3939 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3940 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 3941 SourceType = S.Context.getTypeDeclType(Enum); 3942 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 3943 } 3944 } 3945 3946 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 3947 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 3948 if ((SourceEnum->getDecl()->getIdentifier() || 3949 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 3950 (TargetEnum->getDecl()->getIdentifier() || 3951 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 3952 SourceEnum != TargetEnum) { 3953 if (S.SourceMgr.isInSystemMacro(CC)) 3954 return; 3955 3956 return DiagnoseImpCast(S, E, SourceType, T, CC, 3957 diag::warn_impcast_different_enum_types); 3958 } 3959 3960 return; 3961} 3962 3963void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 3964 3965void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 3966 SourceLocation CC, bool &ICContext) { 3967 E = E->IgnoreParenImpCasts(); 3968 3969 if (isa<ConditionalOperator>(E)) 3970 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 3971 3972 AnalyzeImplicitConversions(S, E, CC); 3973 if (E->getType() != T) 3974 return CheckImplicitConversion(S, E, T, CC, &ICContext); 3975 return; 3976} 3977 3978void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 3979 SourceLocation CC = E->getQuestionLoc(); 3980 3981 AnalyzeImplicitConversions(S, E->getCond(), CC); 3982 3983 bool Suspicious = false; 3984 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 3985 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 3986 3987 // If -Wconversion would have warned about either of the candidates 3988 // for a signedness conversion to the context type... 3989 if (!Suspicious) return; 3990 3991 // ...but it's currently ignored... 3992 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 3993 CC)) 3994 return; 3995 3996 // ...then check whether it would have warned about either of the 3997 // candidates for a signedness conversion to the condition type. 3998 if (E->getType() == T) return; 3999 4000 Suspicious = false; 4001 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4002 E->getType(), CC, &Suspicious); 4003 if (!Suspicious) 4004 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4005 E->getType(), CC, &Suspicious); 4006} 4007 4008/// AnalyzeImplicitConversions - Find and report any interesting 4009/// implicit conversions in the given expression. There are a couple 4010/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4011void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4012 QualType T = OrigE->getType(); 4013 Expr *E = OrigE->IgnoreParenImpCasts(); 4014 4015 if (E->isTypeDependent() || E->isValueDependent()) 4016 return; 4017 4018 // For conditional operators, we analyze the arguments as if they 4019 // were being fed directly into the output. 4020 if (isa<ConditionalOperator>(E)) { 4021 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4022 CheckConditionalOperator(S, CO, T); 4023 return; 4024 } 4025 4026 // Go ahead and check any implicit conversions we might have skipped. 4027 // The non-canonical typecheck is just an optimization; 4028 // CheckImplicitConversion will filter out dead implicit conversions. 4029 if (E->getType() != T) 4030 CheckImplicitConversion(S, E, T, CC); 4031 4032 // Now continue drilling into this expression. 4033 4034 // Skip past explicit casts. 4035 if (isa<ExplicitCastExpr>(E)) { 4036 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4037 return AnalyzeImplicitConversions(S, E, CC); 4038 } 4039 4040 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4041 // Do a somewhat different check with comparison operators. 4042 if (BO->isComparisonOp()) 4043 return AnalyzeComparison(S, BO); 4044 4045 // And with assignments and compound assignments. 4046 if (BO->isAssignmentOp()) 4047 return AnalyzeAssignment(S, BO); 4048 } 4049 4050 // These break the otherwise-useful invariant below. Fortunately, 4051 // we don't really need to recurse into them, because any internal 4052 // expressions should have been analyzed already when they were 4053 // built into statements. 4054 if (isa<StmtExpr>(E)) return; 4055 4056 // Don't descend into unevaluated contexts. 4057 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4058 4059 // Now just recurse over the expression's children. 4060 CC = E->getExprLoc(); 4061 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4062 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4063 for (Stmt::child_range I = E->children(); I; ++I) { 4064 Expr *ChildExpr = cast<Expr>(*I); 4065 if (IsLogicalOperator && 4066 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4067 // Ignore checking string literals that are in logical operators. 4068 continue; 4069 AnalyzeImplicitConversions(S, ChildExpr, CC); 4070 } 4071} 4072 4073} // end anonymous namespace 4074 4075/// Diagnoses "dangerous" implicit conversions within the given 4076/// expression (which is a full expression). Implements -Wconversion 4077/// and -Wsign-compare. 4078/// 4079/// \param CC the "context" location of the implicit conversion, i.e. 4080/// the most location of the syntactic entity requiring the implicit 4081/// conversion 4082void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4083 // Don't diagnose in unevaluated contexts. 4084 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4085 return; 4086 4087 // Don't diagnose for value- or type-dependent expressions. 4088 if (E->isTypeDependent() || E->isValueDependent()) 4089 return; 4090 4091 // Check for array bounds violations in cases where the check isn't triggered 4092 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4093 // ArraySubscriptExpr is on the RHS of a variable initialization. 4094 CheckArrayAccess(E); 4095 4096 // This is not the right CC for (e.g.) a variable initialization. 4097 AnalyzeImplicitConversions(*this, E, CC); 4098} 4099 4100void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4101 FieldDecl *BitField, 4102 Expr *Init) { 4103 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4104} 4105 4106/// CheckParmsForFunctionDef - Check that the parameters of the given 4107/// function are appropriate for the definition of a function. This 4108/// takes care of any checks that cannot be performed on the 4109/// declaration itself, e.g., that the types of each of the function 4110/// parameters are complete. 4111bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4112 bool CheckParameterNames) { 4113 bool HasInvalidParm = false; 4114 for (; P != PEnd; ++P) { 4115 ParmVarDecl *Param = *P; 4116 4117 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4118 // function declarator that is part of a function definition of 4119 // that function shall not have incomplete type. 4120 // 4121 // This is also C++ [dcl.fct]p6. 4122 if (!Param->isInvalidDecl() && 4123 RequireCompleteType(Param->getLocation(), Param->getType(), 4124 diag::err_typecheck_decl_incomplete_type)) { 4125 Param->setInvalidDecl(); 4126 HasInvalidParm = true; 4127 } 4128 4129 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4130 // declaration of each parameter shall include an identifier. 4131 if (CheckParameterNames && 4132 Param->getIdentifier() == 0 && 4133 !Param->isImplicit() && 4134 !getLangOptions().CPlusPlus) 4135 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4136 4137 // C99 6.7.5.3p12: 4138 // If the function declarator is not part of a definition of that 4139 // function, parameters may have incomplete type and may use the [*] 4140 // notation in their sequences of declarator specifiers to specify 4141 // variable length array types. 4142 QualType PType = Param->getOriginalType(); 4143 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4144 if (AT->getSizeModifier() == ArrayType::Star) { 4145 // FIXME: This diagnosic should point the the '[*]' if source-location 4146 // information is added for it. 4147 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4148 } 4149 } 4150 } 4151 4152 return HasInvalidParm; 4153} 4154 4155/// CheckCastAlign - Implements -Wcast-align, which warns when a 4156/// pointer cast increases the alignment requirements. 4157void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4158 // This is actually a lot of work to potentially be doing on every 4159 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4160 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4161 TRange.getBegin()) 4162 == DiagnosticsEngine::Ignored) 4163 return; 4164 4165 // Ignore dependent types. 4166 if (T->isDependentType() || Op->getType()->isDependentType()) 4167 return; 4168 4169 // Require that the destination be a pointer type. 4170 const PointerType *DestPtr = T->getAs<PointerType>(); 4171 if (!DestPtr) return; 4172 4173 // If the destination has alignment 1, we're done. 4174 QualType DestPointee = DestPtr->getPointeeType(); 4175 if (DestPointee->isIncompleteType()) return; 4176 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4177 if (DestAlign.isOne()) return; 4178 4179 // Require that the source be a pointer type. 4180 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4181 if (!SrcPtr) return; 4182 QualType SrcPointee = SrcPtr->getPointeeType(); 4183 4184 // Whitelist casts from cv void*. We already implicitly 4185 // whitelisted casts to cv void*, since they have alignment 1. 4186 // Also whitelist casts involving incomplete types, which implicitly 4187 // includes 'void'. 4188 if (SrcPointee->isIncompleteType()) return; 4189 4190 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4191 if (SrcAlign >= DestAlign) return; 4192 4193 Diag(TRange.getBegin(), diag::warn_cast_align) 4194 << Op->getType() << T 4195 << static_cast<unsigned>(SrcAlign.getQuantity()) 4196 << static_cast<unsigned>(DestAlign.getQuantity()) 4197 << TRange << Op->getSourceRange(); 4198} 4199 4200static const Type* getElementType(const Expr *BaseExpr) { 4201 const Type* EltType = BaseExpr->getType().getTypePtr(); 4202 if (EltType->isAnyPointerType()) 4203 return EltType->getPointeeType().getTypePtr(); 4204 else if (EltType->isArrayType()) 4205 return EltType->getBaseElementTypeUnsafe(); 4206 return EltType; 4207} 4208 4209/// \brief Check whether this array fits the idiom of a size-one tail padded 4210/// array member of a struct. 4211/// 4212/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4213/// commonly used to emulate flexible arrays in C89 code. 4214static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4215 const NamedDecl *ND) { 4216 if (Size != 1 || !ND) return false; 4217 4218 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4219 if (!FD) return false; 4220 4221 // Don't consider sizes resulting from macro expansions or template argument 4222 // substitution to form C89 tail-padded arrays. 4223 ConstantArrayTypeLoc TL = 4224 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc()); 4225 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr()); 4226 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4227 return false; 4228 4229 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4230 if (!RD) return false; 4231 if (RD->isUnion()) return false; 4232 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4233 if (!CRD->isStandardLayout()) return false; 4234 } 4235 4236 // See if this is the last field decl in the record. 4237 const Decl *D = FD; 4238 while ((D = D->getNextDeclInContext())) 4239 if (isa<FieldDecl>(D)) 4240 return false; 4241 return true; 4242} 4243 4244void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4245 const ArraySubscriptExpr *ASE, 4246 bool AllowOnePastEnd, bool IndexNegated) { 4247 IndexExpr = IndexExpr->IgnoreParenCasts(); 4248 if (IndexExpr->isValueDependent()) 4249 return; 4250 4251 const Type *EffectiveType = getElementType(BaseExpr); 4252 BaseExpr = BaseExpr->IgnoreParenCasts(); 4253 const ConstantArrayType *ArrayTy = 4254 Context.getAsConstantArrayType(BaseExpr->getType()); 4255 if (!ArrayTy) 4256 return; 4257 4258 llvm::APSInt index; 4259 if (!IndexExpr->EvaluateAsInt(index, Context)) 4260 return; 4261 if (IndexNegated) 4262 index = -index; 4263 4264 const NamedDecl *ND = NULL; 4265 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4266 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4267 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4268 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4269 4270 if (index.isUnsigned() || !index.isNegative()) { 4271 llvm::APInt size = ArrayTy->getSize(); 4272 if (!size.isStrictlyPositive()) 4273 return; 4274 4275 const Type* BaseType = getElementType(BaseExpr); 4276 if (BaseType != EffectiveType) { 4277 // Make sure we're comparing apples to apples when comparing index to size 4278 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4279 uint64_t array_typesize = Context.getTypeSize(BaseType); 4280 // Handle ptrarith_typesize being zero, such as when casting to void* 4281 if (!ptrarith_typesize) ptrarith_typesize = 1; 4282 if (ptrarith_typesize != array_typesize) { 4283 // There's a cast to a different size type involved 4284 uint64_t ratio = array_typesize / ptrarith_typesize; 4285 // TODO: Be smarter about handling cases where array_typesize is not a 4286 // multiple of ptrarith_typesize 4287 if (ptrarith_typesize * ratio == array_typesize) 4288 size *= llvm::APInt(size.getBitWidth(), ratio); 4289 } 4290 } 4291 4292 if (size.getBitWidth() > index.getBitWidth()) 4293 index = index.sext(size.getBitWidth()); 4294 else if (size.getBitWidth() < index.getBitWidth()) 4295 size = size.sext(index.getBitWidth()); 4296 4297 // For array subscripting the index must be less than size, but for pointer 4298 // arithmetic also allow the index (offset) to be equal to size since 4299 // computing the next address after the end of the array is legal and 4300 // commonly done e.g. in C++ iterators and range-based for loops. 4301 if (AllowOnePastEnd ? index.sle(size) : index.slt(size)) 4302 return; 4303 4304 // Also don't warn for arrays of size 1 which are members of some 4305 // structure. These are often used to approximate flexible arrays in C89 4306 // code. 4307 if (IsTailPaddedMemberArray(*this, size, ND)) 4308 return; 4309 4310 // Suppress the warning if the subscript expression (as identified by the 4311 // ']' location) and the index expression are both from macro expansions 4312 // within a system header. 4313 if (ASE) { 4314 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4315 ASE->getRBracketLoc()); 4316 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4317 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4318 IndexExpr->getLocStart()); 4319 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4320 return; 4321 } 4322 } 4323 4324 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4325 if (ASE) 4326 DiagID = diag::warn_array_index_exceeds_bounds; 4327 4328 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4329 PDiag(DiagID) << index.toString(10, true) 4330 << size.toString(10, true) 4331 << (unsigned)size.getLimitedValue(~0U) 4332 << IndexExpr->getSourceRange()); 4333 } else { 4334 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4335 if (!ASE) { 4336 DiagID = diag::warn_ptr_arith_precedes_bounds; 4337 if (index.isNegative()) index = -index; 4338 } 4339 4340 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4341 PDiag(DiagID) << index.toString(10, true) 4342 << IndexExpr->getSourceRange()); 4343 } 4344 4345 if (!ND) { 4346 // Try harder to find a NamedDecl to point at in the note. 4347 while (const ArraySubscriptExpr *ASE = 4348 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 4349 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 4350 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4351 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4352 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4353 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4354 } 4355 4356 if (ND) 4357 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4358 PDiag(diag::note_array_index_out_of_bounds) 4359 << ND->getDeclName()); 4360} 4361 4362void Sema::CheckArrayAccess(const Expr *expr) { 4363 int AllowOnePastEnd = 0; 4364 while (expr) { 4365 expr = expr->IgnoreParenImpCasts(); 4366 switch (expr->getStmtClass()) { 4367 case Stmt::ArraySubscriptExprClass: { 4368 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4369 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 4370 AllowOnePastEnd > 0); 4371 return; 4372 } 4373 case Stmt::UnaryOperatorClass: { 4374 // Only unwrap the * and & unary operators 4375 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4376 expr = UO->getSubExpr(); 4377 switch (UO->getOpcode()) { 4378 case UO_AddrOf: 4379 AllowOnePastEnd++; 4380 break; 4381 case UO_Deref: 4382 AllowOnePastEnd--; 4383 break; 4384 default: 4385 return; 4386 } 4387 break; 4388 } 4389 case Stmt::ConditionalOperatorClass: { 4390 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4391 if (const Expr *lhs = cond->getLHS()) 4392 CheckArrayAccess(lhs); 4393 if (const Expr *rhs = cond->getRHS()) 4394 CheckArrayAccess(rhs); 4395 return; 4396 } 4397 default: 4398 return; 4399 } 4400 } 4401} 4402 4403//===--- CHECK: Objective-C retain cycles ----------------------------------// 4404 4405namespace { 4406 struct RetainCycleOwner { 4407 RetainCycleOwner() : Variable(0), Indirect(false) {} 4408 VarDecl *Variable; 4409 SourceRange Range; 4410 SourceLocation Loc; 4411 bool Indirect; 4412 4413 void setLocsFrom(Expr *e) { 4414 Loc = e->getExprLoc(); 4415 Range = e->getSourceRange(); 4416 } 4417 }; 4418} 4419 4420/// Consider whether capturing the given variable can possibly lead to 4421/// a retain cycle. 4422static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4423 // In ARC, it's captured strongly iff the variable has __strong 4424 // lifetime. In MRR, it's captured strongly if the variable is 4425 // __block and has an appropriate type. 4426 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4427 return false; 4428 4429 owner.Variable = var; 4430 owner.setLocsFrom(ref); 4431 return true; 4432} 4433 4434static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 4435 while (true) { 4436 e = e->IgnoreParens(); 4437 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4438 switch (cast->getCastKind()) { 4439 case CK_BitCast: 4440 case CK_LValueBitCast: 4441 case CK_LValueToRValue: 4442 case CK_ARCReclaimReturnedObject: 4443 e = cast->getSubExpr(); 4444 continue; 4445 4446 default: 4447 return false; 4448 } 4449 } 4450 4451 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4452 ObjCIvarDecl *ivar = ref->getDecl(); 4453 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4454 return false; 4455 4456 // Try to find a retain cycle in the base. 4457 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 4458 return false; 4459 4460 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4461 owner.Indirect = true; 4462 return true; 4463 } 4464 4465 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4466 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4467 if (!var) return false; 4468 return considerVariable(var, ref, owner); 4469 } 4470 4471 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) { 4472 owner.Variable = ref->getDecl(); 4473 owner.setLocsFrom(ref); 4474 return true; 4475 } 4476 4477 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4478 if (member->isArrow()) return false; 4479 4480 // Don't count this as an indirect ownership. 4481 e = member->getBase(); 4482 continue; 4483 } 4484 4485 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4486 // Only pay attention to pseudo-objects on property references. 4487 ObjCPropertyRefExpr *pre 4488 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4489 ->IgnoreParens()); 4490 if (!pre) return false; 4491 if (pre->isImplicitProperty()) return false; 4492 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4493 if (!property->isRetaining() && 4494 !(property->getPropertyIvarDecl() && 4495 property->getPropertyIvarDecl()->getType() 4496 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4497 return false; 4498 4499 owner.Indirect = true; 4500 if (pre->isSuperReceiver()) { 4501 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 4502 if (!owner.Variable) 4503 return false; 4504 owner.Loc = pre->getLocation(); 4505 owner.Range = pre->getSourceRange(); 4506 return true; 4507 } 4508 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4509 ->getSourceExpr()); 4510 continue; 4511 } 4512 4513 // Array ivars? 4514 4515 return false; 4516 } 4517} 4518 4519namespace { 4520 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4521 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4522 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4523 Variable(variable), Capturer(0) {} 4524 4525 VarDecl *Variable; 4526 Expr *Capturer; 4527 4528 void VisitDeclRefExpr(DeclRefExpr *ref) { 4529 if (ref->getDecl() == Variable && !Capturer) 4530 Capturer = ref; 4531 } 4532 4533 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) { 4534 if (ref->getDecl() == Variable && !Capturer) 4535 Capturer = ref; 4536 } 4537 4538 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4539 if (Capturer) return; 4540 Visit(ref->getBase()); 4541 if (Capturer && ref->isFreeIvar()) 4542 Capturer = ref; 4543 } 4544 4545 void VisitBlockExpr(BlockExpr *block) { 4546 // Look inside nested blocks 4547 if (block->getBlockDecl()->capturesVariable(Variable)) 4548 Visit(block->getBlockDecl()->getBody()); 4549 } 4550 }; 4551} 4552 4553/// Check whether the given argument is a block which captures a 4554/// variable. 4555static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4556 assert(owner.Variable && owner.Loc.isValid()); 4557 4558 e = e->IgnoreParenCasts(); 4559 BlockExpr *block = dyn_cast<BlockExpr>(e); 4560 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4561 return 0; 4562 4563 FindCaptureVisitor visitor(S.Context, owner.Variable); 4564 visitor.Visit(block->getBlockDecl()->getBody()); 4565 return visitor.Capturer; 4566} 4567 4568static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4569 RetainCycleOwner &owner) { 4570 assert(capturer); 4571 assert(owner.Variable && owner.Loc.isValid()); 4572 4573 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 4574 << owner.Variable << capturer->getSourceRange(); 4575 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 4576 << owner.Indirect << owner.Range; 4577} 4578 4579/// Check for a keyword selector that starts with the word 'add' or 4580/// 'set'. 4581static bool isSetterLikeSelector(Selector sel) { 4582 if (sel.isUnarySelector()) return false; 4583 4584 StringRef str = sel.getNameForSlot(0); 4585 while (!str.empty() && str.front() == '_') str = str.substr(1); 4586 if (str.startswith("set")) 4587 str = str.substr(3); 4588 else if (str.startswith("add")) { 4589 // Specially whitelist 'addOperationWithBlock:'. 4590 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 4591 return false; 4592 str = str.substr(3); 4593 } 4594 else 4595 return false; 4596 4597 if (str.empty()) return true; 4598 return !islower(str.front()); 4599} 4600 4601/// Check a message send to see if it's likely to cause a retain cycle. 4602void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 4603 // Only check instance methods whose selector looks like a setter. 4604 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 4605 return; 4606 4607 // Try to find a variable that the receiver is strongly owned by. 4608 RetainCycleOwner owner; 4609 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 4610 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 4611 return; 4612 } else { 4613 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 4614 owner.Variable = getCurMethodDecl()->getSelfDecl(); 4615 owner.Loc = msg->getSuperLoc(); 4616 owner.Range = msg->getSuperLoc(); 4617 } 4618 4619 // Check whether the receiver is captured by any of the arguments. 4620 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 4621 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 4622 return diagnoseRetainCycle(*this, capturer, owner); 4623} 4624 4625/// Check a property assign to see if it's likely to cause a retain cycle. 4626void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 4627 RetainCycleOwner owner; 4628 if (!findRetainCycleOwner(*this, receiver, owner)) 4629 return; 4630 4631 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 4632 diagnoseRetainCycle(*this, capturer, owner); 4633} 4634 4635bool Sema::checkUnsafeAssigns(SourceLocation Loc, 4636 QualType LHS, Expr *RHS) { 4637 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 4638 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 4639 return false; 4640 // strip off any implicit cast added to get to the one arc-specific 4641 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4642 if (cast->getCastKind() == CK_ARCConsumeObject) { 4643 Diag(Loc, diag::warn_arc_retained_assign) 4644 << (LT == Qualifiers::OCL_ExplicitNone) 4645 << RHS->getSourceRange(); 4646 return true; 4647 } 4648 RHS = cast->getSubExpr(); 4649 } 4650 return false; 4651} 4652 4653void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 4654 Expr *LHS, Expr *RHS) { 4655 QualType LHSType = LHS->getType(); 4656 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 4657 return; 4658 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 4659 // FIXME. Check for other life times. 4660 if (LT != Qualifiers::OCL_None) 4661 return; 4662 4663 if (ObjCPropertyRefExpr *PRE 4664 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) { 4665 if (PRE->isImplicitProperty()) 4666 return; 4667 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 4668 if (!PD) 4669 return; 4670 4671 unsigned Attributes = PD->getPropertyAttributes(); 4672 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) 4673 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4674 if (cast->getCastKind() == CK_ARCConsumeObject) { 4675 Diag(Loc, diag::warn_arc_retained_property_assign) 4676 << RHS->getSourceRange(); 4677 return; 4678 } 4679 RHS = cast->getSubExpr(); 4680 } 4681 } 4682} 4683