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