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