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