SemaExpr.cpp revision f4e3cfbe8abd124be6341ef5d714819b4fbd9082
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 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 semantic analysis for expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/AnalysisBasedWarnings.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/RecursiveASTVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/DeclSpec.h" 34#include "clang/Sema/Designator.h" 35#include "clang/Sema/Scope.h" 36#include "clang/Sema/ScopeInfo.h" 37#include "clang/Sema/ParsedTemplate.h" 38#include "clang/Sema/Template.h" 39using namespace clang; 40using namespace sema; 41 42 43/// \brief Determine whether the use of this declaration is valid, and 44/// emit any corresponding diagnostics. 45/// 46/// This routine diagnoses various problems with referencing 47/// declarations that can occur when using a declaration. For example, 48/// it might warn if a deprecated or unavailable declaration is being 49/// used, or produce an error (and return true) if a C++0x deleted 50/// function is being used. 51/// 52/// If IgnoreDeprecated is set to true, this should not warn about deprecated 53/// decls. 54/// 55/// \returns true if there was an error (this declaration cannot be 56/// referenced), false otherwise. 57/// 58bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 59 bool UnknownObjCClass) { 60 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 61 // If there were any diagnostics suppressed by template argument deduction, 62 // emit them now. 63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator 64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 65 if (Pos != SuppressedDiagnostics.end()) { 66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 68 Diag(Suppressed[I].first, Suppressed[I].second); 69 70 // Clear out the list of suppressed diagnostics, so that we don't emit 71 // them again for this specialization. However, we don't remove this 72 // entry from the table, because we want to avoid ever emitting these 73 // diagnostics again. 74 Suppressed.clear(); 75 } 76 } 77 78 // See if this is an auto-typed variable whose initializer we are parsing. 79 if (ParsingInitForAutoVars.count(D)) { 80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 81 << D->getDeclName(); 82 return true; 83 } 84 85 // See if the decl is deprecated. 86 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>()) 87 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass); 88 89 // See if the decl is unavailable 90 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) { 91 if (UA->getMessage().empty()) { 92 if (!UnknownObjCClass) 93 Diag(Loc, diag::err_unavailable) << D->getDeclName(); 94 else 95 Diag(Loc, diag::warn_unavailable_fwdclass_message) 96 << D->getDeclName(); 97 } 98 else 99 Diag(Loc, diag::err_unavailable_message) 100 << D->getDeclName() << UA->getMessage(); 101 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 102 } 103 104 // See if this is a deleted function. 105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 106 if (FD->isDeleted()) { 107 Diag(Loc, diag::err_deleted_function_use); 108 Diag(D->getLocation(), diag::note_unavailable_here) << true; 109 return true; 110 } 111 } 112 113 // Warn if this is used but marked unused. 114 if (D->hasAttr<UnusedAttr>()) 115 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 116 117 return false; 118} 119 120/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 121/// (and other functions in future), which have been declared with sentinel 122/// attribute. It warns if call does not have the sentinel argument. 123/// 124void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 125 Expr **Args, unsigned NumArgs) { 126 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 127 if (!attr) 128 return; 129 130 // FIXME: In C++0x, if any of the arguments are parameter pack 131 // expansions, we can't check for the sentinel now. 132 int sentinelPos = attr->getSentinel(); 133 int nullPos = attr->getNullPos(); 134 135 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 136 // base class. Then we won't be needing two versions of the same code. 137 unsigned int i = 0; 138 bool warnNotEnoughArgs = false; 139 int isMethod = 0; 140 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 141 // skip over named parameters. 142 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 143 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 144 if (nullPos) 145 --nullPos; 146 else 147 ++i; 148 } 149 warnNotEnoughArgs = (P != E || i >= NumArgs); 150 isMethod = 1; 151 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 152 // skip over named parameters. 153 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 154 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 155 if (nullPos) 156 --nullPos; 157 else 158 ++i; 159 } 160 warnNotEnoughArgs = (P != E || i >= NumArgs); 161 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 162 // block or function pointer call. 163 QualType Ty = V->getType(); 164 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 165 const FunctionType *FT = Ty->isFunctionPointerType() 166 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 167 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 168 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 169 unsigned NumArgsInProto = Proto->getNumArgs(); 170 unsigned k; 171 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 172 if (nullPos) 173 --nullPos; 174 else 175 ++i; 176 } 177 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 178 } 179 if (Ty->isBlockPointerType()) 180 isMethod = 2; 181 } else 182 return; 183 } else 184 return; 185 186 if (warnNotEnoughArgs) { 187 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 188 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 189 return; 190 } 191 int sentinel = i; 192 while (sentinelPos > 0 && i < NumArgs-1) { 193 --sentinelPos; 194 ++i; 195 } 196 if (sentinelPos > 0) { 197 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 198 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 199 return; 200 } 201 while (i < NumArgs-1) { 202 ++i; 203 ++sentinel; 204 } 205 Expr *sentinelExpr = Args[sentinel]; 206 if (!sentinelExpr) return; 207 if (sentinelExpr->isTypeDependent()) return; 208 if (sentinelExpr->isValueDependent()) return; 209 210 // nullptr_t is always treated as null. 211 if (sentinelExpr->getType()->isNullPtrType()) return; 212 213 if (sentinelExpr->getType()->isAnyPointerType() && 214 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context, 215 Expr::NPC_ValueDependentIsNull)) 216 return; 217 218 // Unfortunately, __null has type 'int'. 219 if (isa<GNUNullExpr>(sentinelExpr)) return; 220 221 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 223} 224 225SourceRange Sema::getExprRange(ExprTy *E) const { 226 Expr *Ex = (Expr *)E; 227 return Ex? Ex->getSourceRange() : SourceRange(); 228} 229 230//===----------------------------------------------------------------------===// 231// Standard Promotions and Conversions 232//===----------------------------------------------------------------------===// 233 234/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 235void Sema::DefaultFunctionArrayConversion(Expr *&E) { 236 QualType Ty = E->getType(); 237 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 238 239 if (Ty->isFunctionType()) 240 ImpCastExprToType(E, Context.getPointerType(Ty), 241 CK_FunctionToPointerDecay); 242 else if (Ty->isArrayType()) { 243 // In C90 mode, arrays only promote to pointers if the array expression is 244 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 245 // type 'array of type' is converted to an expression that has type 'pointer 246 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 247 // that has type 'array of type' ...". The relevant change is "an lvalue" 248 // (C90) to "an expression" (C99). 249 // 250 // C++ 4.2p1: 251 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 252 // T" can be converted to an rvalue of type "pointer to T". 253 // 254 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue()) 255 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 256 CK_ArrayToPointerDecay); 257 } 258} 259 260void Sema::DefaultLvalueConversion(Expr *&E) { 261 // C++ [conv.lval]p1: 262 // A glvalue of a non-function, non-array type T can be 263 // converted to a prvalue. 264 if (!E->isGLValue()) return; 265 266 QualType T = E->getType(); 267 assert(!T.isNull() && "r-value conversion on typeless expression?"); 268 269 // Create a load out of an ObjCProperty l-value, if necessary. 270 if (E->getObjectKind() == OK_ObjCProperty) { 271 ConvertPropertyForRValue(E); 272 if (!E->isGLValue()) 273 return; 274 } 275 276 // We don't want to throw lvalue-to-rvalue casts on top of 277 // expressions of certain types in C++. 278 if (getLangOptions().CPlusPlus && 279 (E->getType() == Context.OverloadTy || 280 T->isDependentType() || 281 T->isRecordType())) 282 return; 283 284 // The C standard is actually really unclear on this point, and 285 // DR106 tells us what the result should be but not why. It's 286 // generally best to say that void types just doesn't undergo 287 // lvalue-to-rvalue at all. Note that expressions of unqualified 288 // 'void' type are never l-values, but qualified void can be. 289 if (T->isVoidType()) 290 return; 291 292 // C++ [conv.lval]p1: 293 // [...] If T is a non-class type, the type of the prvalue is the 294 // cv-unqualified version of T. Otherwise, the type of the 295 // rvalue is T. 296 // 297 // C99 6.3.2.1p2: 298 // If the lvalue has qualified type, the value has the unqualified 299 // version of the type of the lvalue; otherwise, the value has the 300 // type of the lvalue. 301 if (T.hasQualifiers()) 302 T = T.getUnqualifiedType(); 303 304 CheckArrayAccess(E); 305 306 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 307 E, 0, VK_RValue); 308} 309 310void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) { 311 DefaultFunctionArrayConversion(E); 312 DefaultLvalueConversion(E); 313} 314 315 316/// UsualUnaryConversions - Performs various conversions that are common to most 317/// operators (C99 6.3). The conversions of array and function types are 318/// sometimes surpressed. For example, the array->pointer conversion doesn't 319/// apply if the array is an argument to the sizeof or address (&) operators. 320/// In these instances, this routine should *not* be called. 321Expr *Sema::UsualUnaryConversions(Expr *&E) { 322 // First, convert to an r-value. 323 DefaultFunctionArrayLvalueConversion(E); 324 325 QualType Ty = E->getType(); 326 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 327 328 // Try to perform integral promotions if the object has a theoretically 329 // promotable type. 330 if (Ty->isIntegralOrUnscopedEnumerationType()) { 331 // C99 6.3.1.1p2: 332 // 333 // The following may be used in an expression wherever an int or 334 // unsigned int may be used: 335 // - an object or expression with an integer type whose integer 336 // conversion rank is less than or equal to the rank of int 337 // and unsigned int. 338 // - A bit-field of type _Bool, int, signed int, or unsigned int. 339 // 340 // If an int can represent all values of the original type, the 341 // value is converted to an int; otherwise, it is converted to an 342 // unsigned int. These are called the integer promotions. All 343 // other types are unchanged by the integer promotions. 344 345 QualType PTy = Context.isPromotableBitField(E); 346 if (!PTy.isNull()) { 347 ImpCastExprToType(E, PTy, CK_IntegralCast); 348 return E; 349 } 350 if (Ty->isPromotableIntegerType()) { 351 QualType PT = Context.getPromotedIntegerType(Ty); 352 ImpCastExprToType(E, PT, CK_IntegralCast); 353 return E; 354 } 355 } 356 357 return E; 358} 359 360/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 361/// do not have a prototype. Arguments that have type float are promoted to 362/// double. All other argument types are converted by UsualUnaryConversions(). 363void Sema::DefaultArgumentPromotion(Expr *&Expr) { 364 QualType Ty = Expr->getType(); 365 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 366 367 UsualUnaryConversions(Expr); 368 369 // If this is a 'float' (CVR qualified or typedef) promote to double. 370 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 371 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast); 372} 373 374/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 375/// will warn if the resulting type is not a POD type, and rejects ObjC 376/// interfaces passed by value. This returns true if the argument type is 377/// completely illegal. 378bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT, 379 FunctionDecl *FDecl) { 380 DefaultArgumentPromotion(Expr); 381 382 // __builtin_va_start takes the second argument as a "varargs" argument, but 383 // it doesn't actually do anything with it. It doesn't need to be non-pod 384 // etc. 385 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start) 386 return false; 387 388 if (Expr->getType()->isObjCObjectType() && 389 DiagRuntimeBehavior(Expr->getLocStart(), 0, 390 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 391 << Expr->getType() << CT)) 392 return true; 393 394 if (!Expr->getType()->isPODType() && 395 DiagRuntimeBehavior(Expr->getLocStart(), 0, 396 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 397 << Expr->getType() << CT)) 398 return true; 399 400 return false; 401} 402 403/// UsualArithmeticConversions - Performs various conversions that are common to 404/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 405/// routine returns the first non-arithmetic type found. The client is 406/// responsible for emitting appropriate error diagnostics. 407/// FIXME: verify the conversion rules for "complex int" are consistent with 408/// GCC. 409QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 410 bool isCompAssign) { 411 if (!isCompAssign) 412 UsualUnaryConversions(lhsExpr); 413 414 UsualUnaryConversions(rhsExpr); 415 416 // For conversion purposes, we ignore any qualifiers. 417 // For example, "const float" and "float" are equivalent. 418 QualType lhs = 419 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 420 QualType rhs = 421 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 422 423 // If both types are identical, no conversion is needed. 424 if (lhs == rhs) 425 return lhs; 426 427 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 428 // The caller can deal with this (e.g. pointer + int). 429 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 430 return lhs; 431 432 // Apply unary and bitfield promotions to the LHS's type. 433 QualType lhs_unpromoted = lhs; 434 if (lhs->isPromotableIntegerType()) 435 lhs = Context.getPromotedIntegerType(lhs); 436 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 437 if (!LHSBitfieldPromoteTy.isNull()) 438 lhs = LHSBitfieldPromoteTy; 439 if (lhs != lhs_unpromoted && !isCompAssign) 440 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast); 441 442 // If both types are identical, no conversion is needed. 443 if (lhs == rhs) 444 return lhs; 445 446 // At this point, we have two different arithmetic types. 447 448 // Handle complex types first (C99 6.3.1.8p1). 449 bool LHSComplexFloat = lhs->isComplexType(); 450 bool RHSComplexFloat = rhs->isComplexType(); 451 if (LHSComplexFloat || RHSComplexFloat) { 452 // if we have an integer operand, the result is the complex type. 453 454 if (!RHSComplexFloat && !rhs->isRealFloatingType()) { 455 if (rhs->isIntegerType()) { 456 QualType fp = cast<ComplexType>(lhs)->getElementType(); 457 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating); 458 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex); 459 } else { 460 assert(rhs->isComplexIntegerType()); 461 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex); 462 } 463 return lhs; 464 } 465 466 if (!LHSComplexFloat && !lhs->isRealFloatingType()) { 467 if (!isCompAssign) { 468 // int -> float -> _Complex float 469 if (lhs->isIntegerType()) { 470 QualType fp = cast<ComplexType>(rhs)->getElementType(); 471 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating); 472 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex); 473 } else { 474 assert(lhs->isComplexIntegerType()); 475 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex); 476 } 477 } 478 return rhs; 479 } 480 481 // This handles complex/complex, complex/float, or float/complex. 482 // When both operands are complex, the shorter operand is converted to the 483 // type of the longer, and that is the type of the result. This corresponds 484 // to what is done when combining two real floating-point operands. 485 // The fun begins when size promotion occur across type domains. 486 // From H&S 6.3.4: When one operand is complex and the other is a real 487 // floating-point type, the less precise type is converted, within it's 488 // real or complex domain, to the precision of the other type. For example, 489 // when combining a "long double" with a "double _Complex", the 490 // "double _Complex" is promoted to "long double _Complex". 491 int order = Context.getFloatingTypeOrder(lhs, rhs); 492 493 // If both are complex, just cast to the more precise type. 494 if (LHSComplexFloat && RHSComplexFloat) { 495 if (order > 0) { 496 // _Complex float -> _Complex double 497 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast); 498 return lhs; 499 500 } else if (order < 0) { 501 // _Complex float -> _Complex double 502 if (!isCompAssign) 503 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast); 504 return rhs; 505 } 506 return lhs; 507 } 508 509 // If just the LHS is complex, the RHS needs to be converted, 510 // and the LHS might need to be promoted. 511 if (LHSComplexFloat) { 512 if (order > 0) { // LHS is wider 513 // float -> _Complex double 514 QualType fp = cast<ComplexType>(lhs)->getElementType(); 515 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast); 516 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex); 517 return lhs; 518 } 519 520 // RHS is at least as wide. Find its corresponding complex type. 521 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs)); 522 523 // double -> _Complex double 524 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex); 525 526 // _Complex float -> _Complex double 527 if (!isCompAssign && order < 0) 528 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast); 529 530 return result; 531 } 532 533 // Just the RHS is complex, so the LHS needs to be converted 534 // and the RHS might need to be promoted. 535 assert(RHSComplexFloat); 536 537 if (order < 0) { // RHS is wider 538 // float -> _Complex double 539 if (!isCompAssign) { 540 QualType fp = cast<ComplexType>(rhs)->getElementType(); 541 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast); 542 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex); 543 } 544 return rhs; 545 } 546 547 // LHS is at least as wide. Find its corresponding complex type. 548 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs)); 549 550 // double -> _Complex double 551 if (!isCompAssign) 552 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex); 553 554 // _Complex float -> _Complex double 555 if (order > 0) 556 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast); 557 558 return result; 559 } 560 561 // Now handle "real" floating types (i.e. float, double, long double). 562 bool LHSFloat = lhs->isRealFloatingType(); 563 bool RHSFloat = rhs->isRealFloatingType(); 564 if (LHSFloat || RHSFloat) { 565 // If we have two real floating types, convert the smaller operand 566 // to the bigger result. 567 if (LHSFloat && RHSFloat) { 568 int order = Context.getFloatingTypeOrder(lhs, rhs); 569 if (order > 0) { 570 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast); 571 return lhs; 572 } 573 574 assert(order < 0 && "illegal float comparison"); 575 if (!isCompAssign) 576 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast); 577 return rhs; 578 } 579 580 // If we have an integer operand, the result is the real floating type. 581 if (LHSFloat) { 582 if (rhs->isIntegerType()) { 583 // Convert rhs to the lhs floating point type. 584 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating); 585 return lhs; 586 } 587 588 // Convert both sides to the appropriate complex float. 589 assert(rhs->isComplexIntegerType()); 590 QualType result = Context.getComplexType(lhs); 591 592 // _Complex int -> _Complex float 593 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex); 594 595 // float -> _Complex float 596 if (!isCompAssign) 597 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex); 598 599 return result; 600 } 601 602 assert(RHSFloat); 603 if (lhs->isIntegerType()) { 604 // Convert lhs to the rhs floating point type. 605 if (!isCompAssign) 606 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating); 607 return rhs; 608 } 609 610 // Convert both sides to the appropriate complex float. 611 assert(lhs->isComplexIntegerType()); 612 QualType result = Context.getComplexType(rhs); 613 614 // _Complex int -> _Complex float 615 if (!isCompAssign) 616 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex); 617 618 // float -> _Complex float 619 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex); 620 621 return result; 622 } 623 624 // Handle GCC complex int extension. 625 // FIXME: if the operands are (int, _Complex long), we currently 626 // don't promote the complex. Also, signedness? 627 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 628 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 629 if (lhsComplexInt && rhsComplexInt) { 630 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 631 rhsComplexInt->getElementType()); 632 assert(order && "inequal types with equal element ordering"); 633 if (order > 0) { 634 // _Complex int -> _Complex long 635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast); 636 return lhs; 637 } 638 639 if (!isCompAssign) 640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast); 641 return rhs; 642 } else if (lhsComplexInt) { 643 // int -> _Complex int 644 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex); 645 return lhs; 646 } else if (rhsComplexInt) { 647 // int -> _Complex int 648 if (!isCompAssign) 649 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex); 650 return rhs; 651 } 652 653 // Finally, we have two differing integer types. 654 // The rules for this case are in C99 6.3.1.8 655 int compare = Context.getIntegerTypeOrder(lhs, rhs); 656 bool lhsSigned = lhs->hasSignedIntegerRepresentation(), 657 rhsSigned = rhs->hasSignedIntegerRepresentation(); 658 if (lhsSigned == rhsSigned) { 659 // Same signedness; use the higher-ranked type 660 if (compare >= 0) { 661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast); 662 return lhs; 663 } else if (!isCompAssign) 664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast); 665 return rhs; 666 } else if (compare != (lhsSigned ? 1 : -1)) { 667 // The unsigned type has greater than or equal rank to the 668 // signed type, so use the unsigned type 669 if (rhsSigned) { 670 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast); 671 return lhs; 672 } else if (!isCompAssign) 673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast); 674 return rhs; 675 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 676 // The two types are different widths; if we are here, that 677 // means the signed type is larger than the unsigned type, so 678 // use the signed type. 679 if (lhsSigned) { 680 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast); 681 return lhs; 682 } else if (!isCompAssign) 683 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast); 684 return rhs; 685 } else { 686 // The signed type is higher-ranked than the unsigned type, 687 // but isn't actually any bigger (like unsigned int and long 688 // on most 32-bit systems). Use the unsigned type corresponding 689 // to the signed type. 690 QualType result = 691 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 692 ImpCastExprToType(rhsExpr, result, CK_IntegralCast); 693 if (!isCompAssign) 694 ImpCastExprToType(lhsExpr, result, CK_IntegralCast); 695 return result; 696 } 697} 698 699//===----------------------------------------------------------------------===// 700// Semantic Analysis for various Expression Types 701//===----------------------------------------------------------------------===// 702 703 704/// ActOnStringLiteral - The specified tokens were lexed as pasted string 705/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 706/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 707/// multiple tokens. However, the common case is that StringToks points to one 708/// string. 709/// 710ExprResult 711Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 712 assert(NumStringToks && "Must have at least one string!"); 713 714 StringLiteralParser Literal(StringToks, NumStringToks, PP); 715 if (Literal.hadError) 716 return ExprError(); 717 718 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 719 for (unsigned i = 0; i != NumStringToks; ++i) 720 StringTokLocs.push_back(StringToks[i].getLocation()); 721 722 QualType StrTy = Context.CharTy; 723 if (Literal.AnyWide) StrTy = Context.getWCharType(); 724 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 725 726 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 727 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 728 StrTy.addConst(); 729 730 // Get an array type for the string, according to C99 6.4.5. This includes 731 // the nul terminator character as well as the string length for pascal 732 // strings. 733 StrTy = Context.getConstantArrayType(StrTy, 734 llvm::APInt(32, Literal.GetNumStringChars()+1), 735 ArrayType::Normal, 0); 736 737 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 738 return Owned(StringLiteral::Create(Context, Literal.GetString(), 739 Literal.GetStringLength(), 740 Literal.AnyWide, StrTy, 741 &StringTokLocs[0], 742 StringTokLocs.size())); 743} 744 745enum CaptureResult { 746 /// No capture is required. 747 CR_NoCapture, 748 749 /// A capture is required. 750 CR_Capture, 751 752 /// A by-ref capture is required. 753 CR_CaptureByRef, 754 755 /// An error occurred when trying to capture the given variable. 756 CR_Error 757}; 758 759/// Diagnose an uncapturable value reference. 760/// 761/// \param var - the variable referenced 762/// \param DC - the context which we couldn't capture through 763static CaptureResult 764diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 765 VarDecl *var, DeclContext *DC) { 766 switch (S.ExprEvalContexts.back().Context) { 767 case Sema::Unevaluated: 768 // The argument will never be evaluated, so don't complain. 769 return CR_NoCapture; 770 771 case Sema::PotentiallyEvaluated: 772 case Sema::PotentiallyEvaluatedIfUsed: 773 break; 774 775 case Sema::PotentiallyPotentiallyEvaluated: 776 // FIXME: delay these! 777 break; 778 } 779 780 // Don't diagnose about capture if we're not actually in code right 781 // now; in general, there are more appropriate places that will 782 // diagnose this. 783 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture; 784 785 // This particular madness can happen in ill-formed default 786 // arguments; claim it's okay and let downstream code handle it. 787 if (isa<ParmVarDecl>(var) && 788 S.CurContext == var->getDeclContext()->getParent()) 789 return CR_NoCapture; 790 791 DeclarationName functionName; 792 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext())) 793 functionName = fn->getDeclName(); 794 // FIXME: variable from enclosing block that we couldn't capture from! 795 796 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 797 << var->getIdentifier() << functionName; 798 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 799 << var->getIdentifier(); 800 801 return CR_Error; 802} 803 804/// There is a well-formed capture at a particular scope level; 805/// propagate it through all the nested blocks. 806static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex, 807 const BlockDecl::Capture &capture) { 808 VarDecl *var = capture.getVariable(); 809 810 // Update all the inner blocks with the capture information. 811 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size(); 812 i != e; ++i) { 813 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]); 814 innerBlock->Captures.push_back( 815 BlockDecl::Capture(capture.getVariable(), capture.isByRef(), 816 /*nested*/ true, capture.getCopyExpr())); 817 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1 818 } 819 820 return capture.isByRef() ? CR_CaptureByRef : CR_Capture; 821} 822 823/// shouldCaptureValueReference - Determine if a reference to the 824/// given value in the current context requires a variable capture. 825/// 826/// This also keeps the captures set in the BlockScopeInfo records 827/// up-to-date. 828static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc, 829 ValueDecl *value) { 830 // Only variables ever require capture. 831 VarDecl *var = dyn_cast<VarDecl>(value); 832 if (!var) return CR_NoCapture; 833 834 // Fast path: variables from the current context never require capture. 835 DeclContext *DC = S.CurContext; 836 if (var->getDeclContext() == DC) return CR_NoCapture; 837 838 // Only variables with local storage require capture. 839 // FIXME: What about 'const' variables in C++? 840 if (!var->hasLocalStorage()) return CR_NoCapture; 841 842 // Otherwise, we need to capture. 843 844 unsigned functionScopesIndex = S.FunctionScopes.size() - 1; 845 do { 846 // Only blocks (and eventually C++0x closures) can capture; other 847 // scopes don't work. 848 if (!isa<BlockDecl>(DC)) 849 return diagnoseUncapturableValueReference(S, loc, var, DC); 850 851 BlockScopeInfo *blockScope = 852 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 853 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC)); 854 855 // Check whether we've already captured it in this block. If so, 856 // we're done. 857 if (unsigned indexPlus1 = blockScope->CaptureMap[var]) 858 return propagateCapture(S, functionScopesIndex, 859 blockScope->Captures[indexPlus1 - 1]); 860 861 functionScopesIndex--; 862 DC = cast<BlockDecl>(DC)->getDeclContext(); 863 } while (var->getDeclContext() != DC); 864 865 // Okay, we descended all the way to the block that defines the variable. 866 // Actually try to capture it. 867 QualType type = var->getType(); 868 869 // Prohibit variably-modified types. 870 if (type->isVariablyModifiedType()) { 871 S.Diag(loc, diag::err_ref_vm_type); 872 S.Diag(var->getLocation(), diag::note_declared_at); 873 return CR_Error; 874 } 875 876 // Prohibit arrays, even in __block variables, but not references to 877 // them. 878 if (type->isArrayType()) { 879 S.Diag(loc, diag::err_ref_array_type); 880 S.Diag(var->getLocation(), diag::note_declared_at); 881 return CR_Error; 882 } 883 884 S.MarkDeclarationReferenced(loc, var); 885 886 // The BlocksAttr indicates the variable is bound by-reference. 887 bool byRef = var->hasAttr<BlocksAttr>(); 888 889 // Build a copy expression. 890 Expr *copyExpr = 0; 891 if (!byRef && S.getLangOptions().CPlusPlus && 892 !type->isDependentType() && type->isStructureOrClassType()) { 893 // According to the blocks spec, the capture of a variable from 894 // the stack requires a const copy constructor. This is not true 895 // of the copy/move done to move a __block variable to the heap. 896 type.addConst(); 897 898 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc); 899 ExprResult result = 900 S.PerformCopyInitialization( 901 InitializedEntity::InitializeBlock(var->getLocation(), 902 type, false), 903 loc, S.Owned(declRef)); 904 905 // Build a full-expression copy expression if initialization 906 // succeeded and used a non-trivial constructor. Recover from 907 // errors by pretending that the copy isn't necessary. 908 if (!result.isInvalid() && 909 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) { 910 result = S.MaybeCreateExprWithCleanups(result); 911 copyExpr = result.take(); 912 } 913 } 914 915 // We're currently at the declarer; go back to the closure. 916 functionScopesIndex++; 917 BlockScopeInfo *blockScope = 918 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 919 920 // Build a valid capture in this scope. 921 blockScope->Captures.push_back( 922 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr)); 923 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1 924 925 // Propagate that to inner captures if necessary. 926 return propagateCapture(S, functionScopesIndex, 927 blockScope->Captures.back()); 928} 929 930static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd, 931 const DeclarationNameInfo &NameInfo, 932 bool byRef) { 933 assert(isa<VarDecl>(vd) && "capturing non-variable"); 934 935 VarDecl *var = cast<VarDecl>(vd); 936 assert(var->hasLocalStorage() && "capturing non-local"); 937 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong"); 938 939 QualType exprType = var->getType().getNonReferenceType(); 940 941 BlockDeclRefExpr *BDRE; 942 if (!byRef) { 943 // The variable will be bound by copy; make it const within the 944 // closure, but record that this was done in the expression. 945 bool constAdded = !exprType.isConstQualified(); 946 exprType.addConst(); 947 948 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 949 NameInfo.getLoc(), false, 950 constAdded); 951 } else { 952 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 953 NameInfo.getLoc(), true); 954 } 955 956 return S.Owned(BDRE); 957} 958 959ExprResult 960Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 961 SourceLocation Loc, 962 const CXXScopeSpec *SS) { 963 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 964 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 965} 966 967/// BuildDeclRefExpr - Build an expression that references a 968/// declaration that does not require a closure capture. 969ExprResult 970Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 971 const DeclarationNameInfo &NameInfo, 972 const CXXScopeSpec *SS) { 973 MarkDeclarationReferenced(NameInfo.getLoc(), D); 974 975 Expr *E = DeclRefExpr::Create(Context, 976 SS? SS->getWithLocInContext(Context) 977 : NestedNameSpecifierLoc(), 978 D, NameInfo, Ty, VK); 979 980 // Just in case we're building an illegal pointer-to-member. 981 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth()) 982 E->setObjectKind(OK_BitField); 983 984 return Owned(E); 985} 986 987static ExprResult 988BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 989 const CXXScopeSpec &SS, FieldDecl *Field, 990 DeclAccessPair FoundDecl, 991 const DeclarationNameInfo &MemberNameInfo); 992 993ExprResult 994Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 995 SourceLocation loc, 996 IndirectFieldDecl *indirectField, 997 Expr *baseObjectExpr, 998 SourceLocation opLoc) { 999 // First, build the expression that refers to the base object. 1000 1001 bool baseObjectIsPointer = false; 1002 Qualifiers baseQuals; 1003 1004 // Case 1: the base of the indirect field is not a field. 1005 VarDecl *baseVariable = indirectField->getVarDecl(); 1006 CXXScopeSpec EmptySS; 1007 if (baseVariable) { 1008 assert(baseVariable->getType()->isRecordType()); 1009 1010 // In principle we could have a member access expression that 1011 // accesses an anonymous struct/union that's a static member of 1012 // the base object's class. However, under the current standard, 1013 // static data members cannot be anonymous structs or unions. 1014 // Supporting this is as easy as building a MemberExpr here. 1015 assert(!baseObjectExpr && "anonymous struct/union is static data member?"); 1016 1017 DeclarationNameInfo baseNameInfo(DeclarationName(), loc); 1018 1019 ExprResult result = 1020 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); 1021 if (result.isInvalid()) return ExprError(); 1022 1023 baseObjectExpr = result.take(); 1024 baseObjectIsPointer = false; 1025 baseQuals = baseObjectExpr->getType().getQualifiers(); 1026 1027 // Case 2: the base of the indirect field is a field and the user 1028 // wrote a member expression. 1029 } else if (baseObjectExpr) { 1030 // The caller provided the base object expression. Determine 1031 // whether its a pointer and whether it adds any qualifiers to the 1032 // anonymous struct/union fields we're looking into. 1033 QualType objectType = baseObjectExpr->getType(); 1034 1035 if (const PointerType *ptr = objectType->getAs<PointerType>()) { 1036 baseObjectIsPointer = true; 1037 objectType = ptr->getPointeeType(); 1038 } else { 1039 baseObjectIsPointer = false; 1040 } 1041 baseQuals = objectType.getQualifiers(); 1042 1043 // Case 3: the base of the indirect field is a field and we should 1044 // build an implicit member access. 1045 } else { 1046 // We've found a member of an anonymous struct/union that is 1047 // inside a non-anonymous struct/union, so in a well-formed 1048 // program our base object expression is "this". 1049 CXXMethodDecl *method = tryCaptureCXXThis(); 1050 if (!method) { 1051 Diag(loc, diag::err_invalid_member_use_in_static_method) 1052 << indirectField->getDeclName(); 1053 return ExprError(); 1054 } 1055 1056 // Our base object expression is "this". 1057 baseObjectExpr = 1058 new (Context) CXXThisExpr(loc, method->getThisType(Context), 1059 /*isImplicit=*/ true); 1060 baseObjectIsPointer = true; 1061 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers()); 1062 } 1063 1064 // Build the implicit member references to the field of the 1065 // anonymous struct/union. 1066 Expr *result = baseObjectExpr; 1067 IndirectFieldDecl::chain_iterator 1068 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end(); 1069 1070 // Build the first member access in the chain with full information. 1071 if (!baseVariable) { 1072 FieldDecl *field = cast<FieldDecl>(*FI); 1073 1074 // FIXME: use the real found-decl info! 1075 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess()); 1076 1077 // Make a nameInfo that properly uses the anonymous name. 1078 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 1079 1080 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer, 1081 EmptySS, field, foundDecl, 1082 memberNameInfo).take(); 1083 baseObjectIsPointer = false; 1084 1085 // FIXME: check qualified member access 1086 } 1087 1088 // In all cases, we should now skip the first declaration in the chain. 1089 ++FI; 1090 1091 while (FI != FEnd) { 1092 FieldDecl *field = cast<FieldDecl>(*FI++); 1093 1094 // FIXME: these are somewhat meaningless 1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess()); 1097 1098 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false, 1099 (FI == FEnd? SS : EmptySS), field, 1100 foundDecl, memberNameInfo) 1101 .take(); 1102 } 1103 1104 return Owned(result); 1105} 1106 1107/// Decomposes the given name into a DeclarationNameInfo, its location, and 1108/// possibly a list of template arguments. 1109/// 1110/// If this produces template arguments, it is permitted to call 1111/// DecomposeTemplateName. 1112/// 1113/// This actually loses a lot of source location information for 1114/// non-standard name kinds; we should consider preserving that in 1115/// some way. 1116static void DecomposeUnqualifiedId(Sema &SemaRef, 1117 const UnqualifiedId &Id, 1118 TemplateArgumentListInfo &Buffer, 1119 DeclarationNameInfo &NameInfo, 1120 const TemplateArgumentListInfo *&TemplateArgs) { 1121 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1122 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1123 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1124 1125 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef, 1126 Id.TemplateId->getTemplateArgs(), 1127 Id.TemplateId->NumArgs); 1128 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer); 1129 TemplateArgsPtr.release(); 1130 1131 TemplateName TName = Id.TemplateId->Template.get(); 1132 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1133 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc); 1134 TemplateArgs = &Buffer; 1135 } else { 1136 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id); 1137 TemplateArgs = 0; 1138 } 1139} 1140 1141/// Determines if the given class is provably not derived from all of 1142/// the prospective base classes. 1143static bool IsProvablyNotDerivedFrom(Sema &SemaRef, 1144 CXXRecordDecl *Record, 1145 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) { 1146 if (Bases.count(Record->getCanonicalDecl())) 1147 return false; 1148 1149 RecordDecl *RD = Record->getDefinition(); 1150 if (!RD) return false; 1151 Record = cast<CXXRecordDecl>(RD); 1152 1153 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 1154 E = Record->bases_end(); I != E; ++I) { 1155 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 1156 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 1157 if (!BaseRT) return false; 1158 1159 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 1160 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases)) 1161 return false; 1162 } 1163 1164 return true; 1165} 1166 1167enum IMAKind { 1168 /// The reference is definitely not an instance member access. 1169 IMA_Static, 1170 1171 /// The reference may be an implicit instance member access. 1172 IMA_Mixed, 1173 1174 /// The reference may be to an instance member, but it is invalid if 1175 /// so, because the context is not an instance method. 1176 IMA_Mixed_StaticContext, 1177 1178 /// The reference may be to an instance member, but it is invalid if 1179 /// so, because the context is from an unrelated class. 1180 IMA_Mixed_Unrelated, 1181 1182 /// The reference is definitely an implicit instance member access. 1183 IMA_Instance, 1184 1185 /// The reference may be to an unresolved using declaration. 1186 IMA_Unresolved, 1187 1188 /// The reference may be to an unresolved using declaration and the 1189 /// context is not an instance method. 1190 IMA_Unresolved_StaticContext, 1191 1192 /// All possible referrents are instance members and the current 1193 /// context is not an instance method. 1194 IMA_Error_StaticContext, 1195 1196 /// All possible referrents are instance members of an unrelated 1197 /// class. 1198 IMA_Error_Unrelated 1199}; 1200 1201/// The given lookup names class member(s) and is not being used for 1202/// an address-of-member expression. Classify the type of access 1203/// according to whether it's possible that this reference names an 1204/// instance member. This is best-effort; it is okay to 1205/// conservatively answer "yes", in which case some errors will simply 1206/// not be caught until template-instantiation. 1207static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, 1208 const LookupResult &R) { 1209 assert(!R.empty() && (*R.begin())->isCXXClassMember()); 1210 1211 DeclContext *DC = SemaRef.getFunctionLevelDeclContext(); 1212 bool isStaticContext = 1213 (!isa<CXXMethodDecl>(DC) || 1214 cast<CXXMethodDecl>(DC)->isStatic()); 1215 1216 if (R.isUnresolvableResult()) 1217 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 1218 1219 // Collect all the declaring classes of instance members we find. 1220 bool hasNonInstance = false; 1221 bool hasField = false; 1222 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes; 1223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1224 NamedDecl *D = *I; 1225 1226 if (D->isCXXInstanceMember()) { 1227 if (dyn_cast<FieldDecl>(D)) 1228 hasField = true; 1229 1230 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 1231 Classes.insert(R->getCanonicalDecl()); 1232 } 1233 else 1234 hasNonInstance = true; 1235 } 1236 1237 // If we didn't find any instance members, it can't be an implicit 1238 // member reference. 1239 if (Classes.empty()) 1240 return IMA_Static; 1241 1242 // If the current context is not an instance method, it can't be 1243 // an implicit member reference. 1244 if (isStaticContext) { 1245 if (hasNonInstance) 1246 return IMA_Mixed_StaticContext; 1247 1248 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) { 1249 // C++0x [expr.prim.general]p10: 1250 // An id-expression that denotes a non-static data member or non-static 1251 // member function of a class can only be used: 1252 // (...) 1253 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand. 1254 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back(); 1255 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated; 1256 if (isUnevaluatedExpression) 1257 return IMA_Mixed_StaticContext; 1258 } 1259 1260 return IMA_Error_StaticContext; 1261 } 1262 1263 // If we can prove that the current context is unrelated to all the 1264 // declaring classes, it can't be an implicit member reference (in 1265 // which case it's an error if any of those members are selected). 1266 if (IsProvablyNotDerivedFrom(SemaRef, 1267 cast<CXXMethodDecl>(DC)->getParent(), 1268 Classes)) 1269 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated); 1270 1271 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 1272} 1273 1274/// Diagnose a reference to a field with no object available. 1275static void DiagnoseInstanceReference(Sema &SemaRef, 1276 const CXXScopeSpec &SS, 1277 NamedDecl *rep, 1278 const DeclarationNameInfo &nameInfo) { 1279 SourceLocation Loc = nameInfo.getLoc(); 1280 SourceRange Range(Loc); 1281 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 1282 1283 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) { 1284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) { 1285 if (MD->isStatic()) { 1286 // "invalid use of member 'x' in static member function" 1287 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 1288 << Range << nameInfo.getName(); 1289 return; 1290 } 1291 } 1292 1293 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 1294 << nameInfo.getName() << Range; 1295 return; 1296 } 1297 1298 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range; 1299} 1300 1301/// Diagnose an empty lookup. 1302/// 1303/// \return false if new lookup candidates were found 1304bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1305 CorrectTypoContext CTC) { 1306 DeclarationName Name = R.getLookupName(); 1307 1308 unsigned diagnostic = diag::err_undeclared_var_use; 1309 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1310 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1311 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1312 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1313 diagnostic = diag::err_undeclared_use; 1314 diagnostic_suggest = diag::err_undeclared_use_suggest; 1315 } 1316 1317 // If the original lookup was an unqualified lookup, fake an 1318 // unqualified lookup. This is useful when (for example) the 1319 // original lookup would not have found something because it was a 1320 // dependent name. 1321 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0; 1322 DC; DC = DC->getParent()) { 1323 if (isa<CXXRecordDecl>(DC)) { 1324 LookupQualifiedName(R, DC); 1325 1326 if (!R.empty()) { 1327 // Don't give errors about ambiguities in this lookup. 1328 R.suppressDiagnostics(); 1329 1330 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1331 bool isInstance = CurMethod && 1332 CurMethod->isInstance() && 1333 DC == CurMethod->getParent(); 1334 1335 // Give a code modification hint to insert 'this->'. 1336 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1337 // Actually quite difficult! 1338 if (isInstance) { 1339 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1340 CallsUndergoingInstantiation.back()->getCallee()); 1341 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 1342 CurMethod->getInstantiatedFromMemberFunction()); 1343 if (DepMethod) { 1344 Diag(R.getNameLoc(), diagnostic) << Name 1345 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1346 QualType DepThisType = DepMethod->getThisType(Context); 1347 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1348 R.getNameLoc(), DepThisType, false); 1349 TemplateArgumentListInfo TList; 1350 if (ULE->hasExplicitTemplateArgs()) 1351 ULE->copyTemplateArgumentsInto(TList); 1352 1353 CXXScopeSpec SS; 1354 SS.Adopt(ULE->getQualifierLoc()); 1355 CXXDependentScopeMemberExpr *DepExpr = 1356 CXXDependentScopeMemberExpr::Create( 1357 Context, DepThis, DepThisType, true, SourceLocation(), 1358 SS.getWithLocInContext(Context), NULL, 1359 R.getLookupNameInfo(), &TList); 1360 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1361 } else { 1362 // FIXME: we should be able to handle this case too. It is correct 1363 // to add this-> here. This is a workaround for PR7947. 1364 Diag(R.getNameLoc(), diagnostic) << Name; 1365 } 1366 } else { 1367 Diag(R.getNameLoc(), diagnostic) << Name; 1368 } 1369 1370 // Do we really want to note all of these? 1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1372 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1373 1374 // Tell the callee to try to recover. 1375 return false; 1376 } 1377 1378 R.clear(); 1379 } 1380 } 1381 1382 // We didn't find anything, so try to correct for a typo. 1383 DeclarationName Corrected; 1384 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) { 1385 if (!R.empty()) { 1386 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) { 1387 if (SS.isEmpty()) 1388 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName() 1389 << FixItHint::CreateReplacement(R.getNameLoc(), 1390 R.getLookupName().getAsString()); 1391 else 1392 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1393 << Name << computeDeclContext(SS, false) << R.getLookupName() 1394 << SS.getRange() 1395 << FixItHint::CreateReplacement(R.getNameLoc(), 1396 R.getLookupName().getAsString()); 1397 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 1398 Diag(ND->getLocation(), diag::note_previous_decl) 1399 << ND->getDeclName(); 1400 1401 // Tell the callee to try to recover. 1402 return false; 1403 } 1404 1405 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) { 1406 // FIXME: If we ended up with a typo for a type name or 1407 // Objective-C class name, we're in trouble because the parser 1408 // is in the wrong place to recover. Suggest the typo 1409 // correction, but don't make it a fix-it since we're not going 1410 // to recover well anyway. 1411 if (SS.isEmpty()) 1412 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName(); 1413 else 1414 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1415 << Name << computeDeclContext(SS, false) << R.getLookupName() 1416 << SS.getRange(); 1417 1418 // Don't try to recover; it won't work. 1419 return true; 1420 } 1421 } else { 1422 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1423 // because we aren't able to recover. 1424 if (SS.isEmpty()) 1425 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected; 1426 else 1427 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1428 << Name << computeDeclContext(SS, false) << Corrected 1429 << SS.getRange(); 1430 return true; 1431 } 1432 R.clear(); 1433 } 1434 1435 // Emit a special diagnostic for failed member lookups. 1436 // FIXME: computing the declaration context might fail here (?) 1437 if (!SS.isEmpty()) { 1438 Diag(R.getNameLoc(), diag::err_no_member) 1439 << Name << computeDeclContext(SS, false) 1440 << SS.getRange(); 1441 return true; 1442 } 1443 1444 // Give up, we can't recover. 1445 Diag(R.getNameLoc(), diagnostic) << Name; 1446 return true; 1447} 1448 1449ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) { 1450 ObjCMethodDecl *CurMeth = getCurMethodDecl(); 1451 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1452 if (!IDecl) 1453 return 0; 1454 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1455 if (!ClassImpDecl) 1456 return 0; 1457 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II); 1458 if (!property) 1459 return 0; 1460 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) 1461 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic || 1462 PIDecl->getPropertyIvarDecl()) 1463 return 0; 1464 return property; 1465} 1466 1467bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) { 1468 ObjCMethodDecl *CurMeth = getCurMethodDecl(); 1469 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1470 if (!IDecl) 1471 return false; 1472 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1473 if (!ClassImpDecl) 1474 return false; 1475 if (ObjCPropertyImplDecl *PIDecl 1476 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier())) 1477 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic || 1478 PIDecl->getPropertyIvarDecl()) 1479 return false; 1480 1481 return true; 1482} 1483 1484static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef, 1485 LookupResult &Lookup, 1486 IdentifierInfo *II, 1487 SourceLocation NameLoc) { 1488 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl(); 1489 bool LookForIvars; 1490 if (Lookup.empty()) 1491 LookForIvars = true; 1492 else if (CurMeth->isClassMethod()) 1493 LookForIvars = false; 1494 else 1495 LookForIvars = (Lookup.isSingleResult() && 1496 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() && 1497 (Lookup.getAsSingle<VarDecl>() != 0)); 1498 if (!LookForIvars) 1499 return 0; 1500 1501 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1502 if (!IDecl) 1503 return 0; 1504 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1505 if (!ClassImpDecl) 1506 return 0; 1507 bool DynamicImplSeen = false; 1508 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II); 1509 if (!property) 1510 return 0; 1511 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) { 1512 DynamicImplSeen = 1513 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 1514 // property implementation has a designated ivar. No need to assume a new 1515 // one. 1516 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl()) 1517 return 0; 1518 } 1519 if (!DynamicImplSeen) { 1520 QualType PropType = SemaRef.Context.getCanonicalType(property->getType()); 1521 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl, 1522 NameLoc, NameLoc, 1523 II, PropType, /*Dinfo=*/0, 1524 ObjCIvarDecl::Private, 1525 (Expr *)0, true); 1526 ClassImpDecl->addDecl(Ivar); 1527 IDecl->makeDeclVisibleInContext(Ivar, false); 1528 property->setPropertyIvarDecl(Ivar); 1529 return Ivar; 1530 } 1531 return 0; 1532} 1533 1534ExprResult Sema::ActOnIdExpression(Scope *S, 1535 CXXScopeSpec &SS, 1536 UnqualifiedId &Id, 1537 bool HasTrailingLParen, 1538 bool isAddressOfOperand) { 1539 assert(!(isAddressOfOperand && HasTrailingLParen) && 1540 "cannot be direct & operand and have a trailing lparen"); 1541 1542 if (SS.isInvalid()) 1543 return ExprError(); 1544 1545 TemplateArgumentListInfo TemplateArgsBuffer; 1546 1547 // Decompose the UnqualifiedId into the following data. 1548 DeclarationNameInfo NameInfo; 1549 const TemplateArgumentListInfo *TemplateArgs; 1550 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1551 1552 DeclarationName Name = NameInfo.getName(); 1553 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1554 SourceLocation NameLoc = NameInfo.getLoc(); 1555 1556 // C++ [temp.dep.expr]p3: 1557 // An id-expression is type-dependent if it contains: 1558 // -- an identifier that was declared with a dependent type, 1559 // (note: handled after lookup) 1560 // -- a template-id that is dependent, 1561 // (note: handled in BuildTemplateIdExpr) 1562 // -- a conversion-function-id that specifies a dependent type, 1563 // -- a nested-name-specifier that contains a class-name that 1564 // names a dependent type. 1565 // Determine whether this is a member of an unknown specialization; 1566 // we need to handle these differently. 1567 bool DependentID = false; 1568 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1569 Name.getCXXNameType()->isDependentType()) { 1570 DependentID = true; 1571 } else if (SS.isSet()) { 1572 if (DeclContext *DC = computeDeclContext(SS, false)) { 1573 if (RequireCompleteDeclContext(SS, DC)) 1574 return ExprError(); 1575 } else { 1576 DependentID = true; 1577 } 1578 } 1579 1580 if (DependentID) 1581 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1582 TemplateArgs); 1583 1584 bool IvarLookupFollowUp = false; 1585 // Perform the required lookup. 1586 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1587 if (TemplateArgs) { 1588 // Lookup the template name again to correctly establish the context in 1589 // which it was found. This is really unfortunate as we already did the 1590 // lookup to determine that it was a template name in the first place. If 1591 // this becomes a performance hit, we can work harder to preserve those 1592 // results until we get here but it's likely not worth it. 1593 bool MemberOfUnknownSpecialization; 1594 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1595 MemberOfUnknownSpecialization); 1596 1597 if (MemberOfUnknownSpecialization || 1598 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1599 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1600 TemplateArgs); 1601 } else { 1602 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1603 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1604 1605 // If the result might be in a dependent base class, this is a dependent 1606 // id-expression. 1607 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1608 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1609 TemplateArgs); 1610 1611 // If this reference is in an Objective-C method, then we need to do 1612 // some special Objective-C lookup, too. 1613 if (IvarLookupFollowUp) { 1614 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1615 if (E.isInvalid()) 1616 return ExprError(); 1617 1618 if (Expr *Ex = E.takeAs<Expr>()) 1619 return Owned(Ex); 1620 1621 // Synthesize ivars lazily. 1622 if (getLangOptions().ObjCDefaultSynthProperties && 1623 getLangOptions().ObjCNonFragileABI2) { 1624 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) { 1625 if (const ObjCPropertyDecl *Property = 1626 canSynthesizeProvisionalIvar(II)) { 1627 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II; 1628 Diag(Property->getLocation(), diag::note_property_declare); 1629 } 1630 return ActOnIdExpression(S, SS, Id, HasTrailingLParen, 1631 isAddressOfOperand); 1632 } 1633 } 1634 // for further use, this must be set to false if in class method. 1635 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod(); 1636 } 1637 } 1638 1639 if (R.isAmbiguous()) 1640 return ExprError(); 1641 1642 // Determine whether this name might be a candidate for 1643 // argument-dependent lookup. 1644 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1645 1646 if (R.empty() && !ADL) { 1647 // Otherwise, this could be an implicitly declared function reference (legal 1648 // in C90, extension in C99, forbidden in C++). 1649 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1650 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1651 if (D) R.addDecl(D); 1652 } 1653 1654 // If this name wasn't predeclared and if this is not a function 1655 // call, diagnose the problem. 1656 if (R.empty()) { 1657 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown)) 1658 return ExprError(); 1659 1660 assert(!R.empty() && 1661 "DiagnoseEmptyLookup returned false but added no results"); 1662 1663 // If we found an Objective-C instance variable, let 1664 // LookupInObjCMethod build the appropriate expression to 1665 // reference the ivar. 1666 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1667 R.clear(); 1668 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1669 assert(E.isInvalid() || E.get()); 1670 return move(E); 1671 } 1672 } 1673 } 1674 1675 // This is guaranteed from this point on. 1676 assert(!R.empty() || ADL); 1677 1678 // Check whether this might be a C++ implicit instance member access. 1679 // C++ [class.mfct.non-static]p3: 1680 // When an id-expression that is not part of a class member access 1681 // syntax and not used to form a pointer to member is used in the 1682 // body of a non-static member function of class X, if name lookup 1683 // resolves the name in the id-expression to a non-static non-type 1684 // member of some class C, the id-expression is transformed into a 1685 // class member access expression using (*this) as the 1686 // postfix-expression to the left of the . operator. 1687 // 1688 // But we don't actually need to do this for '&' operands if R 1689 // resolved to a function or overloaded function set, because the 1690 // expression is ill-formed if it actually works out to be a 1691 // non-static member function: 1692 // 1693 // C++ [expr.ref]p4: 1694 // Otherwise, if E1.E2 refers to a non-static member function. . . 1695 // [t]he expression can be used only as the left-hand operand of a 1696 // member function call. 1697 // 1698 // There are other safeguards against such uses, but it's important 1699 // to get this right here so that we don't end up making a 1700 // spuriously dependent expression if we're inside a dependent 1701 // instance method. 1702 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1703 bool MightBeImplicitMember; 1704 if (!isAddressOfOperand) 1705 MightBeImplicitMember = true; 1706 else if (!SS.isEmpty()) 1707 MightBeImplicitMember = false; 1708 else if (R.isOverloadedResult()) 1709 MightBeImplicitMember = false; 1710 else if (R.isUnresolvableResult()) 1711 MightBeImplicitMember = true; 1712 else 1713 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1714 isa<IndirectFieldDecl>(R.getFoundDecl()); 1715 1716 if (MightBeImplicitMember) 1717 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1718 } 1719 1720 if (TemplateArgs) 1721 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1722 1723 return BuildDeclarationNameExpr(SS, R, ADL); 1724} 1725 1726/// Builds an expression which might be an implicit member expression. 1727ExprResult 1728Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 1729 LookupResult &R, 1730 const TemplateArgumentListInfo *TemplateArgs) { 1731 switch (ClassifyImplicitMemberAccess(*this, R)) { 1732 case IMA_Instance: 1733 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true); 1734 1735 case IMA_Mixed: 1736 case IMA_Mixed_Unrelated: 1737 case IMA_Unresolved: 1738 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false); 1739 1740 case IMA_Static: 1741 case IMA_Mixed_StaticContext: 1742 case IMA_Unresolved_StaticContext: 1743 if (TemplateArgs) 1744 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs); 1745 return BuildDeclarationNameExpr(SS, R, false); 1746 1747 case IMA_Error_StaticContext: 1748 case IMA_Error_Unrelated: 1749 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(), 1750 R.getLookupNameInfo()); 1751 return ExprError(); 1752 } 1753 1754 llvm_unreachable("unexpected instance member access kind"); 1755 return ExprError(); 1756} 1757 1758/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1759/// declaration name, generally during template instantiation. 1760/// There's a large number of things which don't need to be done along 1761/// this path. 1762ExprResult 1763Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1764 const DeclarationNameInfo &NameInfo) { 1765 DeclContext *DC; 1766 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1767 return BuildDependentDeclRefExpr(SS, NameInfo, 0); 1768 1769 if (RequireCompleteDeclContext(SS, DC)) 1770 return ExprError(); 1771 1772 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1773 LookupQualifiedName(R, DC); 1774 1775 if (R.isAmbiguous()) 1776 return ExprError(); 1777 1778 if (R.empty()) { 1779 Diag(NameInfo.getLoc(), diag::err_no_member) 1780 << NameInfo.getName() << DC << SS.getRange(); 1781 return ExprError(); 1782 } 1783 1784 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1785} 1786 1787/// LookupInObjCMethod - The parser has read a name in, and Sema has 1788/// detected that we're currently inside an ObjC method. Perform some 1789/// additional lookup. 1790/// 1791/// Ideally, most of this would be done by lookup, but there's 1792/// actually quite a lot of extra work involved. 1793/// 1794/// Returns a null sentinel to indicate trivial success. 1795ExprResult 1796Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1797 IdentifierInfo *II, bool AllowBuiltinCreation) { 1798 SourceLocation Loc = Lookup.getNameLoc(); 1799 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1800 1801 // There are two cases to handle here. 1) scoped lookup could have failed, 1802 // in which case we should look for an ivar. 2) scoped lookup could have 1803 // found a decl, but that decl is outside the current instance method (i.e. 1804 // a global variable). In these two cases, we do a lookup for an ivar with 1805 // this name, if the lookup sucedes, we replace it our current decl. 1806 1807 // If we're in a class method, we don't normally want to look for 1808 // ivars. But if we don't find anything else, and there's an 1809 // ivar, that's an error. 1810 bool IsClassMethod = CurMethod->isClassMethod(); 1811 1812 bool LookForIvars; 1813 if (Lookup.empty()) 1814 LookForIvars = true; 1815 else if (IsClassMethod) 1816 LookForIvars = false; 1817 else 1818 LookForIvars = (Lookup.isSingleResult() && 1819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1820 ObjCInterfaceDecl *IFace = 0; 1821 if (LookForIvars) { 1822 IFace = CurMethod->getClassInterface(); 1823 ObjCInterfaceDecl *ClassDeclared; 1824 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1825 // Diagnose using an ivar in a class method. 1826 if (IsClassMethod) 1827 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1828 << IV->getDeclName()); 1829 1830 // If we're referencing an invalid decl, just return this as a silent 1831 // error node. The error diagnostic was already emitted on the decl. 1832 if (IV->isInvalidDecl()) 1833 return ExprError(); 1834 1835 // Check if referencing a field with __attribute__((deprecated)). 1836 if (DiagnoseUseOfDecl(IV, Loc)) 1837 return ExprError(); 1838 1839 // Diagnose the use of an ivar outside of the declaring class. 1840 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1841 ClassDeclared != IFace) 1842 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1843 1844 // FIXME: This should use a new expr for a direct reference, don't 1845 // turn this into Self->ivar, just return a BareIVarExpr or something. 1846 IdentifierInfo &II = Context.Idents.get("self"); 1847 UnqualifiedId SelfName; 1848 SelfName.setIdentifier(&II, SourceLocation()); 1849 CXXScopeSpec SelfScopeSpec; 1850 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1851 SelfName, false, false); 1852 if (SelfExpr.isInvalid()) 1853 return ExprError(); 1854 1855 Expr *SelfE = SelfExpr.take(); 1856 DefaultLvalueConversion(SelfE); 1857 1858 MarkDeclarationReferenced(Loc, IV); 1859 return Owned(new (Context) 1860 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1861 SelfE, true, true)); 1862 } 1863 } else if (CurMethod->isInstanceMethod()) { 1864 // We should warn if a local variable hides an ivar. 1865 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 1866 ObjCInterfaceDecl *ClassDeclared; 1867 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1868 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1869 IFace == ClassDeclared) 1870 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1871 } 1872 } 1873 1874 if (Lookup.empty() && II && AllowBuiltinCreation) { 1875 // FIXME. Consolidate this with similar code in LookupName. 1876 if (unsigned BuiltinID = II->getBuiltinID()) { 1877 if (!(getLangOptions().CPlusPlus && 1878 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1879 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1880 S, Lookup.isForRedeclaration(), 1881 Lookup.getNameLoc()); 1882 if (D) Lookup.addDecl(D); 1883 } 1884 } 1885 } 1886 // Sentinel value saying that we didn't do anything special. 1887 return Owned((Expr*) 0); 1888} 1889 1890/// \brief Cast a base object to a member's actual type. 1891/// 1892/// Logically this happens in three phases: 1893/// 1894/// * First we cast from the base type to the naming class. 1895/// The naming class is the class into which we were looking 1896/// when we found the member; it's the qualifier type if a 1897/// qualifier was provided, and otherwise it's the base type. 1898/// 1899/// * Next we cast from the naming class to the declaring class. 1900/// If the member we found was brought into a class's scope by 1901/// a using declaration, this is that class; otherwise it's 1902/// the class declaring the member. 1903/// 1904/// * Finally we cast from the declaring class to the "true" 1905/// declaring class of the member. This conversion does not 1906/// obey access control. 1907bool 1908Sema::PerformObjectMemberConversion(Expr *&From, 1909 NestedNameSpecifier *Qualifier, 1910 NamedDecl *FoundDecl, 1911 NamedDecl *Member) { 1912 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1913 if (!RD) 1914 return false; 1915 1916 QualType DestRecordType; 1917 QualType DestType; 1918 QualType FromRecordType; 1919 QualType FromType = From->getType(); 1920 bool PointerConversions = false; 1921 if (isa<FieldDecl>(Member)) { 1922 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1923 1924 if (FromType->getAs<PointerType>()) { 1925 DestType = Context.getPointerType(DestRecordType); 1926 FromRecordType = FromType->getPointeeType(); 1927 PointerConversions = true; 1928 } else { 1929 DestType = DestRecordType; 1930 FromRecordType = FromType; 1931 } 1932 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1933 if (Method->isStatic()) 1934 return false; 1935 1936 DestType = Method->getThisType(Context); 1937 DestRecordType = DestType->getPointeeType(); 1938 1939 if (FromType->getAs<PointerType>()) { 1940 FromRecordType = FromType->getPointeeType(); 1941 PointerConversions = true; 1942 } else { 1943 FromRecordType = FromType; 1944 DestType = DestRecordType; 1945 } 1946 } else { 1947 // No conversion necessary. 1948 return false; 1949 } 1950 1951 if (DestType->isDependentType() || FromType->isDependentType()) 1952 return false; 1953 1954 // If the unqualified types are the same, no conversion is necessary. 1955 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1956 return false; 1957 1958 SourceRange FromRange = From->getSourceRange(); 1959 SourceLocation FromLoc = FromRange.getBegin(); 1960 1961 ExprValueKind VK = CastCategory(From); 1962 1963 // C++ [class.member.lookup]p8: 1964 // [...] Ambiguities can often be resolved by qualifying a name with its 1965 // class name. 1966 // 1967 // If the member was a qualified name and the qualified referred to a 1968 // specific base subobject type, we'll cast to that intermediate type 1969 // first and then to the object in which the member is declared. That allows 1970 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1971 // 1972 // class Base { public: int x; }; 1973 // class Derived1 : public Base { }; 1974 // class Derived2 : public Base { }; 1975 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1976 // 1977 // void VeryDerived::f() { 1978 // x = 17; // error: ambiguous base subobjects 1979 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1980 // } 1981 if (Qualifier) { 1982 QualType QType = QualType(Qualifier->getAsType(), 0); 1983 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 1984 assert(QType->isRecordType() && "lookup done with non-record type"); 1985 1986 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 1987 1988 // In C++98, the qualifier type doesn't actually have to be a base 1989 // type of the object type, in which case we just ignore it. 1990 // Otherwise build the appropriate casts. 1991 if (IsDerivedFrom(FromRecordType, QRecordType)) { 1992 CXXCastPath BasePath; 1993 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 1994 FromLoc, FromRange, &BasePath)) 1995 return true; 1996 1997 if (PointerConversions) 1998 QType = Context.getPointerType(QType); 1999 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2000 VK, &BasePath); 2001 2002 FromType = QType; 2003 FromRecordType = QRecordType; 2004 2005 // If the qualifier type was the same as the destination type, 2006 // we're done. 2007 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2008 return false; 2009 } 2010 } 2011 2012 bool IgnoreAccess = false; 2013 2014 // If we actually found the member through a using declaration, cast 2015 // down to the using declaration's type. 2016 // 2017 // Pointer equality is fine here because only one declaration of a 2018 // class ever has member declarations. 2019 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2020 assert(isa<UsingShadowDecl>(FoundDecl)); 2021 QualType URecordType = Context.getTypeDeclType( 2022 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2023 2024 // We only need to do this if the naming-class to declaring-class 2025 // conversion is non-trivial. 2026 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2027 assert(IsDerivedFrom(FromRecordType, URecordType)); 2028 CXXCastPath BasePath; 2029 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2030 FromLoc, FromRange, &BasePath)) 2031 return true; 2032 2033 QualType UType = URecordType; 2034 if (PointerConversions) 2035 UType = Context.getPointerType(UType); 2036 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2037 VK, &BasePath); 2038 FromType = UType; 2039 FromRecordType = URecordType; 2040 } 2041 2042 // We don't do access control for the conversion from the 2043 // declaring class to the true declaring class. 2044 IgnoreAccess = true; 2045 } 2046 2047 CXXCastPath BasePath; 2048 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2049 FromLoc, FromRange, &BasePath, 2050 IgnoreAccess)) 2051 return true; 2052 2053 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2054 VK, &BasePath); 2055 return false; 2056} 2057 2058/// \brief Build a MemberExpr AST node. 2059static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 2060 const CXXScopeSpec &SS, ValueDecl *Member, 2061 DeclAccessPair FoundDecl, 2062 const DeclarationNameInfo &MemberNameInfo, 2063 QualType Ty, 2064 ExprValueKind VK, ExprObjectKind OK, 2065 const TemplateArgumentListInfo *TemplateArgs = 0) { 2066 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C), 2067 Member, FoundDecl, MemberNameInfo, 2068 TemplateArgs, Ty, VK, OK); 2069} 2070 2071static ExprResult 2072BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 2073 const CXXScopeSpec &SS, FieldDecl *Field, 2074 DeclAccessPair FoundDecl, 2075 const DeclarationNameInfo &MemberNameInfo) { 2076 // x.a is an l-value if 'a' has a reference type. Otherwise: 2077 // x.a is an l-value/x-value/pr-value if the base is (and note 2078 // that *x is always an l-value), except that if the base isn't 2079 // an ordinary object then we must have an rvalue. 2080 ExprValueKind VK = VK_LValue; 2081 ExprObjectKind OK = OK_Ordinary; 2082 if (!IsArrow) { 2083 if (BaseExpr->getObjectKind() == OK_Ordinary) 2084 VK = BaseExpr->getValueKind(); 2085 else 2086 VK = VK_RValue; 2087 } 2088 if (VK != VK_RValue && Field->isBitField()) 2089 OK = OK_BitField; 2090 2091 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2092 QualType MemberType = Field->getType(); 2093 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { 2094 MemberType = Ref->getPointeeType(); 2095 VK = VK_LValue; 2096 } else { 2097 QualType BaseType = BaseExpr->getType(); 2098 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 2099 2100 Qualifiers BaseQuals = BaseType.getQualifiers(); 2101 2102 // GC attributes are never picked up by members. 2103 BaseQuals.removeObjCGCAttr(); 2104 2105 // CVR attributes from the base are picked up by members, 2106 // except that 'mutable' members don't pick up 'const'. 2107 if (Field->isMutable()) BaseQuals.removeConst(); 2108 2109 Qualifiers MemberQuals 2110 = S.Context.getCanonicalType(MemberType).getQualifiers(); 2111 2112 // TR 18037 does not allow fields to be declared with address spaces. 2113 assert(!MemberQuals.hasAddressSpace()); 2114 2115 Qualifiers Combined = BaseQuals + MemberQuals; 2116 if (Combined != MemberQuals) 2117 MemberType = S.Context.getQualifiedType(MemberType, Combined); 2118 } 2119 2120 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field); 2121 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(), 2122 FoundDecl, Field)) 2123 return ExprError(); 2124 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS, 2125 Field, FoundDecl, MemberNameInfo, 2126 MemberType, VK, OK)); 2127} 2128 2129/// Builds an implicit member access expression. The current context 2130/// is known to be an instance method, and the given unqualified lookup 2131/// set is known to contain only instance members, at least one of which 2132/// is from an appropriate type. 2133ExprResult 2134Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2135 LookupResult &R, 2136 const TemplateArgumentListInfo *TemplateArgs, 2137 bool IsKnownInstance) { 2138 assert(!R.empty() && !R.isAmbiguous()); 2139 2140 SourceLocation loc = R.getNameLoc(); 2141 2142 // We may have found a field within an anonymous union or struct 2143 // (C++ [class.union]). 2144 // FIXME: template-ids inside anonymous structs? 2145 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>()) 2146 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD); 2147 2148 // If this is known to be an instance access, go ahead and build an 2149 // implicit 'this' expression now. 2150 // 'this' expression now. 2151 CXXMethodDecl *method = tryCaptureCXXThis(); 2152 assert(method && "didn't correctly pre-flight capture of 'this'"); 2153 2154 QualType thisType = method->getThisType(Context); 2155 Expr *baseExpr = 0; // null signifies implicit access 2156 if (IsKnownInstance) { 2157 SourceLocation Loc = R.getNameLoc(); 2158 if (SS.getRange().isValid()) 2159 Loc = SS.getRange().getBegin(); 2160 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true); 2161 } 2162 2163 return BuildMemberReferenceExpr(baseExpr, thisType, 2164 /*OpLoc*/ SourceLocation(), 2165 /*IsArrow*/ true, 2166 SS, 2167 /*FirstQualifierInScope*/ 0, 2168 R, TemplateArgs); 2169} 2170 2171bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2172 const LookupResult &R, 2173 bool HasTrailingLParen) { 2174 // Only when used directly as the postfix-expression of a call. 2175 if (!HasTrailingLParen) 2176 return false; 2177 2178 // Never if a scope specifier was provided. 2179 if (SS.isSet()) 2180 return false; 2181 2182 // Only in C++ or ObjC++. 2183 if (!getLangOptions().CPlusPlus) 2184 return false; 2185 2186 // Turn off ADL when we find certain kinds of declarations during 2187 // normal lookup: 2188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2189 NamedDecl *D = *I; 2190 2191 // C++0x [basic.lookup.argdep]p3: 2192 // -- a declaration of a class member 2193 // Since using decls preserve this property, we check this on the 2194 // original decl. 2195 if (D->isCXXClassMember()) 2196 return false; 2197 2198 // C++0x [basic.lookup.argdep]p3: 2199 // -- a block-scope function declaration that is not a 2200 // using-declaration 2201 // NOTE: we also trigger this for function templates (in fact, we 2202 // don't check the decl type at all, since all other decl types 2203 // turn off ADL anyway). 2204 if (isa<UsingShadowDecl>(D)) 2205 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2206 else if (D->getDeclContext()->isFunctionOrMethod()) 2207 return false; 2208 2209 // C++0x [basic.lookup.argdep]p3: 2210 // -- a declaration that is neither a function or a function 2211 // template 2212 // And also for builtin functions. 2213 if (isa<FunctionDecl>(D)) { 2214 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2215 2216 // But also builtin functions. 2217 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2218 return false; 2219 } else if (!isa<FunctionTemplateDecl>(D)) 2220 return false; 2221 } 2222 2223 return true; 2224} 2225 2226 2227/// Diagnoses obvious problems with the use of the given declaration 2228/// as an expression. This is only actually called for lookups that 2229/// were not overloaded, and it doesn't promise that the declaration 2230/// will in fact be used. 2231static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2232 if (isa<TypedefDecl>(D)) { 2233 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2234 return true; 2235 } 2236 2237 if (isa<ObjCInterfaceDecl>(D)) { 2238 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2239 return true; 2240 } 2241 2242 if (isa<NamespaceDecl>(D)) { 2243 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2244 return true; 2245 } 2246 2247 return false; 2248} 2249 2250ExprResult 2251Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2252 LookupResult &R, 2253 bool NeedsADL) { 2254 // If this is a single, fully-resolved result and we don't need ADL, 2255 // just build an ordinary singleton decl ref. 2256 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2257 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2258 R.getFoundDecl()); 2259 2260 // We only need to check the declaration if there's exactly one 2261 // result, because in the overloaded case the results can only be 2262 // functions and function templates. 2263 if (R.isSingleResult() && 2264 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2265 return ExprError(); 2266 2267 // Otherwise, just build an unresolved lookup expression. Suppress 2268 // any lookup-related diagnostics; we'll hash these out later, when 2269 // we've picked a target. 2270 R.suppressDiagnostics(); 2271 2272 UnresolvedLookupExpr *ULE 2273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2274 SS.getWithLocInContext(Context), 2275 R.getLookupNameInfo(), 2276 NeedsADL, R.isOverloadedResult(), 2277 R.begin(), R.end()); 2278 2279 return Owned(ULE); 2280} 2281 2282/// \brief Complete semantic analysis for a reference to the given declaration. 2283ExprResult 2284Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2285 const DeclarationNameInfo &NameInfo, 2286 NamedDecl *D) { 2287 assert(D && "Cannot refer to a NULL declaration"); 2288 assert(!isa<FunctionTemplateDecl>(D) && 2289 "Cannot refer unambiguously to a function template"); 2290 2291 SourceLocation Loc = NameInfo.getLoc(); 2292 if (CheckDeclInExpr(*this, Loc, D)) 2293 return ExprError(); 2294 2295 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2296 // Specifically diagnose references to class templates that are missing 2297 // a template argument list. 2298 Diag(Loc, diag::err_template_decl_ref) 2299 << Template << SS.getRange(); 2300 Diag(Template->getLocation(), diag::note_template_decl_here); 2301 return ExprError(); 2302 } 2303 2304 // Make sure that we're referring to a value. 2305 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2306 if (!VD) { 2307 Diag(Loc, diag::err_ref_non_value) 2308 << D << SS.getRange(); 2309 Diag(D->getLocation(), diag::note_declared_at); 2310 return ExprError(); 2311 } 2312 2313 // Check whether this declaration can be used. Note that we suppress 2314 // this check when we're going to perform argument-dependent lookup 2315 // on this function name, because this might not be the function 2316 // that overload resolution actually selects. 2317 if (DiagnoseUseOfDecl(VD, Loc)) 2318 return ExprError(); 2319 2320 // Only create DeclRefExpr's for valid Decl's. 2321 if (VD->isInvalidDecl()) 2322 return ExprError(); 2323 2324 // Handle members of anonymous structs and unions. If we got here, 2325 // and the reference is to a class member indirect field, then this 2326 // must be the subject of a pointer-to-member expression. 2327 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2328 if (!indirectField->isCXXClassMember()) 2329 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2330 indirectField); 2331 2332 // If the identifier reference is inside a block, and it refers to a value 2333 // that is outside the block, create a BlockDeclRefExpr instead of a 2334 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 2335 // the block is formed. 2336 // 2337 // We do not do this for things like enum constants, global variables, etc, 2338 // as they do not get snapshotted. 2339 // 2340 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) { 2341 case CR_Error: 2342 return ExprError(); 2343 2344 case CR_Capture: 2345 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2346 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false); 2347 2348 case CR_CaptureByRef: 2349 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2350 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true); 2351 2352 case CR_NoCapture: { 2353 // If this reference is not in a block or if the referenced 2354 // variable is within the block, create a normal DeclRefExpr. 2355 2356 QualType type = VD->getType(); 2357 ExprValueKind valueKind = VK_RValue; 2358 2359 switch (D->getKind()) { 2360 // Ignore all the non-ValueDecl kinds. 2361#define ABSTRACT_DECL(kind) 2362#define VALUE(type, base) 2363#define DECL(type, base) \ 2364 case Decl::type: 2365#include "clang/AST/DeclNodes.inc" 2366 llvm_unreachable("invalid value decl kind"); 2367 return ExprError(); 2368 2369 // These shouldn't make it here. 2370 case Decl::ObjCAtDefsField: 2371 case Decl::ObjCIvar: 2372 llvm_unreachable("forming non-member reference to ivar?"); 2373 return ExprError(); 2374 2375 // Enum constants are always r-values and never references. 2376 // Unresolved using declarations are dependent. 2377 case Decl::EnumConstant: 2378 case Decl::UnresolvedUsingValue: 2379 valueKind = VK_RValue; 2380 break; 2381 2382 // Fields and indirect fields that got here must be for 2383 // pointer-to-member expressions; we just call them l-values for 2384 // internal consistency, because this subexpression doesn't really 2385 // exist in the high-level semantics. 2386 case Decl::Field: 2387 case Decl::IndirectField: 2388 assert(getLangOptions().CPlusPlus && 2389 "building reference to field in C?"); 2390 2391 // These can't have reference type in well-formed programs, but 2392 // for internal consistency we do this anyway. 2393 type = type.getNonReferenceType(); 2394 valueKind = VK_LValue; 2395 break; 2396 2397 // Non-type template parameters are either l-values or r-values 2398 // depending on the type. 2399 case Decl::NonTypeTemplateParm: { 2400 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2401 type = reftype->getPointeeType(); 2402 valueKind = VK_LValue; // even if the parameter is an r-value reference 2403 break; 2404 } 2405 2406 // For non-references, we need to strip qualifiers just in case 2407 // the template parameter was declared as 'const int' or whatever. 2408 valueKind = VK_RValue; 2409 type = type.getUnqualifiedType(); 2410 break; 2411 } 2412 2413 case Decl::Var: 2414 // In C, "extern void blah;" is valid and is an r-value. 2415 if (!getLangOptions().CPlusPlus && 2416 !type.hasQualifiers() && 2417 type->isVoidType()) { 2418 valueKind = VK_RValue; 2419 break; 2420 } 2421 // fallthrough 2422 2423 case Decl::ImplicitParam: 2424 case Decl::ParmVar: 2425 // These are always l-values. 2426 valueKind = VK_LValue; 2427 type = type.getNonReferenceType(); 2428 break; 2429 2430 case Decl::Function: { 2431 // Functions are l-values in C++. 2432 if (getLangOptions().CPlusPlus) { 2433 valueKind = VK_LValue; 2434 break; 2435 } 2436 2437 // C99 DR 316 says that, if a function type comes from a 2438 // function definition (without a prototype), that type is only 2439 // used for checking compatibility. Therefore, when referencing 2440 // the function, we pretend that we don't have the full function 2441 // type. 2442 if (!cast<FunctionDecl>(VD)->hasPrototype()) 2443 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>()) 2444 type = Context.getFunctionNoProtoType(proto->getResultType(), 2445 proto->getExtInfo()); 2446 2447 // Functions are r-values in C. 2448 valueKind = VK_RValue; 2449 break; 2450 } 2451 2452 case Decl::CXXMethod: 2453 // C++ methods are l-values if static, r-values if non-static. 2454 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2455 valueKind = VK_LValue; 2456 break; 2457 } 2458 // fallthrough 2459 2460 case Decl::CXXConversion: 2461 case Decl::CXXDestructor: 2462 case Decl::CXXConstructor: 2463 valueKind = VK_RValue; 2464 break; 2465 } 2466 2467 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2468 } 2469 2470 } 2471 2472 llvm_unreachable("unknown capture result"); 2473 return ExprError(); 2474} 2475 2476ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 2477 tok::TokenKind Kind) { 2478 PredefinedExpr::IdentType IT; 2479 2480 switch (Kind) { 2481 default: assert(0 && "Unknown simple primary expr!"); 2482 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2483 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2484 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2485 } 2486 2487 // Pre-defined identifiers are of type char[x], where x is the length of the 2488 // string. 2489 2490 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2491 if (!currentDecl && getCurBlock()) 2492 currentDecl = getCurBlock()->TheDecl; 2493 if (!currentDecl) { 2494 Diag(Loc, diag::ext_predef_outside_function); 2495 currentDecl = Context.getTranslationUnitDecl(); 2496 } 2497 2498 QualType ResTy; 2499 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2500 ResTy = Context.DependentTy; 2501 } else { 2502 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2503 2504 llvm::APInt LengthI(32, Length + 1); 2505 ResTy = Context.CharTy.withConst(); 2506 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2507 } 2508 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2509} 2510 2511ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 2512 llvm::SmallString<16> CharBuffer; 2513 bool Invalid = false; 2514 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2515 if (Invalid) 2516 return ExprError(); 2517 2518 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2519 PP); 2520 if (Literal.hadError()) 2521 return ExprError(); 2522 2523 QualType Ty; 2524 if (!getLangOptions().CPlusPlus) 2525 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 2526 else if (Literal.isWide()) 2527 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 2528 else if (Literal.isMultiChar()) 2529 Ty = Context.IntTy; // 'wxyz' -> int in C++. 2530 else 2531 Ty = Context.CharTy; // 'x' -> char in C++ 2532 2533 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 2534 Literal.isWide(), 2535 Ty, Tok.getLocation())); 2536} 2537 2538ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 2539 // Fast path for a single digit (which is quite common). A single digit 2540 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 2541 if (Tok.getLength() == 1) { 2542 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2543 unsigned IntSize = Context.Target.getIntWidth(); 2544 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'), 2545 Context.IntTy, Tok.getLocation())); 2546 } 2547 2548 llvm::SmallString<512> IntegerBuffer; 2549 // Add padding so that NumericLiteralParser can overread by one character. 2550 IntegerBuffer.resize(Tok.getLength()+1); 2551 const char *ThisTokBegin = &IntegerBuffer[0]; 2552 2553 // Get the spelling of the token, which eliminates trigraphs, etc. 2554 bool Invalid = false; 2555 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2556 if (Invalid) 2557 return ExprError(); 2558 2559 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2560 Tok.getLocation(), PP); 2561 if (Literal.hadError) 2562 return ExprError(); 2563 2564 Expr *Res; 2565 2566 if (Literal.isFloatingLiteral()) { 2567 QualType Ty; 2568 if (Literal.isFloat) 2569 Ty = Context.FloatTy; 2570 else if (!Literal.isLong) 2571 Ty = Context.DoubleTy; 2572 else 2573 Ty = Context.LongDoubleTy; 2574 2575 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 2576 2577 using llvm::APFloat; 2578 APFloat Val(Format); 2579 2580 APFloat::opStatus result = Literal.GetFloatValue(Val); 2581 2582 // Overflow is always an error, but underflow is only an error if 2583 // we underflowed to zero (APFloat reports denormals as underflow). 2584 if ((result & APFloat::opOverflow) || 2585 ((result & APFloat::opUnderflow) && Val.isZero())) { 2586 unsigned diagnostic; 2587 llvm::SmallString<20> buffer; 2588 if (result & APFloat::opOverflow) { 2589 diagnostic = diag::warn_float_overflow; 2590 APFloat::getLargest(Format).toString(buffer); 2591 } else { 2592 diagnostic = diag::warn_float_underflow; 2593 APFloat::getSmallest(Format).toString(buffer); 2594 } 2595 2596 Diag(Tok.getLocation(), diagnostic) 2597 << Ty 2598 << llvm::StringRef(buffer.data(), buffer.size()); 2599 } 2600 2601 bool isExact = (result == APFloat::opOK); 2602 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation()); 2603 2604 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy) 2605 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast); 2606 2607 } else if (!Literal.isIntegerLiteral()) { 2608 return ExprError(); 2609 } else { 2610 QualType Ty; 2611 2612 // long long is a C99 feature. 2613 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 2614 Literal.isLongLong) 2615 Diag(Tok.getLocation(), diag::ext_longlong); 2616 2617 // Get the value in the widest-possible width. 2618 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 2619 2620 if (Literal.GetIntegerValue(ResultVal)) { 2621 // If this value didn't fit into uintmax_t, warn and force to ull. 2622 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2623 Ty = Context.UnsignedLongLongTy; 2624 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2625 "long long is not intmax_t?"); 2626 } else { 2627 // If this value fits into a ULL, try to figure out what else it fits into 2628 // according to the rules of C99 6.4.4.1p5. 2629 2630 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2631 // be an unsigned int. 2632 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2633 2634 // Check from smallest to largest, picking the smallest type we can. 2635 unsigned Width = 0; 2636 if (!Literal.isLong && !Literal.isLongLong) { 2637 // Are int/unsigned possibilities? 2638 unsigned IntSize = Context.Target.getIntWidth(); 2639 2640 // Does it fit in a unsigned int? 2641 if (ResultVal.isIntN(IntSize)) { 2642 // Does it fit in a signed int? 2643 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2644 Ty = Context.IntTy; 2645 else if (AllowUnsigned) 2646 Ty = Context.UnsignedIntTy; 2647 Width = IntSize; 2648 } 2649 } 2650 2651 // Are long/unsigned long possibilities? 2652 if (Ty.isNull() && !Literal.isLongLong) { 2653 unsigned LongSize = Context.Target.getLongWidth(); 2654 2655 // Does it fit in a unsigned long? 2656 if (ResultVal.isIntN(LongSize)) { 2657 // Does it fit in a signed long? 2658 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2659 Ty = Context.LongTy; 2660 else if (AllowUnsigned) 2661 Ty = Context.UnsignedLongTy; 2662 Width = LongSize; 2663 } 2664 } 2665 2666 // Finally, check long long if needed. 2667 if (Ty.isNull()) { 2668 unsigned LongLongSize = Context.Target.getLongLongWidth(); 2669 2670 // Does it fit in a unsigned long long? 2671 if (ResultVal.isIntN(LongLongSize)) { 2672 // Does it fit in a signed long long? 2673 // To be compatible with MSVC, hex integer literals ending with the 2674 // LL or i64 suffix are always signed in Microsoft mode. 2675 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2676 (getLangOptions().Microsoft && Literal.isLongLong))) 2677 Ty = Context.LongLongTy; 2678 else if (AllowUnsigned) 2679 Ty = Context.UnsignedLongLongTy; 2680 Width = LongLongSize; 2681 } 2682 } 2683 2684 // If we still couldn't decide a type, we probably have something that 2685 // does not fit in a signed long long, but has no U suffix. 2686 if (Ty.isNull()) { 2687 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2688 Ty = Context.UnsignedLongLongTy; 2689 Width = Context.Target.getLongLongWidth(); 2690 } 2691 2692 if (ResultVal.getBitWidth() != Width) 2693 ResultVal = ResultVal.trunc(Width); 2694 } 2695 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2696 } 2697 2698 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2699 if (Literal.isImaginary) 2700 Res = new (Context) ImaginaryLiteral(Res, 2701 Context.getComplexType(Res->getType())); 2702 2703 return Owned(Res); 2704} 2705 2706ExprResult Sema::ActOnParenExpr(SourceLocation L, 2707 SourceLocation R, Expr *E) { 2708 assert((E != 0) && "ActOnParenExpr() missing expr"); 2709 return Owned(new (Context) ParenExpr(L, R, E)); 2710} 2711 2712/// The UsualUnaryConversions() function is *not* called by this routine. 2713/// See C99 6.3.2.1p[2-4] for more details. 2714bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType, 2715 SourceLocation OpLoc, 2716 SourceRange ExprRange, 2717 UnaryExprOrTypeTrait ExprKind) { 2718 if (exprType->isDependentType()) 2719 return false; 2720 2721 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2722 // the result is the size of the referenced type." 2723 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2724 // result shall be the alignment of the referenced type." 2725 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 2726 exprType = Ref->getPointeeType(); 2727 2728 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2729 // scalar or vector data type argument..." 2730 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2731 // type (C99 6.2.5p18) or void. 2732 if (ExprKind == UETT_VecStep) { 2733 if (!(exprType->isArithmeticType() || exprType->isVoidType() || 2734 exprType->isVectorType())) { 2735 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type) 2736 << exprType << ExprRange; 2737 return true; 2738 } 2739 } 2740 2741 // C99 6.5.3.4p1: 2742 if (exprType->isFunctionType()) { 2743 // alignof(function) is allowed as an extension. 2744 if (ExprKind == UETT_SizeOf) 2745 Diag(OpLoc, diag::ext_sizeof_function_type) 2746 << ExprRange; 2747 return false; 2748 } 2749 2750 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not 2751 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1). 2752 if (exprType->isVoidType()) { 2753 if (ExprKind != UETT_VecStep) 2754 Diag(OpLoc, diag::ext_sizeof_void_type) 2755 << ExprKind << ExprRange; 2756 return false; 2757 } 2758 2759 if (RequireCompleteType(OpLoc, exprType, 2760 PDiag(diag::err_sizeof_alignof_incomplete_type) 2761 << ExprKind << ExprRange)) 2762 return true; 2763 2764 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2765 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) { 2766 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 2767 << exprType << (ExprKind == UETT_SizeOf) 2768 << ExprRange; 2769 return true; 2770 } 2771 2772 return false; 2773} 2774 2775static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc, 2776 SourceRange ExprRange) { 2777 E = E->IgnoreParens(); 2778 2779 // alignof decl is always ok. 2780 if (isa<DeclRefExpr>(E)) 2781 return false; 2782 2783 // Cannot know anything else if the expression is dependent. 2784 if (E->isTypeDependent()) 2785 return false; 2786 2787 if (E->getBitField()) { 2788 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 2789 return true; 2790 } 2791 2792 // Alignment of a field access is always okay, so long as it isn't a 2793 // bit-field. 2794 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2795 if (isa<FieldDecl>(ME->getMemberDecl())) 2796 return false; 2797 2798 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange, 2799 UETT_AlignOf); 2800} 2801 2802bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc, 2803 SourceRange ExprRange) { 2804 E = E->IgnoreParens(); 2805 2806 // Cannot know anything else if the expression is dependent. 2807 if (E->isTypeDependent()) 2808 return false; 2809 2810 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange, 2811 UETT_VecStep); 2812} 2813 2814/// \brief Build a sizeof or alignof expression given a type operand. 2815ExprResult 2816Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2817 SourceLocation OpLoc, 2818 UnaryExprOrTypeTrait ExprKind, 2819 SourceRange R) { 2820 if (!TInfo) 2821 return ExprError(); 2822 2823 QualType T = TInfo->getType(); 2824 2825 if (!T->isDependentType() && 2826 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 2827 return ExprError(); 2828 2829 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2830 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 2831 Context.getSizeType(), 2832 OpLoc, R.getEnd())); 2833} 2834 2835/// \brief Build a sizeof or alignof expression given an expression 2836/// operand. 2837ExprResult 2838Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2839 UnaryExprOrTypeTrait ExprKind, 2840 SourceRange R) { 2841 // Verify that the operand is valid. 2842 bool isInvalid = false; 2843 if (E->isTypeDependent()) { 2844 // Delay type-checking for type-dependent expressions. 2845 } else if (ExprKind == UETT_AlignOf) { 2846 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R); 2847 } else if (ExprKind == UETT_VecStep) { 2848 isInvalid = CheckVecStepExpr(E, OpLoc, R); 2849 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2850 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 2851 isInvalid = true; 2852 } else if (E->getType()->isPlaceholderType()) { 2853 ExprResult PE = CheckPlaceholderExpr(E, OpLoc); 2854 if (PE.isInvalid()) return ExprError(); 2855 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R); 2856 } else { 2857 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R, 2858 UETT_SizeOf); 2859 } 2860 2861 if (isInvalid) 2862 return ExprError(); 2863 2864 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2865 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E, 2866 Context.getSizeType(), 2867 OpLoc, R.getEnd())); 2868} 2869 2870/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 2871/// expr and the same for @c alignof and @c __alignof 2872/// Note that the ArgRange is invalid if isType is false. 2873ExprResult 2874Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2875 UnaryExprOrTypeTrait ExprKind, bool isType, 2876 void *TyOrEx, const SourceRange &ArgRange) { 2877 // If error parsing type, ignore. 2878 if (TyOrEx == 0) return ExprError(); 2879 2880 if (isType) { 2881 TypeSourceInfo *TInfo; 2882 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 2883 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 2884 } 2885 2886 Expr *ArgEx = (Expr *)TyOrEx; 2887 ExprResult Result 2888 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind, 2889 ArgEx->getSourceRange()); 2890 2891 return move(Result); 2892} 2893 2894static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc, 2895 bool isReal) { 2896 if (V->isTypeDependent()) 2897 return S.Context.DependentTy; 2898 2899 // _Real and _Imag are only l-values for normal l-values. 2900 if (V->getObjectKind() != OK_Ordinary) 2901 S.DefaultLvalueConversion(V); 2902 2903 // These operators return the element type of a complex type. 2904 if (const ComplexType *CT = V->getType()->getAs<ComplexType>()) 2905 return CT->getElementType(); 2906 2907 // Otherwise they pass through real integer and floating point types here. 2908 if (V->getType()->isArithmeticType()) 2909 return V->getType(); 2910 2911 // Test for placeholders. 2912 ExprResult PR = S.CheckPlaceholderExpr(V, Loc); 2913 if (PR.isInvalid()) return QualType(); 2914 if (PR.take() != V) { 2915 V = PR.take(); 2916 return CheckRealImagOperand(S, V, Loc, isReal); 2917 } 2918 2919 // Reject anything else. 2920 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 2921 << (isReal ? "__real" : "__imag"); 2922 return QualType(); 2923} 2924 2925 2926 2927ExprResult 2928Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2929 tok::TokenKind Kind, Expr *Input) { 2930 UnaryOperatorKind Opc; 2931 switch (Kind) { 2932 default: assert(0 && "Unknown unary op!"); 2933 case tok::plusplus: Opc = UO_PostInc; break; 2934 case tok::minusminus: Opc = UO_PostDec; break; 2935 } 2936 2937 return BuildUnaryOp(S, OpLoc, Opc, Input); 2938} 2939 2940/// Expressions of certain arbitrary types are forbidden by C from 2941/// having l-value type. These are: 2942/// - 'void', but not qualified void 2943/// - function types 2944/// 2945/// The exact rule here is C99 6.3.2.1: 2946/// An lvalue is an expression with an object type or an incomplete 2947/// type other than void. 2948static bool IsCForbiddenLValueType(ASTContext &C, QualType T) { 2949 return ((T->isVoidType() && !T.hasQualifiers()) || 2950 T->isFunctionType()); 2951} 2952 2953ExprResult 2954Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2955 Expr *Idx, SourceLocation RLoc) { 2956 // Since this might be a postfix expression, get rid of ParenListExprs. 2957 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2958 if (Result.isInvalid()) return ExprError(); 2959 Base = Result.take(); 2960 2961 Expr *LHSExp = Base, *RHSExp = Idx; 2962 2963 if (getLangOptions().CPlusPlus && 2964 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2965 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2966 Context.DependentTy, 2967 VK_LValue, OK_Ordinary, 2968 RLoc)); 2969 } 2970 2971 if (getLangOptions().CPlusPlus && 2972 (LHSExp->getType()->isRecordType() || 2973 LHSExp->getType()->isEnumeralType() || 2974 RHSExp->getType()->isRecordType() || 2975 RHSExp->getType()->isEnumeralType())) { 2976 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 2977 } 2978 2979 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 2980} 2981 2982 2983ExprResult 2984Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2985 Expr *Idx, SourceLocation RLoc) { 2986 Expr *LHSExp = Base; 2987 Expr *RHSExp = Idx; 2988 2989 // Perform default conversions. 2990 if (!LHSExp->getType()->getAs<VectorType>()) 2991 DefaultFunctionArrayLvalueConversion(LHSExp); 2992 DefaultFunctionArrayLvalueConversion(RHSExp); 2993 2994 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 2995 ExprValueKind VK = VK_LValue; 2996 ExprObjectKind OK = OK_Ordinary; 2997 2998 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 2999 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3000 // in the subscript position. As a result, we need to derive the array base 3001 // and index from the expression types. 3002 Expr *BaseExpr, *IndexExpr; 3003 QualType ResultType; 3004 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3005 BaseExpr = LHSExp; 3006 IndexExpr = RHSExp; 3007 ResultType = Context.DependentTy; 3008 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3009 BaseExpr = LHSExp; 3010 IndexExpr = RHSExp; 3011 ResultType = PTy->getPointeeType(); 3012 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3013 // Handle the uncommon case of "123[Ptr]". 3014 BaseExpr = RHSExp; 3015 IndexExpr = LHSExp; 3016 ResultType = PTy->getPointeeType(); 3017 } else if (const ObjCObjectPointerType *PTy = 3018 LHSTy->getAs<ObjCObjectPointerType>()) { 3019 BaseExpr = LHSExp; 3020 IndexExpr = RHSExp; 3021 ResultType = PTy->getPointeeType(); 3022 } else if (const ObjCObjectPointerType *PTy = 3023 RHSTy->getAs<ObjCObjectPointerType>()) { 3024 // Handle the uncommon case of "123[Ptr]". 3025 BaseExpr = RHSExp; 3026 IndexExpr = LHSExp; 3027 ResultType = PTy->getPointeeType(); 3028 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3029 BaseExpr = LHSExp; // vectors: V[123] 3030 IndexExpr = RHSExp; 3031 VK = LHSExp->getValueKind(); 3032 if (VK != VK_RValue) 3033 OK = OK_VectorComponent; 3034 3035 // FIXME: need to deal with const... 3036 ResultType = VTy->getElementType(); 3037 } else if (LHSTy->isArrayType()) { 3038 // If we see an array that wasn't promoted by 3039 // DefaultFunctionArrayLvalueConversion, it must be an array that 3040 // wasn't promoted because of the C90 rule that doesn't 3041 // allow promoting non-lvalue arrays. Warn, then 3042 // force the promotion here. 3043 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3044 LHSExp->getSourceRange(); 3045 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3046 CK_ArrayToPointerDecay); 3047 LHSTy = LHSExp->getType(); 3048 3049 BaseExpr = LHSExp; 3050 IndexExpr = RHSExp; 3051 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3052 } else if (RHSTy->isArrayType()) { 3053 // Same as previous, except for 123[f().a] case 3054 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3055 RHSExp->getSourceRange(); 3056 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3057 CK_ArrayToPointerDecay); 3058 RHSTy = RHSExp->getType(); 3059 3060 BaseExpr = RHSExp; 3061 IndexExpr = LHSExp; 3062 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3063 } else { 3064 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3065 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3066 } 3067 // C99 6.5.2.1p1 3068 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3069 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3070 << IndexExpr->getSourceRange()); 3071 3072 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3073 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3074 && !IndexExpr->isTypeDependent()) 3075 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3076 3077 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3078 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3079 // type. Note that Functions are not objects, and that (in C99 parlance) 3080 // incomplete types are not object types. 3081 if (ResultType->isFunctionType()) { 3082 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3083 << ResultType << BaseExpr->getSourceRange(); 3084 return ExprError(); 3085 } 3086 3087 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) { 3088 // GNU extension: subscripting on pointer to void 3089 Diag(LLoc, diag::ext_gnu_void_ptr) 3090 << BaseExpr->getSourceRange(); 3091 3092 // C forbids expressions of unqualified void type from being l-values. 3093 // See IsCForbiddenLValueType. 3094 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3095 } else if (!ResultType->isDependentType() && 3096 RequireCompleteType(LLoc, ResultType, 3097 PDiag(diag::err_subscript_incomplete_type) 3098 << BaseExpr->getSourceRange())) 3099 return ExprError(); 3100 3101 // Diagnose bad cases where we step over interface counts. 3102 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 3103 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3104 << ResultType << BaseExpr->getSourceRange(); 3105 return ExprError(); 3106 } 3107 3108 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3109 !IsCForbiddenLValueType(Context, ResultType)); 3110 3111 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3112 ResultType, VK, OK, RLoc)); 3113} 3114 3115/// Check an ext-vector component access expression. 3116/// 3117/// VK should be set in advance to the value kind of the base 3118/// expression. 3119static QualType 3120CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK, 3121 SourceLocation OpLoc, const IdentifierInfo *CompName, 3122 SourceLocation CompLoc) { 3123 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 3124 // see FIXME there. 3125 // 3126 // FIXME: This logic can be greatly simplified by splitting it along 3127 // halving/not halving and reworking the component checking. 3128 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 3129 3130 // The vector accessor can't exceed the number of elements. 3131 const char *compStr = CompName->getNameStart(); 3132 3133 // This flag determines whether or not the component is one of the four 3134 // special names that indicate a subset of exactly half the elements are 3135 // to be selected. 3136 bool HalvingSwizzle = false; 3137 3138 // This flag determines whether or not CompName has an 's' char prefix, 3139 // indicating that it is a string of hex values to be used as vector indices. 3140 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 3141 3142 bool HasRepeated = false; 3143 bool HasIndex[16] = {}; 3144 3145 int Idx; 3146 3147 // Check that we've found one of the special components, or that the component 3148 // names must come from the same set. 3149 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 3150 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 3151 HalvingSwizzle = true; 3152 } else if (!HexSwizzle && 3153 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) { 3154 do { 3155 if (HasIndex[Idx]) HasRepeated = true; 3156 HasIndex[Idx] = true; 3157 compStr++; 3158 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1); 3159 } else { 3160 if (HexSwizzle) compStr++; 3161 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) { 3162 if (HasIndex[Idx]) HasRepeated = true; 3163 HasIndex[Idx] = true; 3164 compStr++; 3165 } 3166 } 3167 3168 if (!HalvingSwizzle && *compStr) { 3169 // We didn't get to the end of the string. This means the component names 3170 // didn't come from the same set *or* we encountered an illegal name. 3171 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 3172 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc); 3173 return QualType(); 3174 } 3175 3176 // Ensure no component accessor exceeds the width of the vector type it 3177 // operates on. 3178 if (!HalvingSwizzle) { 3179 compStr = CompName->getNameStart(); 3180 3181 if (HexSwizzle) 3182 compStr++; 3183 3184 while (*compStr) { 3185 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 3186 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 3187 << baseType << SourceRange(CompLoc); 3188 return QualType(); 3189 } 3190 } 3191 } 3192 3193 // The component accessor looks fine - now we need to compute the actual type. 3194 // The vector type is implied by the component accessor. For example, 3195 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 3196 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 3197 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 3198 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 3199 : CompName->getLength(); 3200 if (HexSwizzle) 3201 CompSize--; 3202 3203 if (CompSize == 1) 3204 return vecType->getElementType(); 3205 3206 if (HasRepeated) VK = VK_RValue; 3207 3208 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize); 3209 // Now look up the TypeDefDecl from the vector type. Without this, 3210 // diagostics look bad. We want extended vector types to appear built-in. 3211 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) { 3212 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT) 3213 return S.Context.getTypedefType(S.ExtVectorDecls[i]); 3214 } 3215 return VT; // should never get here (a typedef type should always be found). 3216} 3217 3218static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 3219 IdentifierInfo *Member, 3220 const Selector &Sel, 3221 ASTContext &Context) { 3222 if (Member) 3223 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 3224 return PD; 3225 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 3226 return OMD; 3227 3228 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 3229 E = PDecl->protocol_end(); I != E; ++I) { 3230 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 3231 Context)) 3232 return D; 3233 } 3234 return 0; 3235} 3236 3237static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy, 3238 IdentifierInfo *Member, 3239 const Selector &Sel, 3240 ASTContext &Context) { 3241 // Check protocols on qualified interfaces. 3242 Decl *GDecl = 0; 3243 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 3244 E = QIdTy->qual_end(); I != E; ++I) { 3245 if (Member) 3246 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 3247 GDecl = PD; 3248 break; 3249 } 3250 // Also must look for a getter or setter name which uses property syntax. 3251 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 3252 GDecl = OMD; 3253 break; 3254 } 3255 } 3256 if (!GDecl) { 3257 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 3258 E = QIdTy->qual_end(); I != E; ++I) { 3259 // Search in the protocol-qualifier list of current protocol. 3260 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 3261 Context); 3262 if (GDecl) 3263 return GDecl; 3264 } 3265 } 3266 return GDecl; 3267} 3268 3269ExprResult 3270Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType, 3271 bool IsArrow, SourceLocation OpLoc, 3272 const CXXScopeSpec &SS, 3273 NamedDecl *FirstQualifierInScope, 3274 const DeclarationNameInfo &NameInfo, 3275 const TemplateArgumentListInfo *TemplateArgs) { 3276 // Even in dependent contexts, try to diagnose base expressions with 3277 // obviously wrong types, e.g.: 3278 // 3279 // T* t; 3280 // t.f; 3281 // 3282 // In Obj-C++, however, the above expression is valid, since it could be 3283 // accessing the 'f' property if T is an Obj-C interface. The extra check 3284 // allows this, while still reporting an error if T is a struct pointer. 3285 if (!IsArrow) { 3286 const PointerType *PT = BaseType->getAs<PointerType>(); 3287 if (PT && (!getLangOptions().ObjC1 || 3288 PT->getPointeeType()->isRecordType())) { 3289 assert(BaseExpr && "cannot happen with implicit member accesses"); 3290 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union) 3291 << BaseType << BaseExpr->getSourceRange(); 3292 return ExprError(); 3293 } 3294 } 3295 3296 assert(BaseType->isDependentType() || 3297 NameInfo.getName().isDependentName() || 3298 isDependentScopeSpecifier(SS)); 3299 3300 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 3301 // must have pointer type, and the accessed type is the pointee. 3302 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType, 3303 IsArrow, OpLoc, 3304 SS.getWithLocInContext(Context), 3305 FirstQualifierInScope, 3306 NameInfo, TemplateArgs)); 3307} 3308 3309/// We know that the given qualified member reference points only to 3310/// declarations which do not belong to the static type of the base 3311/// expression. Diagnose the problem. 3312static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 3313 Expr *BaseExpr, 3314 QualType BaseType, 3315 const CXXScopeSpec &SS, 3316 NamedDecl *rep, 3317 const DeclarationNameInfo &nameInfo) { 3318 // If this is an implicit member access, use a different set of 3319 // diagnostics. 3320 if (!BaseExpr) 3321 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo); 3322 3323 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated) 3324 << SS.getRange() << rep << BaseType; 3325} 3326 3327// Check whether the declarations we found through a nested-name 3328// specifier in a member expression are actually members of the base 3329// type. The restriction here is: 3330// 3331// C++ [expr.ref]p2: 3332// ... In these cases, the id-expression shall name a 3333// member of the class or of one of its base classes. 3334// 3335// So it's perfectly legitimate for the nested-name specifier to name 3336// an unrelated class, and for us to find an overload set including 3337// decls from classes which are not superclasses, as long as the decl 3338// we actually pick through overload resolution is from a superclass. 3339bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 3340 QualType BaseType, 3341 const CXXScopeSpec &SS, 3342 const LookupResult &R) { 3343 const RecordType *BaseRT = BaseType->getAs<RecordType>(); 3344 if (!BaseRT) { 3345 // We can't check this yet because the base type is still 3346 // dependent. 3347 assert(BaseType->isDependentType()); 3348 return false; 3349 } 3350 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 3351 3352 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3353 // If this is an implicit member reference and we find a 3354 // non-instance member, it's not an error. 3355 if (!BaseExpr && !(*I)->isCXXInstanceMember()) 3356 return false; 3357 3358 // Note that we use the DC of the decl, not the underlying decl. 3359 DeclContext *DC = (*I)->getDeclContext(); 3360 while (DC->isTransparentContext()) 3361 DC = DC->getParent(); 3362 3363 if (!DC->isRecord()) 3364 continue; 3365 3366 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord; 3367 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl()); 3368 3369 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord)) 3370 return false; 3371 } 3372 3373 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, 3374 R.getRepresentativeDecl(), 3375 R.getLookupNameInfo()); 3376 return true; 3377} 3378 3379static bool 3380LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 3381 SourceRange BaseRange, const RecordType *RTy, 3382 SourceLocation OpLoc, CXXScopeSpec &SS, 3383 bool HasTemplateArgs) { 3384 RecordDecl *RDecl = RTy->getDecl(); 3385 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 3386 SemaRef.PDiag(diag::err_typecheck_incomplete_tag) 3387 << BaseRange)) 3388 return true; 3389 3390 if (HasTemplateArgs) { 3391 // LookupTemplateName doesn't expect these both to exist simultaneously. 3392 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); 3393 3394 bool MOUS; 3395 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS); 3396 return false; 3397 } 3398 3399 DeclContext *DC = RDecl; 3400 if (SS.isSet()) { 3401 // If the member name was a qualified-id, look into the 3402 // nested-name-specifier. 3403 DC = SemaRef.computeDeclContext(SS, false); 3404 3405 if (SemaRef.RequireCompleteDeclContext(SS, DC)) { 3406 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 3407 << SS.getRange() << DC; 3408 return true; 3409 } 3410 3411 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 3412 3413 if (!isa<TypeDecl>(DC)) { 3414 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 3415 << DC << SS.getRange(); 3416 return true; 3417 } 3418 } 3419 3420 // The record definition is complete, now look up the member. 3421 SemaRef.LookupQualifiedName(R, DC); 3422 3423 if (!R.empty()) 3424 return false; 3425 3426 // We didn't find anything with the given name, so try to correct 3427 // for typos. 3428 DeclarationName Name = R.getLookupName(); 3429 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) && 3430 !R.empty() && 3431 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) { 3432 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest) 3433 << Name << DC << R.getLookupName() << SS.getRange() 3434 << FixItHint::CreateReplacement(R.getNameLoc(), 3435 R.getLookupName().getAsString()); 3436 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 3437 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl) 3438 << ND->getDeclName(); 3439 return false; 3440 } else { 3441 R.clear(); 3442 R.setLookupName(Name); 3443 } 3444 3445 return false; 3446} 3447 3448ExprResult 3449Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3450 SourceLocation OpLoc, bool IsArrow, 3451 CXXScopeSpec &SS, 3452 NamedDecl *FirstQualifierInScope, 3453 const DeclarationNameInfo &NameInfo, 3454 const TemplateArgumentListInfo *TemplateArgs) { 3455 if (BaseType->isDependentType() || 3456 (SS.isSet() && isDependentScopeSpecifier(SS))) 3457 return ActOnDependentMemberExpr(Base, BaseType, 3458 IsArrow, OpLoc, 3459 SS, FirstQualifierInScope, 3460 NameInfo, TemplateArgs); 3461 3462 LookupResult R(*this, NameInfo, LookupMemberName); 3463 3464 // Implicit member accesses. 3465 if (!Base) { 3466 QualType RecordTy = BaseType; 3467 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 3468 if (LookupMemberExprInRecord(*this, R, SourceRange(), 3469 RecordTy->getAs<RecordType>(), 3470 OpLoc, SS, TemplateArgs != 0)) 3471 return ExprError(); 3472 3473 // Explicit member accesses. 3474 } else { 3475 ExprResult Result = 3476 LookupMemberExpr(R, Base, IsArrow, OpLoc, 3477 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0); 3478 3479 if (Result.isInvalid()) { 3480 Owned(Base); 3481 return ExprError(); 3482 } 3483 3484 if (Result.get()) 3485 return move(Result); 3486 3487 // LookupMemberExpr can modify Base, and thus change BaseType 3488 BaseType = Base->getType(); 3489 } 3490 3491 return BuildMemberReferenceExpr(Base, BaseType, 3492 OpLoc, IsArrow, SS, FirstQualifierInScope, 3493 R, TemplateArgs); 3494} 3495 3496ExprResult 3497Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 3498 SourceLocation OpLoc, bool IsArrow, 3499 const CXXScopeSpec &SS, 3500 NamedDecl *FirstQualifierInScope, 3501 LookupResult &R, 3502 const TemplateArgumentListInfo *TemplateArgs, 3503 bool SuppressQualifierCheck) { 3504 QualType BaseType = BaseExprType; 3505 if (IsArrow) { 3506 assert(BaseType->isPointerType()); 3507 BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 3508 } 3509 R.setBaseObjectType(BaseType); 3510 3511 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 3512 DeclarationName MemberName = MemberNameInfo.getName(); 3513 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 3514 3515 if (R.isAmbiguous()) 3516 return ExprError(); 3517 3518 if (R.empty()) { 3519 // Rederive where we looked up. 3520 DeclContext *DC = (SS.isSet() 3521 ? computeDeclContext(SS, false) 3522 : BaseType->getAs<RecordType>()->getDecl()); 3523 3524 Diag(R.getNameLoc(), diag::err_no_member) 3525 << MemberName << DC 3526 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 3527 return ExprError(); 3528 } 3529 3530 // Diagnose lookups that find only declarations from a non-base 3531 // type. This is possible for either qualified lookups (which may 3532 // have been qualified with an unrelated type) or implicit member 3533 // expressions (which were found with unqualified lookup and thus 3534 // may have come from an enclosing scope). Note that it's okay for 3535 // lookup to find declarations from a non-base type as long as those 3536 // aren't the ones picked by overload resolution. 3537 if ((SS.isSet() || !BaseExpr || 3538 (isa<CXXThisExpr>(BaseExpr) && 3539 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 3540 !SuppressQualifierCheck && 3541 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 3542 return ExprError(); 3543 3544 // Construct an unresolved result if we in fact got an unresolved 3545 // result. 3546 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 3547 // Suppress any lookup-related diagnostics; we'll do these when we 3548 // pick a member. 3549 R.suppressDiagnostics(); 3550 3551 UnresolvedMemberExpr *MemExpr 3552 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(), 3553 BaseExpr, BaseExprType, 3554 IsArrow, OpLoc, 3555 SS.getWithLocInContext(Context), 3556 MemberNameInfo, 3557 TemplateArgs, R.begin(), R.end()); 3558 3559 return Owned(MemExpr); 3560 } 3561 3562 assert(R.isSingleResult()); 3563 DeclAccessPair FoundDecl = R.begin().getPair(); 3564 NamedDecl *MemberDecl = R.getFoundDecl(); 3565 3566 // FIXME: diagnose the presence of template arguments now. 3567 3568 // If the decl being referenced had an error, return an error for this 3569 // sub-expr without emitting another error, in order to avoid cascading 3570 // error cases. 3571 if (MemberDecl->isInvalidDecl()) 3572 return ExprError(); 3573 3574 // Handle the implicit-member-access case. 3575 if (!BaseExpr) { 3576 // If this is not an instance member, convert to a non-member access. 3577 if (!MemberDecl->isCXXInstanceMember()) 3578 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 3579 3580 SourceLocation Loc = R.getNameLoc(); 3581 if (SS.getRange().isValid()) 3582 Loc = SS.getRange().getBegin(); 3583 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 3584 } 3585 3586 bool ShouldCheckUse = true; 3587 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 3588 // Don't diagnose the use of a virtual member function unless it's 3589 // explicitly qualified. 3590 if (MD->isVirtual() && !SS.isSet()) 3591 ShouldCheckUse = false; 3592 } 3593 3594 // Check the use of this member. 3595 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 3596 Owned(BaseExpr); 3597 return ExprError(); 3598 } 3599 3600 // Perform a property load on the base regardless of whether we 3601 // actually need it for the declaration. 3602 if (BaseExpr->getObjectKind() == OK_ObjCProperty) 3603 ConvertPropertyForRValue(BaseExpr); 3604 3605 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) 3606 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, 3607 SS, FD, FoundDecl, MemberNameInfo); 3608 3609 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl)) 3610 // We may have found a field within an anonymous union or struct 3611 // (C++ [class.union]). 3612 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD, 3613 BaseExpr, OpLoc); 3614 3615 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 3616 MarkDeclarationReferenced(MemberLoc, Var); 3617 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 3618 Var, FoundDecl, MemberNameInfo, 3619 Var->getType().getNonReferenceType(), 3620 VK_LValue, OK_Ordinary)); 3621 } 3622 3623 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) { 3624 MarkDeclarationReferenced(MemberLoc, MemberDecl); 3625 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 3626 MemberFn, FoundDecl, MemberNameInfo, 3627 MemberFn->getType(), 3628 MemberFn->isInstance() ? VK_RValue : VK_LValue, 3629 OK_Ordinary)); 3630 } 3631 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?"); 3632 3633 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 3634 MarkDeclarationReferenced(MemberLoc, MemberDecl); 3635 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 3636 Enum, FoundDecl, MemberNameInfo, 3637 Enum->getType(), VK_RValue, OK_Ordinary)); 3638 } 3639 3640 Owned(BaseExpr); 3641 3642 // We found something that we didn't expect. Complain. 3643 if (isa<TypeDecl>(MemberDecl)) 3644 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 3645 << MemberName << BaseType << int(IsArrow); 3646 else 3647 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 3648 << MemberName << BaseType << int(IsArrow); 3649 3650 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 3651 << MemberName; 3652 R.suppressDiagnostics(); 3653 return ExprError(); 3654} 3655 3656/// Given that normal member access failed on the given expression, 3657/// and given that the expression's type involves builtin-id or 3658/// builtin-Class, decide whether substituting in the redefinition 3659/// types would be profitable. The redefinition type is whatever 3660/// this translation unit tried to typedef to id/Class; we store 3661/// it to the side and then re-use it in places like this. 3662static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) { 3663 const ObjCObjectPointerType *opty 3664 = base->getType()->getAs<ObjCObjectPointerType>(); 3665 if (!opty) return false; 3666 3667 const ObjCObjectType *ty = opty->getObjectType(); 3668 3669 QualType redef; 3670 if (ty->isObjCId()) { 3671 redef = S.Context.ObjCIdRedefinitionType; 3672 } else if (ty->isObjCClass()) { 3673 redef = S.Context.ObjCClassRedefinitionType; 3674 } else { 3675 return false; 3676 } 3677 3678 // Do the substitution as long as the redefinition type isn't just a 3679 // possibly-qualified pointer to builtin-id or builtin-Class again. 3680 opty = redef->getAs<ObjCObjectPointerType>(); 3681 if (opty && !opty->getObjectType()->getInterface() != 0) 3682 return false; 3683 3684 S.ImpCastExprToType(base, redef, CK_BitCast); 3685 return true; 3686} 3687 3688/// Look up the given member of the given non-type-dependent 3689/// expression. This can return in one of two ways: 3690/// * If it returns a sentinel null-but-valid result, the caller will 3691/// assume that lookup was performed and the results written into 3692/// the provided structure. It will take over from there. 3693/// * Otherwise, the returned expression will be produced in place of 3694/// an ordinary member expression. 3695/// 3696/// The ObjCImpDecl bit is a gross hack that will need to be properly 3697/// fixed for ObjC++. 3698ExprResult 3699Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr, 3700 bool &IsArrow, SourceLocation OpLoc, 3701 CXXScopeSpec &SS, 3702 Decl *ObjCImpDecl, bool HasTemplateArgs) { 3703 assert(BaseExpr && "no base expression"); 3704 3705 // Perform default conversions. 3706 DefaultFunctionArrayConversion(BaseExpr); 3707 if (IsArrow) DefaultLvalueConversion(BaseExpr); 3708 3709 QualType BaseType = BaseExpr->getType(); 3710 assert(!BaseType->isDependentType()); 3711 3712 DeclarationName MemberName = R.getLookupName(); 3713 SourceLocation MemberLoc = R.getNameLoc(); 3714 3715 // For later type-checking purposes, turn arrow accesses into dot 3716 // accesses. The only access type we support that doesn't follow 3717 // the C equivalence "a->b === (*a).b" is ObjC property accesses, 3718 // and those never use arrows, so this is unaffected. 3719 if (IsArrow) { 3720 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 3721 BaseType = Ptr->getPointeeType(); 3722 else if (const ObjCObjectPointerType *Ptr 3723 = BaseType->getAs<ObjCObjectPointerType>()) 3724 BaseType = Ptr->getPointeeType(); 3725 else if (BaseType->isRecordType()) { 3726 // Recover from arrow accesses to records, e.g.: 3727 // struct MyRecord foo; 3728 // foo->bar 3729 // This is actually well-formed in C++ if MyRecord has an 3730 // overloaded operator->, but that should have been dealt with 3731 // by now. 3732 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3733 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 3734 << FixItHint::CreateReplacement(OpLoc, "."); 3735 IsArrow = false; 3736 } else { 3737 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 3738 << BaseType << BaseExpr->getSourceRange(); 3739 return ExprError(); 3740 } 3741 } 3742 3743 // Handle field access to simple records. 3744 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 3745 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(), 3746 RTy, OpLoc, SS, HasTemplateArgs)) 3747 return ExprError(); 3748 3749 // Returning valid-but-null is how we indicate to the caller that 3750 // the lookup result was filled in. 3751 return Owned((Expr*) 0); 3752 } 3753 3754 // Handle ivar access to Objective-C objects. 3755 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) { 3756 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3757 3758 // There are three cases for the base type: 3759 // - builtin id (qualified or unqualified) 3760 // - builtin Class (qualified or unqualified) 3761 // - an interface 3762 ObjCInterfaceDecl *IDecl = OTy->getInterface(); 3763 if (!IDecl) { 3764 // There's an implicit 'isa' ivar on all objects. 3765 // But we only actually find it this way on objects of type 'id', 3766 // apparently. 3767 if (OTy->isObjCId() && Member->isStr("isa")) 3768 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc, 3769 Context.getObjCClassType())); 3770 3771 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 3772 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 3773 ObjCImpDecl, HasTemplateArgs); 3774 goto fail; 3775 } 3776 3777 ObjCInterfaceDecl *ClassDeclared; 3778 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 3779 3780 if (!IV) { 3781 // Attempt to correct for typos in ivar names. 3782 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(), 3783 LookupMemberName); 3784 if (CorrectTypo(Res, 0, 0, IDecl, false, 3785 IsArrow ? CTC_ObjCIvarLookup 3786 : CTC_ObjCPropertyLookup) && 3787 (IV = Res.getAsSingle<ObjCIvarDecl>())) { 3788 Diag(R.getNameLoc(), 3789 diag::err_typecheck_member_reference_ivar_suggest) 3790 << IDecl->getDeclName() << MemberName << IV->getDeclName() 3791 << FixItHint::CreateReplacement(R.getNameLoc(), 3792 IV->getNameAsString()); 3793 Diag(IV->getLocation(), diag::note_previous_decl) 3794 << IV->getDeclName(); 3795 } else { 3796 Res.clear(); 3797 Res.setLookupName(Member); 3798 3799 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 3800 << IDecl->getDeclName() << MemberName 3801 << BaseExpr->getSourceRange(); 3802 return ExprError(); 3803 } 3804 } 3805 3806 // If the decl being referenced had an error, return an error for this 3807 // sub-expr without emitting another error, in order to avoid cascading 3808 // error cases. 3809 if (IV->isInvalidDecl()) 3810 return ExprError(); 3811 3812 // Check whether we can reference this field. 3813 if (DiagnoseUseOfDecl(IV, MemberLoc)) 3814 return ExprError(); 3815 if (IV->getAccessControl() != ObjCIvarDecl::Public && 3816 IV->getAccessControl() != ObjCIvarDecl::Package) { 3817 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 3818 if (ObjCMethodDecl *MD = getCurMethodDecl()) 3819 ClassOfMethodDecl = MD->getClassInterface(); 3820 else if (ObjCImpDecl && getCurFunctionDecl()) { 3821 // Case of a c-function declared inside an objc implementation. 3822 // FIXME: For a c-style function nested inside an objc implementation 3823 // class, there is no implementation context available, so we pass 3824 // down the context as argument to this routine. Ideally, this context 3825 // need be passed down in the AST node and somehow calculated from the 3826 // AST for a function decl. 3827 if (ObjCImplementationDecl *IMPD = 3828 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 3829 ClassOfMethodDecl = IMPD->getClassInterface(); 3830 else if (ObjCCategoryImplDecl* CatImplClass = 3831 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 3832 ClassOfMethodDecl = CatImplClass->getClassInterface(); 3833 } 3834 3835 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 3836 if (ClassDeclared != IDecl || 3837 ClassOfMethodDecl != ClassDeclared) 3838 Diag(MemberLoc, diag::error_private_ivar_access) 3839 << IV->getDeclName(); 3840 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 3841 // @protected 3842 Diag(MemberLoc, diag::error_protected_ivar_access) 3843 << IV->getDeclName(); 3844 } 3845 3846 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 3847 MemberLoc, BaseExpr, 3848 IsArrow)); 3849 } 3850 3851 // Objective-C property access. 3852 const ObjCObjectPointerType *OPT; 3853 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) { 3854 // This actually uses the base as an r-value. 3855 DefaultLvalueConversion(BaseExpr); 3856 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType())); 3857 3858 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3859 3860 const ObjCObjectType *OT = OPT->getObjectType(); 3861 3862 // id, with and without qualifiers. 3863 if (OT->isObjCId()) { 3864 // Check protocols on qualified interfaces. 3865 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3866 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) { 3867 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 3868 // Check the use of this declaration 3869 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3870 return ExprError(); 3871 3872 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 3873 VK_LValue, 3874 OK_ObjCProperty, 3875 MemberLoc, 3876 BaseExpr)); 3877 } 3878 3879 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 3880 // Check the use of this method. 3881 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 3882 return ExprError(); 3883 Selector SetterSel = 3884 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3885 PP.getSelectorTable(), Member); 3886 ObjCMethodDecl *SMD = 0; 3887 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0, 3888 SetterSel, Context)) 3889 SMD = dyn_cast<ObjCMethodDecl>(SDecl); 3890 QualType PType = OMD->getSendResultType(); 3891 3892 ExprValueKind VK = VK_LValue; 3893 if (!getLangOptions().CPlusPlus && 3894 IsCForbiddenLValueType(Context, PType)) 3895 VK = VK_RValue; 3896 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty); 3897 3898 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType, 3899 VK, OK, 3900 MemberLoc, BaseExpr)); 3901 } 3902 } 3903 3904 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 3905 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 3906 ObjCImpDecl, HasTemplateArgs); 3907 3908 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3909 << MemberName << BaseType); 3910 } 3911 3912 // 'Class', unqualified only. 3913 if (OT->isObjCClass()) { 3914 // Only works in a method declaration (??!). 3915 ObjCMethodDecl *MD = getCurMethodDecl(); 3916 if (!MD) { 3917 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 3918 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 3919 ObjCImpDecl, HasTemplateArgs); 3920 3921 goto fail; 3922 } 3923 3924 // Also must look for a getter name which uses property syntax. 3925 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3926 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 3927 ObjCMethodDecl *Getter; 3928 if ((Getter = IFace->lookupClassMethod(Sel))) { 3929 // Check the use of this method. 3930 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 3931 return ExprError(); 3932 } else 3933 Getter = IFace->lookupPrivateMethod(Sel, false); 3934 // If we found a getter then this may be a valid dot-reference, we 3935 // will look for the matching setter, in case it is needed. 3936 Selector SetterSel = 3937 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3938 PP.getSelectorTable(), Member); 3939 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 3940 if (!Setter) { 3941 // If this reference is in an @implementation, also check for 'private' 3942 // methods. 3943 Setter = IFace->lookupPrivateMethod(SetterSel, false); 3944 } 3945 // Look through local category implementations associated with the class. 3946 if (!Setter) 3947 Setter = IFace->getCategoryClassMethod(SetterSel); 3948 3949 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 3950 return ExprError(); 3951 3952 if (Getter || Setter) { 3953 QualType PType; 3954 3955 ExprValueKind VK = VK_LValue; 3956 if (Getter) { 3957 PType = Getter->getSendResultType(); 3958 if (!getLangOptions().CPlusPlus && 3959 IsCForbiddenLValueType(Context, PType)) 3960 VK = VK_RValue; 3961 } else { 3962 // Get the expression type from Setter's incoming parameter. 3963 PType = (*(Setter->param_end() -1))->getType(); 3964 } 3965 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty); 3966 3967 // FIXME: we must check that the setter has property type. 3968 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 3969 PType, VK, OK, 3970 MemberLoc, BaseExpr)); 3971 } 3972 3973 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 3974 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 3975 ObjCImpDecl, HasTemplateArgs); 3976 3977 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3978 << MemberName << BaseType); 3979 } 3980 3981 // Normal property access. 3982 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc, 3983 SourceLocation(), QualType(), false); 3984 } 3985 3986 // Handle 'field access' to vectors, such as 'V.xx'. 3987 if (BaseType->isExtVectorType()) { 3988 // FIXME: this expr should store IsArrow. 3989 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3990 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind()); 3991 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc, 3992 Member, MemberLoc); 3993 if (ret.isNull()) 3994 return ExprError(); 3995 3996 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr, 3997 *Member, MemberLoc)); 3998 } 3999 4000 // Adjust builtin-sel to the appropriate redefinition type if that's 4001 // not just a pointer to builtin-sel again. 4002 if (IsArrow && 4003 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) && 4004 !Context.ObjCSelRedefinitionType->isObjCSelType()) { 4005 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast); 4006 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 4007 ObjCImpDecl, HasTemplateArgs); 4008 } 4009 4010 // Failure cases. 4011 fail: 4012 4013 // Recover from dot accesses to pointers, e.g.: 4014 // type *foo; 4015 // foo.bar 4016 // This is actually well-formed in two cases: 4017 // - 'type' is an Objective C type 4018 // - 'bar' is a pseudo-destructor name which happens to refer to 4019 // the appropriate pointer type 4020 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 4021 if (!IsArrow && Ptr->getPointeeType()->isRecordType() && 4022 MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 4023 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 4024 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 4025 << FixItHint::CreateReplacement(OpLoc, "->"); 4026 4027 // Recurse as an -> access. 4028 IsArrow = true; 4029 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 4030 ObjCImpDecl, HasTemplateArgs); 4031 } 4032 } 4033 4034 // If the user is trying to apply -> or . to a function name, it's probably 4035 // because they forgot parentheses to call that function. 4036 bool TryCall = false; 4037 bool Overloaded = false; 4038 UnresolvedSet<8> AllOverloads; 4039 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) { 4040 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end()); 4041 TryCall = true; 4042 Overloaded = true; 4043 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) { 4044 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 4045 AllOverloads.addDecl(Fun); 4046 TryCall = true; 4047 } 4048 } 4049 4050 if (TryCall) { 4051 // Plunder the overload set for something that would make the member 4052 // expression valid. 4053 UnresolvedSet<4> ViableOverloads; 4054 bool HasViableZeroArgOverload = false; 4055 for (OverloadExpr::decls_iterator it = AllOverloads.begin(), 4056 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) { 4057 // Our overload set may include TemplateDecls, which we'll ignore for the 4058 // purposes of determining whether we can issue a '()' fixit. 4059 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) { 4060 QualType ResultTy = OverloadDecl->getResultType(); 4061 if ((!IsArrow && ResultTy->isRecordType()) || 4062 (IsArrow && ResultTy->isPointerType() && 4063 ResultTy->getPointeeType()->isRecordType())) { 4064 ViableOverloads.addDecl(*it); 4065 if (OverloadDecl->getMinRequiredArguments() == 0) { 4066 HasViableZeroArgOverload = true; 4067 } 4068 } 4069 } 4070 } 4071 4072 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) { 4073 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call) 4074 << (AllOverloads.size() > 1) << 0 4075 << BaseExpr->getSourceRange(); 4076 int ViableOverloadCount = ViableOverloads.size(); 4077 int I; 4078 for (I = 0; I < ViableOverloadCount; ++I) { 4079 // FIXME: Magic number for max shown overloads stolen from 4080 // OverloadCandidateSet::NoteCandidates. 4081 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) { 4082 break; 4083 } 4084 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(), 4085 diag::note_member_ref_possible_intended_overload); 4086 } 4087 if (I != ViableOverloadCount) { 4088 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates) 4089 << int(ViableOverloadCount - I); 4090 } 4091 return ExprError(); 4092 } 4093 } else { 4094 // We don't have an expression that's convenient to get a Decl from, but we 4095 // can at least check if the type is "function of 0 arguments which returns 4096 // an acceptable type". 4097 const FunctionType *Fun = NULL; 4098 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 4099 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) { 4100 TryCall = true; 4101 } 4102 } else if ((Fun = BaseType->getAs<FunctionType>())) { 4103 TryCall = true; 4104 } 4105 4106 if (TryCall) { 4107 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) { 4108 if (FPT->getNumArgs() == 0) { 4109 QualType ResultTy = Fun->getResultType(); 4110 TryCall = (!IsArrow && ResultTy->isRecordType()) || 4111 (IsArrow && ResultTy->isPointerType() && 4112 ResultTy->getPointeeType()->isRecordType()); 4113 } 4114 } 4115 } 4116 } 4117 4118 if (TryCall) { 4119 // At this point, we know BaseExpr looks like it's potentially callable with 4120 // 0 arguments, and that it returns something of a reasonable type, so we 4121 // can emit a fixit and carry on pretending that BaseExpr was actually a 4122 // CallExpr. 4123 SourceLocation ParenInsertionLoc = 4124 PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 4125 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call) 4126 << int(Overloaded) << 1 4127 << BaseExpr->getSourceRange() 4128 << FixItHint::CreateInsertion(ParenInsertionLoc, "()"); 4129 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc, 4130 MultiExprArg(*this, 0, 0), 4131 ParenInsertionLoc); 4132 if (NewBase.isInvalid()) 4133 return ExprError(); 4134 BaseExpr = NewBase.takeAs<Expr>(); 4135 DefaultFunctionArrayConversion(BaseExpr); 4136 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 4137 ObjCImpDecl, HasTemplateArgs); 4138 } 4139 4140 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 4141 << BaseType << BaseExpr->getSourceRange(); 4142 4143 return ExprError(); 4144} 4145 4146/// The main callback when the parser finds something like 4147/// expression . [nested-name-specifier] identifier 4148/// expression -> [nested-name-specifier] identifier 4149/// where 'identifier' encompasses a fairly broad spectrum of 4150/// possibilities, including destructor and operator references. 4151/// 4152/// \param OpKind either tok::arrow or tok::period 4153/// \param HasTrailingLParen whether the next token is '(', which 4154/// is used to diagnose mis-uses of special members that can 4155/// only be called 4156/// \param ObjCImpDecl the current ObjC @implementation decl; 4157/// this is an ugly hack around the fact that ObjC @implementations 4158/// aren't properly put in the context chain 4159ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 4160 SourceLocation OpLoc, 4161 tok::TokenKind OpKind, 4162 CXXScopeSpec &SS, 4163 UnqualifiedId &Id, 4164 Decl *ObjCImpDecl, 4165 bool HasTrailingLParen) { 4166 if (SS.isSet() && SS.isInvalid()) 4167 return ExprError(); 4168 4169 // Warn about the explicit constructor calls Microsoft extension. 4170 if (getLangOptions().Microsoft && 4171 Id.getKind() == UnqualifiedId::IK_ConstructorName) 4172 Diag(Id.getSourceRange().getBegin(), 4173 diag::ext_ms_explicit_constructor_call); 4174 4175 TemplateArgumentListInfo TemplateArgsBuffer; 4176 4177 // Decompose the name into its component parts. 4178 DeclarationNameInfo NameInfo; 4179 const TemplateArgumentListInfo *TemplateArgs; 4180 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, 4181 NameInfo, TemplateArgs); 4182 4183 DeclarationName Name = NameInfo.getName(); 4184 bool IsArrow = (OpKind == tok::arrow); 4185 4186 NamedDecl *FirstQualifierInScope 4187 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, 4188 static_cast<NestedNameSpecifier*>(SS.getScopeRep()))); 4189 4190 // This is a postfix expression, so get rid of ParenListExprs. 4191 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 4192 if (Result.isInvalid()) return ExprError(); 4193 Base = Result.take(); 4194 4195 if (Base->getType()->isDependentType() || Name.isDependentName() || 4196 isDependentScopeSpecifier(SS)) { 4197 Result = ActOnDependentMemberExpr(Base, Base->getType(), 4198 IsArrow, OpLoc, 4199 SS, FirstQualifierInScope, 4200 NameInfo, TemplateArgs); 4201 } else { 4202 LookupResult R(*this, NameInfo, LookupMemberName); 4203 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc, 4204 SS, ObjCImpDecl, TemplateArgs != 0); 4205 4206 if (Result.isInvalid()) { 4207 Owned(Base); 4208 return ExprError(); 4209 } 4210 4211 if (Result.get()) { 4212 // The only way a reference to a destructor can be used is to 4213 // immediately call it, which falls into this case. If the 4214 // next token is not a '(', produce a diagnostic and build the 4215 // call now. 4216 if (!HasTrailingLParen && 4217 Id.getKind() == UnqualifiedId::IK_DestructorName) 4218 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get()); 4219 4220 return move(Result); 4221 } 4222 4223 Result = BuildMemberReferenceExpr(Base, Base->getType(), 4224 OpLoc, IsArrow, SS, FirstQualifierInScope, 4225 R, TemplateArgs); 4226 } 4227 4228 return move(Result); 4229} 4230 4231ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4232 FunctionDecl *FD, 4233 ParmVarDecl *Param) { 4234 if (Param->hasUnparsedDefaultArg()) { 4235 Diag(CallLoc, 4236 diag::err_use_of_default_argument_to_function_declared_later) << 4237 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4238 Diag(UnparsedDefaultArgLocs[Param], 4239 diag::note_default_argument_declared_here); 4240 return ExprError(); 4241 } 4242 4243 if (Param->hasUninstantiatedDefaultArg()) { 4244 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4245 4246 // Instantiate the expression. 4247 MultiLevelTemplateArgumentList ArgList 4248 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 4249 4250 std::pair<const TemplateArgument *, unsigned> Innermost 4251 = ArgList.getInnermost(); 4252 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 4253 Innermost.second); 4254 4255 ExprResult Result; 4256 { 4257 // C++ [dcl.fct.default]p5: 4258 // The names in the [default argument] expression are bound, and 4259 // the semantic constraints are checked, at the point where the 4260 // default argument expression appears. 4261 ContextRAII SavedContext(*this, FD); 4262 Result = SubstExpr(UninstExpr, ArgList); 4263 } 4264 if (Result.isInvalid()) 4265 return ExprError(); 4266 4267 // Check the expression as an initializer for the parameter. 4268 InitializedEntity Entity 4269 = InitializedEntity::InitializeParameter(Context, Param); 4270 InitializationKind Kind 4271 = InitializationKind::CreateCopy(Param->getLocation(), 4272 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 4273 Expr *ResultE = Result.takeAs<Expr>(); 4274 4275 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 4276 Result = InitSeq.Perform(*this, Entity, Kind, 4277 MultiExprArg(*this, &ResultE, 1)); 4278 if (Result.isInvalid()) 4279 return ExprError(); 4280 4281 // Build the default argument expression. 4282 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 4283 Result.takeAs<Expr>())); 4284 } 4285 4286 // If the default expression creates temporaries, we need to 4287 // push them to the current stack of expression temporaries so they'll 4288 // be properly destroyed. 4289 // FIXME: We should really be rebuilding the default argument with new 4290 // bound temporaries; see the comment in PR5810. 4291 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) { 4292 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i); 4293 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(), 4294 const_cast<CXXDestructorDecl*>(Temporary->getDestructor())); 4295 ExprTemporaries.push_back(Temporary); 4296 } 4297 4298 // We already type-checked the argument, so we know it works. 4299 // Just mark all of the declarations in this potentially-evaluated expression 4300 // as being "referenced". 4301 MarkDeclarationsReferencedInExpr(Param->getDefaultArg()); 4302 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 4303} 4304 4305/// ConvertArgumentsForCall - Converts the arguments specified in 4306/// Args/NumArgs to the parameter types of the function FDecl with 4307/// function prototype Proto. Call is the call expression itself, and 4308/// Fn is the function expression. For a C++ member function, this 4309/// routine does not attempt to convert the object argument. Returns 4310/// true if the call is ill-formed. 4311bool 4312Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4313 FunctionDecl *FDecl, 4314 const FunctionProtoType *Proto, 4315 Expr **Args, unsigned NumArgs, 4316 SourceLocation RParenLoc) { 4317 // Bail out early if calling a builtin with custom typechecking. 4318 // We don't need to do this in the 4319 if (FDecl) 4320 if (unsigned ID = FDecl->getBuiltinID()) 4321 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4322 return false; 4323 4324 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4325 // assignment, to the types of the corresponding parameter, ... 4326 unsigned NumArgsInProto = Proto->getNumArgs(); 4327 bool Invalid = false; 4328 4329 // If too few arguments are available (and we don't have default 4330 // arguments for the remaining parameters), don't make the call. 4331 if (NumArgs < NumArgsInProto) { 4332 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 4333 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 4334 << Fn->getType()->isBlockPointerType() 4335 << NumArgsInProto << NumArgs << Fn->getSourceRange(); 4336 Call->setNumArgs(Context, NumArgsInProto); 4337 } 4338 4339 // If too many are passed and not variadic, error on the extras and drop 4340 // them. 4341 if (NumArgs > NumArgsInProto) { 4342 if (!Proto->isVariadic()) { 4343 Diag(Args[NumArgsInProto]->getLocStart(), 4344 diag::err_typecheck_call_too_many_args) 4345 << Fn->getType()->isBlockPointerType() 4346 << NumArgsInProto << NumArgs << Fn->getSourceRange() 4347 << SourceRange(Args[NumArgsInProto]->getLocStart(), 4348 Args[NumArgs-1]->getLocEnd()); 4349 // This deletes the extra arguments. 4350 Call->setNumArgs(Context, NumArgsInProto); 4351 return true; 4352 } 4353 } 4354 llvm::SmallVector<Expr *, 8> AllArgs; 4355 VariadicCallType CallType = 4356 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 4357 if (Fn->getType()->isBlockPointerType()) 4358 CallType = VariadicBlock; // Block 4359 else if (isa<MemberExpr>(Fn)) 4360 CallType = VariadicMethod; 4361 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 4362 Proto, 0, Args, NumArgs, AllArgs, CallType); 4363 if (Invalid) 4364 return true; 4365 unsigned TotalNumArgs = AllArgs.size(); 4366 for (unsigned i = 0; i < TotalNumArgs; ++i) 4367 Call->setArg(i, AllArgs[i]); 4368 4369 return false; 4370} 4371 4372bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 4373 FunctionDecl *FDecl, 4374 const FunctionProtoType *Proto, 4375 unsigned FirstProtoArg, 4376 Expr **Args, unsigned NumArgs, 4377 llvm::SmallVector<Expr *, 8> &AllArgs, 4378 VariadicCallType CallType) { 4379 unsigned NumArgsInProto = Proto->getNumArgs(); 4380 unsigned NumArgsToCheck = NumArgs; 4381 bool Invalid = false; 4382 if (NumArgs != NumArgsInProto) 4383 // Use default arguments for missing arguments 4384 NumArgsToCheck = NumArgsInProto; 4385 unsigned ArgIx = 0; 4386 // Continue to check argument types (even if we have too few/many args). 4387 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 4388 QualType ProtoArgType = Proto->getArgType(i); 4389 4390 Expr *Arg; 4391 if (ArgIx < NumArgs) { 4392 Arg = Args[ArgIx++]; 4393 4394 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 4395 ProtoArgType, 4396 PDiag(diag::err_call_incomplete_argument) 4397 << Arg->getSourceRange())) 4398 return true; 4399 4400 // Pass the argument 4401 ParmVarDecl *Param = 0; 4402 if (FDecl && i < FDecl->getNumParams()) 4403 Param = FDecl->getParamDecl(i); 4404 4405 InitializedEntity Entity = 4406 Param? InitializedEntity::InitializeParameter(Context, Param) 4407 : InitializedEntity::InitializeParameter(Context, ProtoArgType); 4408 ExprResult ArgE = PerformCopyInitialization(Entity, 4409 SourceLocation(), 4410 Owned(Arg)); 4411 if (ArgE.isInvalid()) 4412 return true; 4413 4414 Arg = ArgE.takeAs<Expr>(); 4415 } else { 4416 ParmVarDecl *Param = FDecl->getParamDecl(i); 4417 4418 ExprResult ArgExpr = 4419 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4420 if (ArgExpr.isInvalid()) 4421 return true; 4422 4423 Arg = ArgExpr.takeAs<Expr>(); 4424 } 4425 AllArgs.push_back(Arg); 4426 } 4427 4428 // If this is a variadic call, handle args passed through "...". 4429 if (CallType != VariadicDoesNotApply) { 4430 // Promote the arguments (C99 6.5.2.2p7). 4431 for (unsigned i = ArgIx; i != NumArgs; ++i) { 4432 Expr *Arg = Args[i]; 4433 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl); 4434 AllArgs.push_back(Arg); 4435 } 4436 } 4437 return Invalid; 4438} 4439 4440/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4441/// This provides the location of the left/right parens and a list of comma 4442/// locations. 4443ExprResult 4444Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4445 MultiExprArg args, SourceLocation RParenLoc, 4446 Expr *ExecConfig) { 4447 unsigned NumArgs = args.size(); 4448 4449 // Since this might be a postfix expression, get rid of ParenListExprs. 4450 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4451 if (Result.isInvalid()) return ExprError(); 4452 Fn = Result.take(); 4453 4454 Expr **Args = args.release(); 4455 4456 if (getLangOptions().CPlusPlus) { 4457 // If this is a pseudo-destructor expression, build the call immediately. 4458 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4459 if (NumArgs > 0) { 4460 // Pseudo-destructor calls should not have any arguments. 4461 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4462 << FixItHint::CreateRemoval( 4463 SourceRange(Args[0]->getLocStart(), 4464 Args[NumArgs-1]->getLocEnd())); 4465 4466 NumArgs = 0; 4467 } 4468 4469 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 4470 VK_RValue, RParenLoc)); 4471 } 4472 4473 // Determine whether this is a dependent call inside a C++ template, 4474 // in which case we won't do any semantic analysis now. 4475 // FIXME: Will need to cache the results of name lookup (including ADL) in 4476 // Fn. 4477 bool Dependent = false; 4478 if (Fn->isTypeDependent()) 4479 Dependent = true; 4480 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 4481 Dependent = true; 4482 4483 if (Dependent) { 4484 if (ExecConfig) { 4485 return Owned(new (Context) CUDAKernelCallExpr( 4486 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 4487 Context.DependentTy, VK_RValue, RParenLoc)); 4488 } else { 4489 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 4490 Context.DependentTy, VK_RValue, 4491 RParenLoc)); 4492 } 4493 } 4494 4495 // Determine whether this is a call to an object (C++ [over.call.object]). 4496 if (Fn->getType()->isRecordType()) 4497 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 4498 RParenLoc)); 4499 4500 Expr *NakedFn = Fn->IgnoreParens(); 4501 4502 // Determine whether this is a call to an unresolved member function. 4503 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 4504 // If lookup was unresolved but not dependent (i.e. didn't find 4505 // an unresolved using declaration), it has to be an overloaded 4506 // function set, which means it must contain either multiple 4507 // declarations (all methods or method templates) or a single 4508 // method template. 4509 assert((MemE->getNumDecls() > 1) || 4510 isa<FunctionTemplateDecl>( 4511 (*MemE->decls_begin())->getUnderlyingDecl())); 4512 (void)MemE; 4513 4514 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 4515 RParenLoc); 4516 } 4517 4518 // Determine whether this is a call to a member function. 4519 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) { 4520 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 4521 if (isa<CXXMethodDecl>(MemDecl)) 4522 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 4523 RParenLoc); 4524 } 4525 4526 // Determine whether this is a call to a pointer-to-member function. 4527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) { 4528 if (BO->getOpcode() == BO_PtrMemD || 4529 BO->getOpcode() == BO_PtrMemI) { 4530 if (const FunctionProtoType *FPT 4531 = BO->getType()->getAs<FunctionProtoType>()) { 4532 QualType ResultTy = FPT->getCallResultType(Context); 4533 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType()); 4534 4535 // Check that the object type isn't more qualified than the 4536 // member function we're calling. 4537 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals()); 4538 Qualifiers ObjectQuals 4539 = BO->getOpcode() == BO_PtrMemD 4540 ? BO->getLHS()->getType().getQualifiers() 4541 : BO->getLHS()->getType()->getAs<PointerType>() 4542 ->getPointeeType().getQualifiers(); 4543 4544 Qualifiers Difference = ObjectQuals - FuncQuals; 4545 Difference.removeObjCGCAttr(); 4546 Difference.removeAddressSpace(); 4547 if (Difference) { 4548 std::string QualsString = Difference.getAsString(); 4549 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 4550 << BO->getType().getUnqualifiedType() 4551 << QualsString 4552 << (QualsString.find(' ') == std::string::npos? 1 : 2); 4553 } 4554 4555 CXXMemberCallExpr *TheCall 4556 = new (Context) CXXMemberCallExpr(Context, Fn, Args, 4557 NumArgs, ResultTy, VK, 4558 RParenLoc); 4559 4560 if (CheckCallReturnType(FPT->getResultType(), 4561 BO->getRHS()->getSourceRange().getBegin(), 4562 TheCall, 0)) 4563 return ExprError(); 4564 4565 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs, 4566 RParenLoc)) 4567 return ExprError(); 4568 4569 return MaybeBindToTemporary(TheCall); 4570 } 4571 return ExprError(Diag(Fn->getLocStart(), 4572 diag::err_typecheck_call_not_function) 4573 << Fn->getType() << Fn->getSourceRange()); 4574 } 4575 } 4576 } 4577 4578 // If we're directly calling a function, get the appropriate declaration. 4579 // Also, in C++, keep track of whether we should perform argument-dependent 4580 // lookup and whether there were any explicitly-specified template arguments. 4581 4582 Expr *NakedFn = Fn->IgnoreParens(); 4583 if (isa<UnresolvedLookupExpr>(NakedFn)) { 4584 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn); 4585 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 4586 RParenLoc, ExecConfig); 4587 } 4588 4589 NamedDecl *NDecl = 0; 4590 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4591 if (UnOp->getOpcode() == UO_AddrOf) 4592 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4593 4594 if (isa<DeclRefExpr>(NakedFn)) 4595 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4596 4597 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 4598 ExecConfig); 4599} 4600 4601ExprResult 4602Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4603 MultiExprArg execConfig, SourceLocation GGGLoc) { 4604 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4605 if (!ConfigDecl) 4606 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4607 << "cudaConfigureCall"); 4608 QualType ConfigQTy = ConfigDecl->getType(); 4609 4610 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4611 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc); 4612 4613 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0); 4614} 4615 4616/// BuildResolvedCallExpr - Build a call to a resolved expression, 4617/// i.e. an expression not of \p OverloadTy. The expression should 4618/// unary-convert to an expression of function-pointer or 4619/// block-pointer type. 4620/// 4621/// \param NDecl the declaration being called, if available 4622ExprResult 4623Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4624 SourceLocation LParenLoc, 4625 Expr **Args, unsigned NumArgs, 4626 SourceLocation RParenLoc, 4627 Expr *Config) { 4628 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4629 4630 // Promote the function operand. 4631 UsualUnaryConversions(Fn); 4632 4633 // Make the call expr early, before semantic checks. This guarantees cleanup 4634 // of arguments and function on error. 4635 CallExpr *TheCall; 4636 if (Config) { 4637 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4638 cast<CallExpr>(Config), 4639 Args, NumArgs, 4640 Context.BoolTy, 4641 VK_RValue, 4642 RParenLoc); 4643 } else { 4644 TheCall = new (Context) CallExpr(Context, Fn, 4645 Args, NumArgs, 4646 Context.BoolTy, 4647 VK_RValue, 4648 RParenLoc); 4649 } 4650 4651 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4652 4653 // Bail out early if calling a builtin with custom typechecking. 4654 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4655 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4656 4657 const FunctionType *FuncT; 4658 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4659 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4660 // have type pointer to function". 4661 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4662 if (FuncT == 0) 4663 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4664 << Fn->getType() << Fn->getSourceRange()); 4665 } else if (const BlockPointerType *BPT = 4666 Fn->getType()->getAs<BlockPointerType>()) { 4667 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4668 } else { 4669 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4670 << Fn->getType() << Fn->getSourceRange()); 4671 } 4672 4673 if (getLangOptions().CUDA) { 4674 if (Config) { 4675 // CUDA: Kernel calls must be to global functions 4676 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4677 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4678 << FDecl->getName() << Fn->getSourceRange()); 4679 4680 // CUDA: Kernel function must have 'void' return type 4681 if (!FuncT->getResultType()->isVoidType()) 4682 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4683 << Fn->getType() << Fn->getSourceRange()); 4684 } 4685 } 4686 4687 // Check for a valid return type 4688 if (CheckCallReturnType(FuncT->getResultType(), 4689 Fn->getSourceRange().getBegin(), TheCall, 4690 FDecl)) 4691 return ExprError(); 4692 4693 // We know the result type of the call, set it. 4694 TheCall->setType(FuncT->getCallResultType(Context)); 4695 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4696 4697 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 4698 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 4699 RParenLoc)) 4700 return ExprError(); 4701 } else { 4702 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4703 4704 if (FDecl) { 4705 // Check if we have too few/too many template arguments, based 4706 // on our knowledge of the function definition. 4707 const FunctionDecl *Def = 0; 4708 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 4709 const FunctionProtoType *Proto 4710 = Def->getType()->getAs<FunctionProtoType>(); 4711 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 4712 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4713 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4714 } 4715 4716 // If the function we're calling isn't a function prototype, but we have 4717 // a function prototype from a prior declaratiom, use that prototype. 4718 if (!FDecl->hasPrototype()) 4719 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4720 } 4721 4722 // Promote the arguments (C99 6.5.2.2p6). 4723 for (unsigned i = 0; i != NumArgs; i++) { 4724 Expr *Arg = Args[i]; 4725 4726 if (Proto && i < Proto->getNumArgs()) { 4727 InitializedEntity Entity 4728 = InitializedEntity::InitializeParameter(Context, 4729 Proto->getArgType(i)); 4730 ExprResult ArgE = PerformCopyInitialization(Entity, 4731 SourceLocation(), 4732 Owned(Arg)); 4733 if (ArgE.isInvalid()) 4734 return true; 4735 4736 Arg = ArgE.takeAs<Expr>(); 4737 4738 } else { 4739 DefaultArgumentPromotion(Arg); 4740 } 4741 4742 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 4743 Arg->getType(), 4744 PDiag(diag::err_call_incomplete_argument) 4745 << Arg->getSourceRange())) 4746 return ExprError(); 4747 4748 TheCall->setArg(i, Arg); 4749 } 4750 } 4751 4752 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4753 if (!Method->isStatic()) 4754 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4755 << Fn->getSourceRange()); 4756 4757 // Check for sentinels 4758 if (NDecl) 4759 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4760 4761 // Do special checking on direct calls to functions. 4762 if (FDecl) { 4763 if (CheckFunctionCall(FDecl, TheCall)) 4764 return ExprError(); 4765 4766 if (BuiltinID) 4767 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4768 } else if (NDecl) { 4769 if (CheckBlockCall(NDecl, TheCall)) 4770 return ExprError(); 4771 } 4772 4773 return MaybeBindToTemporary(TheCall); 4774} 4775 4776ExprResult 4777Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4778 SourceLocation RParenLoc, Expr *InitExpr) { 4779 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4780 // FIXME: put back this assert when initializers are worked out. 4781 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4782 4783 TypeSourceInfo *TInfo; 4784 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4785 if (!TInfo) 4786 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4787 4788 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4789} 4790 4791ExprResult 4792Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4793 SourceLocation RParenLoc, Expr *literalExpr) { 4794 QualType literalType = TInfo->getType(); 4795 4796 if (literalType->isArrayType()) { 4797 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4798 PDiag(diag::err_illegal_decl_array_incomplete_type) 4799 << SourceRange(LParenLoc, 4800 literalExpr->getSourceRange().getEnd()))) 4801 return ExprError(); 4802 if (literalType->isVariableArrayType()) 4803 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4804 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 4805 } else if (!literalType->isDependentType() && 4806 RequireCompleteType(LParenLoc, literalType, 4807 PDiag(diag::err_typecheck_decl_incomplete_type) 4808 << SourceRange(LParenLoc, 4809 literalExpr->getSourceRange().getEnd()))) 4810 return ExprError(); 4811 4812 InitializedEntity Entity 4813 = InitializedEntity::InitializeTemporary(literalType); 4814 InitializationKind Kind 4815 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc), 4816 /*IsCStyleCast=*/true); 4817 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1); 4818 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4819 MultiExprArg(*this, &literalExpr, 1), 4820 &literalType); 4821 if (Result.isInvalid()) 4822 return ExprError(); 4823 literalExpr = Result.get(); 4824 4825 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4826 if (isFileScope) { // 6.5.2.5p3 4827 if (CheckForConstantInitializer(literalExpr, literalType)) 4828 return ExprError(); 4829 } 4830 4831 // In C, compound literals are l-values for some reason. 4832 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue; 4833 4834 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4835 VK, literalExpr, isFileScope)); 4836} 4837 4838ExprResult 4839Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 4840 SourceLocation RBraceLoc) { 4841 unsigned NumInit = initlist.size(); 4842 Expr **InitList = initlist.release(); 4843 4844 // Semantic analysis for initializers is done by ActOnDeclarator() and 4845 // CheckInitializer() - it requires knowledge of the object being intialized. 4846 4847 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 4848 NumInit, RBraceLoc); 4849 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4850 return Owned(E); 4851} 4852 4853/// Prepares for a scalar cast, performing all the necessary stages 4854/// except the final cast and returning the kind required. 4855static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) { 4856 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4857 // Also, callers should have filtered out the invalid cases with 4858 // pointers. Everything else should be possible. 4859 4860 QualType SrcTy = Src->getType(); 4861 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4862 return CK_NoOp; 4863 4864 switch (SrcTy->getScalarTypeKind()) { 4865 case Type::STK_MemberPointer: 4866 llvm_unreachable("member pointer type in C"); 4867 4868 case Type::STK_Pointer: 4869 switch (DestTy->getScalarTypeKind()) { 4870 case Type::STK_Pointer: 4871 return DestTy->isObjCObjectPointerType() ? 4872 CK_AnyPointerToObjCPointerCast : 4873 CK_BitCast; 4874 case Type::STK_Bool: 4875 return CK_PointerToBoolean; 4876 case Type::STK_Integral: 4877 return CK_PointerToIntegral; 4878 case Type::STK_Floating: 4879 case Type::STK_FloatingComplex: 4880 case Type::STK_IntegralComplex: 4881 case Type::STK_MemberPointer: 4882 llvm_unreachable("illegal cast from pointer"); 4883 } 4884 break; 4885 4886 case Type::STK_Bool: // casting from bool is like casting from an integer 4887 case Type::STK_Integral: 4888 switch (DestTy->getScalarTypeKind()) { 4889 case Type::STK_Pointer: 4890 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull)) 4891 return CK_NullToPointer; 4892 return CK_IntegralToPointer; 4893 case Type::STK_Bool: 4894 return CK_IntegralToBoolean; 4895 case Type::STK_Integral: 4896 return CK_IntegralCast; 4897 case Type::STK_Floating: 4898 return CK_IntegralToFloating; 4899 case Type::STK_IntegralComplex: 4900 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(), 4901 CK_IntegralCast); 4902 return CK_IntegralRealToComplex; 4903 case Type::STK_FloatingComplex: 4904 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(), 4905 CK_IntegralToFloating); 4906 return CK_FloatingRealToComplex; 4907 case Type::STK_MemberPointer: 4908 llvm_unreachable("member pointer type in C"); 4909 } 4910 break; 4911 4912 case Type::STK_Floating: 4913 switch (DestTy->getScalarTypeKind()) { 4914 case Type::STK_Floating: 4915 return CK_FloatingCast; 4916 case Type::STK_Bool: 4917 return CK_FloatingToBoolean; 4918 case Type::STK_Integral: 4919 return CK_FloatingToIntegral; 4920 case Type::STK_FloatingComplex: 4921 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(), 4922 CK_FloatingCast); 4923 return CK_FloatingRealToComplex; 4924 case Type::STK_IntegralComplex: 4925 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(), 4926 CK_FloatingToIntegral); 4927 return CK_IntegralRealToComplex; 4928 case Type::STK_Pointer: 4929 llvm_unreachable("valid float->pointer cast?"); 4930 case Type::STK_MemberPointer: 4931 llvm_unreachable("member pointer type in C"); 4932 } 4933 break; 4934 4935 case Type::STK_FloatingComplex: 4936 switch (DestTy->getScalarTypeKind()) { 4937 case Type::STK_FloatingComplex: 4938 return CK_FloatingComplexCast; 4939 case Type::STK_IntegralComplex: 4940 return CK_FloatingComplexToIntegralComplex; 4941 case Type::STK_Floating: { 4942 QualType ET = SrcTy->getAs<ComplexType>()->getElementType(); 4943 if (S.Context.hasSameType(ET, DestTy)) 4944 return CK_FloatingComplexToReal; 4945 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal); 4946 return CK_FloatingCast; 4947 } 4948 case Type::STK_Bool: 4949 return CK_FloatingComplexToBoolean; 4950 case Type::STK_Integral: 4951 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(), 4952 CK_FloatingComplexToReal); 4953 return CK_FloatingToIntegral; 4954 case Type::STK_Pointer: 4955 llvm_unreachable("valid complex float->pointer cast?"); 4956 case Type::STK_MemberPointer: 4957 llvm_unreachable("member pointer type in C"); 4958 } 4959 break; 4960 4961 case Type::STK_IntegralComplex: 4962 switch (DestTy->getScalarTypeKind()) { 4963 case Type::STK_FloatingComplex: 4964 return CK_IntegralComplexToFloatingComplex; 4965 case Type::STK_IntegralComplex: 4966 return CK_IntegralComplexCast; 4967 case Type::STK_Integral: { 4968 QualType ET = SrcTy->getAs<ComplexType>()->getElementType(); 4969 if (S.Context.hasSameType(ET, DestTy)) 4970 return CK_IntegralComplexToReal; 4971 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal); 4972 return CK_IntegralCast; 4973 } 4974 case Type::STK_Bool: 4975 return CK_IntegralComplexToBoolean; 4976 case Type::STK_Floating: 4977 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(), 4978 CK_IntegralComplexToReal); 4979 return CK_IntegralToFloating; 4980 case Type::STK_Pointer: 4981 llvm_unreachable("valid complex int->pointer cast?"); 4982 case Type::STK_MemberPointer: 4983 llvm_unreachable("member pointer type in C"); 4984 } 4985 break; 4986 } 4987 4988 llvm_unreachable("Unhandled scalar cast"); 4989 return CK_BitCast; 4990} 4991 4992/// CheckCastTypes - Check type constraints for casting between types. 4993bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, 4994 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK, 4995 CXXCastPath &BasePath, bool FunctionalStyle) { 4996 if (getLangOptions().CPlusPlus) 4997 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(), 4998 castExpr->getLocEnd()), 4999 castType, VK, castExpr, Kind, BasePath, 5000 FunctionalStyle); 5001 5002 // We only support r-value casts in C. 5003 VK = VK_RValue; 5004 5005 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 5006 // type needs to be scalar. 5007 if (castType->isVoidType()) { 5008 // We don't necessarily do lvalue-to-rvalue conversions on this. 5009 IgnoredValueConversions(castExpr); 5010 5011 // Cast to void allows any expr type. 5012 Kind = CK_ToVoid; 5013 return false; 5014 } 5015 5016 DefaultFunctionArrayLvalueConversion(castExpr); 5017 5018 if (RequireCompleteType(TyR.getBegin(), castType, 5019 diag::err_typecheck_cast_to_incomplete)) 5020 return true; 5021 5022 if (!castType->isScalarType() && !castType->isVectorType()) { 5023 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 5024 (castType->isStructureType() || castType->isUnionType())) { 5025 // GCC struct/union extension: allow cast to self. 5026 // FIXME: Check that the cast destination type is complete. 5027 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 5028 << castType << castExpr->getSourceRange(); 5029 Kind = CK_NoOp; 5030 return false; 5031 } 5032 5033 if (castType->isUnionType()) { 5034 // GCC cast to union extension 5035 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 5036 RecordDecl::field_iterator Field, FieldEnd; 5037 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 5038 Field != FieldEnd; ++Field) { 5039 if (Context.hasSameUnqualifiedType(Field->getType(), 5040 castExpr->getType()) && 5041 !Field->isUnnamedBitfield()) { 5042 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 5043 << castExpr->getSourceRange(); 5044 break; 5045 } 5046 } 5047 if (Field == FieldEnd) 5048 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 5049 << castExpr->getType() << castExpr->getSourceRange(); 5050 Kind = CK_ToUnion; 5051 return false; 5052 } 5053 5054 // Reject any other conversions to non-scalar types. 5055 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 5056 << castType << castExpr->getSourceRange(); 5057 } 5058 5059 // The type we're casting to is known to be a scalar or vector. 5060 5061 // Require the operand to be a scalar or vector. 5062 if (!castExpr->getType()->isScalarType() && 5063 !castExpr->getType()->isVectorType()) { 5064 return Diag(castExpr->getLocStart(), 5065 diag::err_typecheck_expect_scalar_operand) 5066 << castExpr->getType() << castExpr->getSourceRange(); 5067 } 5068 5069 if (castType->isExtVectorType()) 5070 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 5071 5072 if (castType->isVectorType()) 5073 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind); 5074 if (castExpr->getType()->isVectorType()) 5075 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind); 5076 5077 // The source and target types are both scalars, i.e. 5078 // - arithmetic types (fundamental, enum, and complex) 5079 // - all kinds of pointers 5080 // Note that member pointers were filtered out with C++, above. 5081 5082 if (isa<ObjCSelectorExpr>(castExpr)) 5083 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 5084 5085 // If either type is a pointer, the other type has to be either an 5086 // integer or a pointer. 5087 if (!castType->isArithmeticType()) { 5088 QualType castExprType = castExpr->getType(); 5089 if (!castExprType->isIntegralType(Context) && 5090 castExprType->isArithmeticType()) 5091 return Diag(castExpr->getLocStart(), 5092 diag::err_cast_pointer_from_non_pointer_int) 5093 << castExprType << castExpr->getSourceRange(); 5094 } else if (!castExpr->getType()->isArithmeticType()) { 5095 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) 5096 return Diag(castExpr->getLocStart(), 5097 diag::err_cast_pointer_to_non_pointer_int) 5098 << castType << castExpr->getSourceRange(); 5099 } 5100 5101 Kind = PrepareScalarCast(*this, castExpr, castType); 5102 5103 if (Kind == CK_BitCast) 5104 CheckCastAlign(castExpr, castType, TyR); 5105 5106 return false; 5107} 5108 5109bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5110 CastKind &Kind) { 5111 assert(VectorTy->isVectorType() && "Not a vector type!"); 5112 5113 if (Ty->isVectorType() || Ty->isIntegerType()) { 5114 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 5115 return Diag(R.getBegin(), 5116 Ty->isVectorType() ? 5117 diag::err_invalid_conversion_between_vectors : 5118 diag::err_invalid_conversion_between_vector_and_integer) 5119 << VectorTy << Ty << R; 5120 } else 5121 return Diag(R.getBegin(), 5122 diag::err_invalid_conversion_between_vector_and_scalar) 5123 << VectorTy << Ty << R; 5124 5125 Kind = CK_BitCast; 5126 return false; 5127} 5128 5129bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 5130 CastKind &Kind) { 5131 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5132 5133 QualType SrcTy = CastExpr->getType(); 5134 5135 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5136 // an ExtVectorType. 5137 if (SrcTy->isVectorType()) { 5138 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 5139 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5140 << DestTy << SrcTy << R; 5141 Kind = CK_BitCast; 5142 return false; 5143 } 5144 5145 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5146 // conversion will take place first from scalar to elt type, and then 5147 // splat from elt type to vector. 5148 if (SrcTy->isPointerType()) 5149 return Diag(R.getBegin(), 5150 diag::err_invalid_conversion_between_vector_and_scalar) 5151 << DestTy << SrcTy << R; 5152 5153 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5154 ImpCastExprToType(CastExpr, DestElemTy, 5155 PrepareScalarCast(*this, CastExpr, DestElemTy)); 5156 5157 Kind = CK_VectorSplat; 5158 return false; 5159} 5160 5161ExprResult 5162Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty, 5163 SourceLocation RParenLoc, Expr *castExpr) { 5164 assert((Ty != 0) && (castExpr != 0) && 5165 "ActOnCastExpr(): missing type or expr"); 5166 5167 TypeSourceInfo *castTInfo; 5168 QualType castType = GetTypeFromParser(Ty, &castTInfo); 5169 if (!castTInfo) 5170 castTInfo = Context.getTrivialTypeSourceInfo(castType); 5171 5172 // If the Expr being casted is a ParenListExpr, handle it specially. 5173 if (isa<ParenListExpr>(castExpr)) 5174 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr, 5175 castTInfo); 5176 5177 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr); 5178} 5179 5180ExprResult 5181Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 5182 SourceLocation RParenLoc, Expr *castExpr) { 5183 CastKind Kind = CK_Invalid; 5184 ExprValueKind VK = VK_RValue; 5185 CXXCastPath BasePath; 5186 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr, 5187 Kind, VK, BasePath)) 5188 return ExprError(); 5189 5190 return Owned(CStyleCastExpr::Create(Context, 5191 Ty->getType().getNonLValueExprType(Context), 5192 VK, Kind, castExpr, &BasePath, Ty, 5193 LParenLoc, RParenLoc)); 5194} 5195 5196/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 5197/// of comma binary operators. 5198ExprResult 5199Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) { 5200 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 5201 if (!E) 5202 return Owned(expr); 5203 5204 ExprResult Result(E->getExpr(0)); 5205 5206 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5207 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5208 E->getExpr(i)); 5209 5210 if (Result.isInvalid()) return ExprError(); 5211 5212 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5213} 5214 5215ExprResult 5216Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 5217 SourceLocation RParenLoc, Expr *Op, 5218 TypeSourceInfo *TInfo) { 5219 ParenListExpr *PE = cast<ParenListExpr>(Op); 5220 QualType Ty = TInfo->getType(); 5221 bool isAltiVecLiteral = false; 5222 5223 // Check for an altivec literal, 5224 // i.e. all the elements are integer constants. 5225 if (getLangOptions().AltiVec && Ty->isVectorType()) { 5226 if (PE->getNumExprs() == 0) { 5227 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 5228 return ExprError(); 5229 } 5230 if (PE->getNumExprs() == 1) { 5231 if (!PE->getExpr(0)->getType()->isVectorType()) 5232 isAltiVecLiteral = true; 5233 } 5234 else 5235 isAltiVecLiteral = true; 5236 } 5237 5238 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 5239 // then handle it as such. 5240 if (isAltiVecLiteral) { 5241 llvm::SmallVector<Expr *, 8> initExprs; 5242 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 5243 initExprs.push_back(PE->getExpr(i)); 5244 5245 // FIXME: This means that pretty-printing the final AST will produce curly 5246 // braces instead of the original commas. 5247 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc, 5248 &initExprs[0], 5249 initExprs.size(), RParenLoc); 5250 E->setType(Ty); 5251 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E); 5252 } else { 5253 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5254 // sequence of BinOp comma operators. 5255 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op); 5256 if (Result.isInvalid()) return ExprError(); 5257 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take()); 5258 } 5259} 5260 5261ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 5262 SourceLocation R, 5263 MultiExprArg Val, 5264 ParsedType TypeOfCast) { 5265 unsigned nexprs = Val.size(); 5266 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 5267 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 5268 Expr *expr; 5269 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast)) 5270 expr = new (Context) ParenExpr(L, R, exprs[0]); 5271 else 5272 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 5273 return Owned(expr); 5274} 5275 5276/// \brief Emit a specialized diagnostic when one expression is a null pointer 5277/// constant and the other is not a pointer. 5278bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS, 5279 SourceLocation QuestionLoc) { 5280 Expr *NullExpr = LHS; 5281 Expr *NonPointerExpr = RHS; 5282 Expr::NullPointerConstantKind NullKind = 5283 NullExpr->isNullPointerConstant(Context, 5284 Expr::NPC_ValueDependentIsNotNull); 5285 5286 if (NullKind == Expr::NPCK_NotNull) { 5287 NullExpr = RHS; 5288 NonPointerExpr = LHS; 5289 NullKind = 5290 NullExpr->isNullPointerConstant(Context, 5291 Expr::NPC_ValueDependentIsNotNull); 5292 } 5293 5294 if (NullKind == Expr::NPCK_NotNull) 5295 return false; 5296 5297 if (NullKind == Expr::NPCK_ZeroInteger) { 5298 // In this case, check to make sure that we got here from a "NULL" 5299 // string in the source code. 5300 NullExpr = NullExpr->IgnoreParenImpCasts(); 5301 SourceLocation loc = NullExpr->getExprLoc(); 5302 if (!findMacroSpelling(loc, "NULL")) 5303 return false; 5304 } 5305 5306 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 5307 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5308 << NonPointerExpr->getType() << DiagType 5309 << NonPointerExpr->getSourceRange(); 5310 return true; 5311} 5312 5313/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 5314/// In that case, lhs = cond. 5315/// C99 6.5.15 5316QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 5317 ExprValueKind &VK, ExprObjectKind &OK, 5318 SourceLocation QuestionLoc) { 5319 // If both LHS and RHS are overloaded functions, try to resolve them. 5320 if (Context.hasSameType(LHS->getType(), RHS->getType()) && 5321 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) { 5322 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc); 5323 if (LHSResult.isInvalid()) 5324 return QualType(); 5325 5326 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc); 5327 if (RHSResult.isInvalid()) 5328 return QualType(); 5329 5330 LHS = LHSResult.take(); 5331 RHS = RHSResult.take(); 5332 } 5333 5334 // C++ is sufficiently different to merit its own checker. 5335 if (getLangOptions().CPlusPlus) 5336 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5337 5338 VK = VK_RValue; 5339 OK = OK_Ordinary; 5340 5341 UsualUnaryConversions(Cond); 5342 UsualUnaryConversions(LHS); 5343 UsualUnaryConversions(RHS); 5344 QualType CondTy = Cond->getType(); 5345 QualType LHSTy = LHS->getType(); 5346 QualType RHSTy = RHS->getType(); 5347 5348 // first, check the condition. 5349 if (!CondTy->isScalarType()) { // C99 6.5.15p2 5350 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 5351 // Throw an error if its not either. 5352 if (getLangOptions().OpenCL) { 5353 if (!CondTy->isVectorType()) { 5354 Diag(Cond->getLocStart(), 5355 diag::err_typecheck_cond_expect_scalar_or_vector) 5356 << CondTy; 5357 return QualType(); 5358 } 5359 } 5360 else { 5361 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5362 << CondTy; 5363 return QualType(); 5364 } 5365 } 5366 5367 // Now check the two expressions. 5368 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5369 return CheckVectorOperands(QuestionLoc, LHS, RHS); 5370 5371 // OpenCL: If the condition is a vector, and both operands are scalar, 5372 // attempt to implicity convert them to the vector type to act like the 5373 // built in select. 5374 if (getLangOptions().OpenCL && CondTy->isVectorType()) { 5375 // Both operands should be of scalar type. 5376 if (!LHSTy->isScalarType()) { 5377 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5378 << CondTy; 5379 return QualType(); 5380 } 5381 if (!RHSTy->isScalarType()) { 5382 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5383 << CondTy; 5384 return QualType(); 5385 } 5386 // Implicity convert these scalars to the type of the condition. 5387 ImpCastExprToType(LHS, CondTy, CK_IntegralCast); 5388 ImpCastExprToType(RHS, CondTy, CK_IntegralCast); 5389 } 5390 5391 // If both operands have arithmetic type, do the usual arithmetic conversions 5392 // to find a common type: C99 6.5.15p3,5. 5393 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5394 UsualArithmeticConversions(LHS, RHS); 5395 return LHS->getType(); 5396 } 5397 5398 // If both operands are the same structure or union type, the result is that 5399 // type. 5400 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5401 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5402 if (LHSRT->getDecl() == RHSRT->getDecl()) 5403 // "If both the operands have structure or union type, the result has 5404 // that type." This implies that CV qualifiers are dropped. 5405 return LHSTy.getUnqualifiedType(); 5406 // FIXME: Type of conditional expression must be complete in C mode. 5407 } 5408 5409 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5410 // The following || allows only one side to be void (a GCC-ism). 5411 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5412 if (!LHSTy->isVoidType()) 5413 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 5414 << RHS->getSourceRange(); 5415 if (!RHSTy->isVoidType()) 5416 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 5417 << LHS->getSourceRange(); 5418 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid); 5419 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid); 5420 return Context.VoidTy; 5421 } 5422 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5423 // the type of the other operand." 5424 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 5425 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 5426 // promote the null to a pointer. 5427 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer); 5428 return LHSTy; 5429 } 5430 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 5431 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 5432 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer); 5433 return RHSTy; 5434 } 5435 5436 // All objective-c pointer type analysis is done here. 5437 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5438 QuestionLoc); 5439 if (!compositeType.isNull()) 5440 return compositeType; 5441 5442 5443 // Handle block pointer types. 5444 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 5445 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5446 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5447 QualType destType = Context.getPointerType(Context.VoidTy); 5448 ImpCastExprToType(LHS, destType, CK_BitCast); 5449 ImpCastExprToType(RHS, destType, CK_BitCast); 5450 return destType; 5451 } 5452 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5453 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5454 return QualType(); 5455 } 5456 // We have 2 block pointer types. 5457 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5458 // Two identical block pointer types are always compatible. 5459 return LHSTy; 5460 } 5461 // The block pointer types aren't identical, continue checking. 5462 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 5463 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 5464 5465 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 5466 rhptee.getUnqualifiedType())) { 5467 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 5468 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5469 // In this situation, we assume void* type. No especially good 5470 // reason, but this is what gcc does, and we do have to pick 5471 // to get a consistent AST. 5472 QualType incompatTy = Context.getPointerType(Context.VoidTy); 5473 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 5474 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 5475 return incompatTy; 5476 } 5477 // The block pointer types are compatible. 5478 ImpCastExprToType(LHS, LHSTy, CK_BitCast); 5479 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 5480 return LHSTy; 5481 } 5482 5483 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5484 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 5485 // get the "pointed to" types 5486 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5487 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5488 5489 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5490 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5491 // Figure out necessary qualifiers (C99 6.5.15p6) 5492 QualType destPointee 5493 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5494 QualType destType = Context.getPointerType(destPointee); 5495 // Add qualifiers if necessary. 5496 ImpCastExprToType(LHS, destType, CK_NoOp); 5497 // Promote to void*. 5498 ImpCastExprToType(RHS, destType, CK_BitCast); 5499 return destType; 5500 } 5501 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5502 QualType destPointee 5503 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5504 QualType destType = Context.getPointerType(destPointee); 5505 // Add qualifiers if necessary. 5506 ImpCastExprToType(RHS, destType, CK_NoOp); 5507 // Promote to void*. 5508 ImpCastExprToType(LHS, destType, CK_BitCast); 5509 return destType; 5510 } 5511 5512 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5513 // Two identical pointer types are always compatible. 5514 return LHSTy; 5515 } 5516 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 5517 rhptee.getUnqualifiedType())) { 5518 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 5519 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5520 // In this situation, we assume void* type. No especially good 5521 // reason, but this is what gcc does, and we do have to pick 5522 // to get a consistent AST. 5523 QualType incompatTy = Context.getPointerType(Context.VoidTy); 5524 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 5525 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 5526 return incompatTy; 5527 } 5528 // The pointer types are compatible. 5529 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 5530 // differently qualified versions of compatible types, the result type is 5531 // a pointer to an appropriately qualified version of the *composite* 5532 // type. 5533 // FIXME: Need to calculate the composite type. 5534 // FIXME: Need to add qualifiers 5535 ImpCastExprToType(LHS, LHSTy, CK_BitCast); 5536 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 5537 return LHSTy; 5538 } 5539 5540 // GCC compatibility: soften pointer/integer mismatch. Note that 5541 // null pointers have been filtered out by this point. 5542 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 5543 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5544 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5545 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer); 5546 return RHSTy; 5547 } 5548 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 5549 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5550 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5551 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer); 5552 return LHSTy; 5553 } 5554 5555 // Emit a better diagnostic if one of the expressions is a null pointer 5556 // constant and the other is not a pointer type. In this case, the user most 5557 // likely forgot to take the address of the other expression. 5558 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc)) 5559 return QualType(); 5560 5561 // Otherwise, the operands are not compatible. 5562 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5563 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 5564 return QualType(); 5565} 5566 5567/// FindCompositeObjCPointerType - Helper method to find composite type of 5568/// two objective-c pointer types of the two input expressions. 5569QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS, 5570 SourceLocation QuestionLoc) { 5571 QualType LHSTy = LHS->getType(); 5572 QualType RHSTy = RHS->getType(); 5573 5574 // Handle things like Class and struct objc_class*. Here we case the result 5575 // to the pseudo-builtin, because that will be implicitly cast back to the 5576 // redefinition type if an attempt is made to access its fields. 5577 if (LHSTy->isObjCClassType() && 5578 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) { 5579 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 5580 return LHSTy; 5581 } 5582 if (RHSTy->isObjCClassType() && 5583 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) { 5584 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 5585 return RHSTy; 5586 } 5587 // And the same for struct objc_object* / id 5588 if (LHSTy->isObjCIdType() && 5589 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) { 5590 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 5591 return LHSTy; 5592 } 5593 if (RHSTy->isObjCIdType() && 5594 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) { 5595 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 5596 return RHSTy; 5597 } 5598 // And the same for struct objc_selector* / SEL 5599 if (Context.isObjCSelType(LHSTy) && 5600 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) { 5601 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 5602 return LHSTy; 5603 } 5604 if (Context.isObjCSelType(RHSTy) && 5605 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) { 5606 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 5607 return RHSTy; 5608 } 5609 // Check constraints for Objective-C object pointers types. 5610 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5611 5612 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5613 // Two identical object pointer types are always compatible. 5614 return LHSTy; 5615 } 5616 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 5617 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 5618 QualType compositeType = LHSTy; 5619 5620 // If both operands are interfaces and either operand can be 5621 // assigned to the other, use that type as the composite 5622 // type. This allows 5623 // xxx ? (A*) a : (B*) b 5624 // where B is a subclass of A. 5625 // 5626 // Additionally, as for assignment, if either type is 'id' 5627 // allow silent coercion. Finally, if the types are 5628 // incompatible then make sure to use 'id' as the composite 5629 // type so the result is acceptable for sending messages to. 5630 5631 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5632 // It could return the composite type. 5633 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5634 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5635 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5636 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5637 } else if ((LHSTy->isObjCQualifiedIdType() || 5638 RHSTy->isObjCQualifiedIdType()) && 5639 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5640 // Need to handle "id<xx>" explicitly. 5641 // GCC allows qualified id and any Objective-C type to devolve to 5642 // id. Currently localizing to here until clear this should be 5643 // part of ObjCQualifiedIdTypesAreCompatible. 5644 compositeType = Context.getObjCIdType(); 5645 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5646 compositeType = Context.getObjCIdType(); 5647 } else if (!(compositeType = 5648 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5649 ; 5650 else { 5651 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5652 << LHSTy << RHSTy 5653 << LHS->getSourceRange() << RHS->getSourceRange(); 5654 QualType incompatTy = Context.getObjCIdType(); 5655 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 5656 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 5657 return incompatTy; 5658 } 5659 // The object pointer types are compatible. 5660 ImpCastExprToType(LHS, compositeType, CK_BitCast); 5661 ImpCastExprToType(RHS, compositeType, CK_BitCast); 5662 return compositeType; 5663 } 5664 // Check Objective-C object pointer types and 'void *' 5665 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5666 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5667 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5668 QualType destPointee 5669 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5670 QualType destType = Context.getPointerType(destPointee); 5671 // Add qualifiers if necessary. 5672 ImpCastExprToType(LHS, destType, CK_NoOp); 5673 // Promote to void*. 5674 ImpCastExprToType(RHS, destType, CK_BitCast); 5675 return destType; 5676 } 5677 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5678 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5679 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5680 QualType destPointee 5681 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5682 QualType destType = Context.getPointerType(destPointee); 5683 // Add qualifiers if necessary. 5684 ImpCastExprToType(RHS, destType, CK_NoOp); 5685 // Promote to void*. 5686 ImpCastExprToType(LHS, destType, CK_BitCast); 5687 return destType; 5688 } 5689 return QualType(); 5690} 5691 5692/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5693/// in the case of a the GNU conditional expr extension. 5694ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5695 SourceLocation ColonLoc, 5696 Expr *CondExpr, Expr *LHSExpr, 5697 Expr *RHSExpr) { 5698 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5699 // was the condition. 5700 OpaqueValueExpr *opaqueValue = 0; 5701 Expr *commonExpr = 0; 5702 if (LHSExpr == 0) { 5703 commonExpr = CondExpr; 5704 5705 // We usually want to apply unary conversions *before* saving, except 5706 // in the special case of a C++ l-value conditional. 5707 if (!(getLangOptions().CPlusPlus 5708 && !commonExpr->isTypeDependent() 5709 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5710 && commonExpr->isGLValue() 5711 && commonExpr->isOrdinaryOrBitFieldObject() 5712 && RHSExpr->isOrdinaryOrBitFieldObject() 5713 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5714 UsualUnaryConversions(commonExpr); 5715 } 5716 5717 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5718 commonExpr->getType(), 5719 commonExpr->getValueKind(), 5720 commonExpr->getObjectKind()); 5721 LHSExpr = CondExpr = opaqueValue; 5722 } 5723 5724 ExprValueKind VK = VK_RValue; 5725 ExprObjectKind OK = OK_Ordinary; 5726 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr, 5727 VK, OK, QuestionLoc); 5728 if (result.isNull()) 5729 return ExprError(); 5730 5731 if (!commonExpr) 5732 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 5733 LHSExpr, ColonLoc, 5734 RHSExpr, result, VK, OK)); 5735 5736 return Owned(new (Context) 5737 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr, 5738 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK)); 5739} 5740 5741// checkPointerTypesForAssignment - This is a very tricky routine (despite 5742// being closely modeled after the C99 spec:-). The odd characteristic of this 5743// routine is it effectively iqnores the qualifiers on the top level pointee. 5744// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5745// FIXME: add a couple examples in this comment. 5746static Sema::AssignConvertType 5747checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) { 5748 assert(lhsType.isCanonical() && "LHS not canonicalized!"); 5749 assert(rhsType.isCanonical() && "RHS not canonicalized!"); 5750 5751 // get the "pointed to" type (ignoring qualifiers at the top level) 5752 const Type *lhptee, *rhptee; 5753 Qualifiers lhq, rhq; 5754 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split(); 5755 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split(); 5756 5757 Sema::AssignConvertType ConvTy = Sema::Compatible; 5758 5759 // C99 6.5.16.1p1: This following citation is common to constraints 5760 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5761 // qualifiers of the type *pointed to* by the right; 5762 Qualifiers lq; 5763 5764 if (!lhq.compatiblyIncludes(rhq)) { 5765 // Treat address-space mismatches as fatal. TODO: address subspaces 5766 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5767 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5768 5769 // For GCC compatibility, other qualifier mismatches are treated 5770 // as still compatible in C. 5771 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5772 } 5773 5774 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5775 // incomplete type and the other is a pointer to a qualified or unqualified 5776 // version of void... 5777 if (lhptee->isVoidType()) { 5778 if (rhptee->isIncompleteOrObjectType()) 5779 return ConvTy; 5780 5781 // As an extension, we allow cast to/from void* to function pointer. 5782 assert(rhptee->isFunctionType()); 5783 return Sema::FunctionVoidPointer; 5784 } 5785 5786 if (rhptee->isVoidType()) { 5787 if (lhptee->isIncompleteOrObjectType()) 5788 return ConvTy; 5789 5790 // As an extension, we allow cast to/from void* to function pointer. 5791 assert(lhptee->isFunctionType()); 5792 return Sema::FunctionVoidPointer; 5793 } 5794 5795 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5796 // unqualified versions of compatible types, ... 5797 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5798 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5799 // Check if the pointee types are compatible ignoring the sign. 5800 // We explicitly check for char so that we catch "char" vs 5801 // "unsigned char" on systems where "char" is unsigned. 5802 if (lhptee->isCharType()) 5803 ltrans = S.Context.UnsignedCharTy; 5804 else if (lhptee->hasSignedIntegerRepresentation()) 5805 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5806 5807 if (rhptee->isCharType()) 5808 rtrans = S.Context.UnsignedCharTy; 5809 else if (rhptee->hasSignedIntegerRepresentation()) 5810 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5811 5812 if (ltrans == rtrans) { 5813 // Types are compatible ignoring the sign. Qualifier incompatibility 5814 // takes priority over sign incompatibility because the sign 5815 // warning can be disabled. 5816 if (ConvTy != Sema::Compatible) 5817 return ConvTy; 5818 5819 return Sema::IncompatiblePointerSign; 5820 } 5821 5822 // If we are a multi-level pointer, it's possible that our issue is simply 5823 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5824 // the eventual target type is the same and the pointers have the same 5825 // level of indirection, this must be the issue. 5826 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5827 do { 5828 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5829 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5830 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5831 5832 if (lhptee == rhptee) 5833 return Sema::IncompatibleNestedPointerQualifiers; 5834 } 5835 5836 // General pointer incompatibility takes priority over qualifiers. 5837 return Sema::IncompatiblePointer; 5838 } 5839 return ConvTy; 5840} 5841 5842/// checkBlockPointerTypesForAssignment - This routine determines whether two 5843/// block pointer types are compatible or whether a block and normal pointer 5844/// are compatible. It is more restrict than comparing two function pointer 5845// types. 5846static Sema::AssignConvertType 5847checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType, 5848 QualType rhsType) { 5849 assert(lhsType.isCanonical() && "LHS not canonicalized!"); 5850 assert(rhsType.isCanonical() && "RHS not canonicalized!"); 5851 5852 QualType lhptee, rhptee; 5853 5854 // get the "pointed to" type (ignoring qualifiers at the top level) 5855 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType(); 5856 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType(); 5857 5858 // In C++, the types have to match exactly. 5859 if (S.getLangOptions().CPlusPlus) 5860 return Sema::IncompatibleBlockPointer; 5861 5862 Sema::AssignConvertType ConvTy = Sema::Compatible; 5863 5864 // For blocks we enforce that qualifiers are identical. 5865 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5866 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5867 5868 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType)) 5869 return Sema::IncompatibleBlockPointer; 5870 5871 return ConvTy; 5872} 5873 5874/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5875/// for assignment compatibility. 5876static Sema::AssignConvertType 5877checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) { 5878 assert(lhsType.isCanonical() && "LHS was not canonicalized!"); 5879 assert(rhsType.isCanonical() && "RHS was not canonicalized!"); 5880 5881 if (lhsType->isObjCBuiltinType()) { 5882 // Class is not compatible with ObjC object pointers. 5883 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() && 5884 !rhsType->isObjCQualifiedClassType()) 5885 return Sema::IncompatiblePointer; 5886 return Sema::Compatible; 5887 } 5888 if (rhsType->isObjCBuiltinType()) { 5889 // Class is not compatible with ObjC object pointers. 5890 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() && 5891 !lhsType->isObjCQualifiedClassType()) 5892 return Sema::IncompatiblePointer; 5893 return Sema::Compatible; 5894 } 5895 QualType lhptee = 5896 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5897 QualType rhptee = 5898 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5899 5900 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 5901 return Sema::CompatiblePointerDiscardsQualifiers; 5902 5903 if (S.Context.typesAreCompatible(lhsType, rhsType)) 5904 return Sema::Compatible; 5905 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 5906 return Sema::IncompatibleObjCQualifiedId; 5907 return Sema::IncompatiblePointer; 5908} 5909 5910Sema::AssignConvertType 5911Sema::CheckAssignmentConstraints(SourceLocation Loc, 5912 QualType lhsType, QualType rhsType) { 5913 // Fake up an opaque expression. We don't actually care about what 5914 // cast operations are required, so if CheckAssignmentConstraints 5915 // adds casts to this they'll be wasted, but fortunately that doesn't 5916 // usually happen on valid code. 5917 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue); 5918 Expr *rhsPtr = &rhs; 5919 CastKind K = CK_Invalid; 5920 5921 return CheckAssignmentConstraints(lhsType, rhsPtr, K); 5922} 5923 5924/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5925/// has code to accommodate several GCC extensions when type checking 5926/// pointers. Here are some objectionable examples that GCC considers warnings: 5927/// 5928/// int a, *pint; 5929/// short *pshort; 5930/// struct foo *pfoo; 5931/// 5932/// pint = pshort; // warning: assignment from incompatible pointer type 5933/// a = pint; // warning: assignment makes integer from pointer without a cast 5934/// pint = a; // warning: assignment makes pointer from integer without a cast 5935/// pint = pfoo; // warning: assignment from incompatible pointer type 5936/// 5937/// As a result, the code for dealing with pointers is more complex than the 5938/// C99 spec dictates. 5939/// 5940/// Sets 'Kind' for any result kind except Incompatible. 5941Sema::AssignConvertType 5942Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs, 5943 CastKind &Kind) { 5944 QualType rhsType = rhs->getType(); 5945 5946 // Get canonical types. We're not formatting these types, just comparing 5947 // them. 5948 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 5949 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 5950 5951 // Common case: no conversion required. 5952 if (lhsType == rhsType) { 5953 Kind = CK_NoOp; 5954 return Compatible; 5955 } 5956 5957 // If the left-hand side is a reference type, then we are in a 5958 // (rare!) case where we've allowed the use of references in C, 5959 // e.g., as a parameter type in a built-in function. In this case, 5960 // just make sure that the type referenced is compatible with the 5961 // right-hand side type. The caller is responsible for adjusting 5962 // lhsType so that the resulting expression does not have reference 5963 // type. 5964 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 5965 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) { 5966 Kind = CK_LValueBitCast; 5967 return Compatible; 5968 } 5969 return Incompatible; 5970 } 5971 5972 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5973 // to the same ExtVector type. 5974 if (lhsType->isExtVectorType()) { 5975 if (rhsType->isExtVectorType()) 5976 return Incompatible; 5977 if (rhsType->isArithmeticType()) { 5978 // CK_VectorSplat does T -> vector T, so first cast to the 5979 // element type. 5980 QualType elType = cast<ExtVectorType>(lhsType)->getElementType(); 5981 if (elType != rhsType) { 5982 Kind = PrepareScalarCast(*this, rhs, elType); 5983 ImpCastExprToType(rhs, elType, Kind); 5984 } 5985 Kind = CK_VectorSplat; 5986 return Compatible; 5987 } 5988 } 5989 5990 // Conversions to or from vector type. 5991 if (lhsType->isVectorType() || rhsType->isVectorType()) { 5992 if (lhsType->isVectorType() && rhsType->isVectorType()) { 5993 // Allow assignments of an AltiVec vector type to an equivalent GCC 5994 // vector type and vice versa 5995 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) { 5996 Kind = CK_BitCast; 5997 return Compatible; 5998 } 5999 6000 // If we are allowing lax vector conversions, and LHS and RHS are both 6001 // vectors, the total size only needs to be the same. This is a bitcast; 6002 // no bits are changed but the result type is different. 6003 if (getLangOptions().LaxVectorConversions && 6004 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) { 6005 Kind = CK_BitCast; 6006 return IncompatibleVectors; 6007 } 6008 } 6009 return Incompatible; 6010 } 6011 6012 // Arithmetic conversions. 6013 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() && 6014 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) { 6015 Kind = PrepareScalarCast(*this, rhs, lhsType); 6016 return Compatible; 6017 } 6018 6019 // Conversions to normal pointers. 6020 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) { 6021 // U* -> T* 6022 if (isa<PointerType>(rhsType)) { 6023 Kind = CK_BitCast; 6024 return checkPointerTypesForAssignment(*this, lhsType, rhsType); 6025 } 6026 6027 // int -> T* 6028 if (rhsType->isIntegerType()) { 6029 Kind = CK_IntegralToPointer; // FIXME: null? 6030 return IntToPointer; 6031 } 6032 6033 // C pointers are not compatible with ObjC object pointers, 6034 // with two exceptions: 6035 if (isa<ObjCObjectPointerType>(rhsType)) { 6036 // - conversions to void* 6037 if (lhsPointer->getPointeeType()->isVoidType()) { 6038 Kind = CK_AnyPointerToObjCPointerCast; 6039 return Compatible; 6040 } 6041 6042 // - conversions from 'Class' to the redefinition type 6043 if (rhsType->isObjCClassType() && 6044 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) { 6045 Kind = CK_BitCast; 6046 return Compatible; 6047 } 6048 6049 Kind = CK_BitCast; 6050 return IncompatiblePointer; 6051 } 6052 6053 // U^ -> void* 6054 if (rhsType->getAs<BlockPointerType>()) { 6055 if (lhsPointer->getPointeeType()->isVoidType()) { 6056 Kind = CK_BitCast; 6057 return Compatible; 6058 } 6059 } 6060 6061 return Incompatible; 6062 } 6063 6064 // Conversions to block pointers. 6065 if (isa<BlockPointerType>(lhsType)) { 6066 // U^ -> T^ 6067 if (rhsType->isBlockPointerType()) { 6068 Kind = CK_AnyPointerToBlockPointerCast; 6069 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType); 6070 } 6071 6072 // int or null -> T^ 6073 if (rhsType->isIntegerType()) { 6074 Kind = CK_IntegralToPointer; // FIXME: null 6075 return IntToBlockPointer; 6076 } 6077 6078 // id -> T^ 6079 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) { 6080 Kind = CK_AnyPointerToBlockPointerCast; 6081 return Compatible; 6082 } 6083 6084 // void* -> T^ 6085 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) 6086 if (RHSPT->getPointeeType()->isVoidType()) { 6087 Kind = CK_AnyPointerToBlockPointerCast; 6088 return Compatible; 6089 } 6090 6091 return Incompatible; 6092 } 6093 6094 // Conversions to Objective-C pointers. 6095 if (isa<ObjCObjectPointerType>(lhsType)) { 6096 // A* -> B* 6097 if (rhsType->isObjCObjectPointerType()) { 6098 Kind = CK_BitCast; 6099 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType); 6100 } 6101 6102 // int or null -> A* 6103 if (rhsType->isIntegerType()) { 6104 Kind = CK_IntegralToPointer; // FIXME: null 6105 return IntToPointer; 6106 } 6107 6108 // In general, C pointers are not compatible with ObjC object pointers, 6109 // with two exceptions: 6110 if (isa<PointerType>(rhsType)) { 6111 // - conversions from 'void*' 6112 if (rhsType->isVoidPointerType()) { 6113 Kind = CK_AnyPointerToObjCPointerCast; 6114 return Compatible; 6115 } 6116 6117 // - conversions to 'Class' from its redefinition type 6118 if (lhsType->isObjCClassType() && 6119 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) { 6120 Kind = CK_BitCast; 6121 return Compatible; 6122 } 6123 6124 Kind = CK_AnyPointerToObjCPointerCast; 6125 return IncompatiblePointer; 6126 } 6127 6128 // T^ -> A* 6129 if (rhsType->isBlockPointerType()) { 6130 Kind = CK_AnyPointerToObjCPointerCast; 6131 return Compatible; 6132 } 6133 6134 return Incompatible; 6135 } 6136 6137 // Conversions from pointers that are not covered by the above. 6138 if (isa<PointerType>(rhsType)) { 6139 // T* -> _Bool 6140 if (lhsType == Context.BoolTy) { 6141 Kind = CK_PointerToBoolean; 6142 return Compatible; 6143 } 6144 6145 // T* -> int 6146 if (lhsType->isIntegerType()) { 6147 Kind = CK_PointerToIntegral; 6148 return PointerToInt; 6149 } 6150 6151 return Incompatible; 6152 } 6153 6154 // Conversions from Objective-C pointers that are not covered by the above. 6155 if (isa<ObjCObjectPointerType>(rhsType)) { 6156 // T* -> _Bool 6157 if (lhsType == Context.BoolTy) { 6158 Kind = CK_PointerToBoolean; 6159 return Compatible; 6160 } 6161 6162 // T* -> int 6163 if (lhsType->isIntegerType()) { 6164 Kind = CK_PointerToIntegral; 6165 return PointerToInt; 6166 } 6167 6168 return Incompatible; 6169 } 6170 6171 // struct A -> struct B 6172 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 6173 if (Context.typesAreCompatible(lhsType, rhsType)) { 6174 Kind = CK_NoOp; 6175 return Compatible; 6176 } 6177 } 6178 6179 return Incompatible; 6180} 6181 6182/// \brief Constructs a transparent union from an expression that is 6183/// used to initialize the transparent union. 6184static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 6185 QualType UnionType, FieldDecl *Field) { 6186 // Build an initializer list that designates the appropriate member 6187 // of the transparent union. 6188 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6189 &E, 1, 6190 SourceLocation()); 6191 Initializer->setType(UnionType); 6192 Initializer->setInitializedFieldInUnion(Field); 6193 6194 // Build a compound literal constructing a value of the transparent 6195 // union type from this initializer list. 6196 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6197 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6198 VK_RValue, Initializer, false); 6199} 6200 6201Sema::AssignConvertType 6202Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 6203 QualType FromType = rExpr->getType(); 6204 6205 // If the ArgType is a Union type, we want to handle a potential 6206 // transparent_union GCC extension. 6207 const RecordType *UT = ArgType->getAsUnionType(); 6208 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6209 return Incompatible; 6210 6211 // The field to initialize within the transparent union. 6212 RecordDecl *UD = UT->getDecl(); 6213 FieldDecl *InitField = 0; 6214 // It's compatible if the expression matches any of the fields. 6215 for (RecordDecl::field_iterator it = UD->field_begin(), 6216 itend = UD->field_end(); 6217 it != itend; ++it) { 6218 if (it->getType()->isPointerType()) { 6219 // If the transparent union contains a pointer type, we allow: 6220 // 1) void pointer 6221 // 2) null pointer constant 6222 if (FromType->isPointerType()) 6223 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 6224 ImpCastExprToType(rExpr, it->getType(), CK_BitCast); 6225 InitField = *it; 6226 break; 6227 } 6228 6229 if (rExpr->isNullPointerConstant(Context, 6230 Expr::NPC_ValueDependentIsNull)) { 6231 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer); 6232 InitField = *it; 6233 break; 6234 } 6235 } 6236 6237 Expr *rhs = rExpr; 6238 CastKind Kind = CK_Invalid; 6239 if (CheckAssignmentConstraints(it->getType(), rhs, Kind) 6240 == Compatible) { 6241 ImpCastExprToType(rhs, it->getType(), Kind); 6242 rExpr = rhs; 6243 InitField = *it; 6244 break; 6245 } 6246 } 6247 6248 if (!InitField) 6249 return Incompatible; 6250 6251 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 6252 return Compatible; 6253} 6254 6255Sema::AssignConvertType 6256Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 6257 if (getLangOptions().CPlusPlus) { 6258 if (!lhsType->isRecordType()) { 6259 // C++ 5.17p3: If the left operand is not of class type, the 6260 // expression is implicitly converted (C++ 4) to the 6261 // cv-unqualified type of the left operand. 6262 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 6263 AA_Assigning)) 6264 return Incompatible; 6265 return Compatible; 6266 } 6267 6268 // FIXME: Currently, we fall through and treat C++ classes like C 6269 // structures. 6270 } 6271 6272 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6273 // a null pointer constant. 6274 if ((lhsType->isPointerType() || 6275 lhsType->isObjCObjectPointerType() || 6276 lhsType->isBlockPointerType()) 6277 && rExpr->isNullPointerConstant(Context, 6278 Expr::NPC_ValueDependentIsNull)) { 6279 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer); 6280 return Compatible; 6281 } 6282 6283 // This check seems unnatural, however it is necessary to ensure the proper 6284 // conversion of functions/arrays. If the conversion were done for all 6285 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6286 // expressions that suppress this implicit conversion (&, sizeof). 6287 // 6288 // Suppress this for references: C++ 8.5.3p5. 6289 if (!lhsType->isReferenceType()) 6290 DefaultFunctionArrayLvalueConversion(rExpr); 6291 6292 CastKind Kind = CK_Invalid; 6293 Sema::AssignConvertType result = 6294 CheckAssignmentConstraints(lhsType, rExpr, Kind); 6295 6296 // C99 6.5.16.1p2: The value of the right operand is converted to the 6297 // type of the assignment expression. 6298 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6299 // so that we can use references in built-in functions even in C. 6300 // The getNonReferenceType() call makes sure that the resulting expression 6301 // does not have reference type. 6302 if (result != Incompatible && rExpr->getType() != lhsType) 6303 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind); 6304 return result; 6305} 6306 6307QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 6308 Diag(Loc, diag::err_typecheck_invalid_operands) 6309 << lex->getType() << rex->getType() 6310 << lex->getSourceRange() << rex->getSourceRange(); 6311 return QualType(); 6312} 6313 6314QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 6315 // For conversion purposes, we ignore any qualifiers. 6316 // For example, "const float" and "float" are equivalent. 6317 QualType lhsType = 6318 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 6319 QualType rhsType = 6320 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 6321 6322 // If the vector types are identical, return. 6323 if (lhsType == rhsType) 6324 return lhsType; 6325 6326 // Handle the case of a vector & extvector type of the same size and element 6327 // type. It would be nice if we only had one vector type someday. 6328 if (getLangOptions().LaxVectorConversions) { 6329 if (const VectorType *LV = lhsType->getAs<VectorType>()) { 6330 if (const VectorType *RV = rhsType->getAs<VectorType>()) { 6331 if (LV->getElementType() == RV->getElementType() && 6332 LV->getNumElements() == RV->getNumElements()) { 6333 if (lhsType->isExtVectorType()) { 6334 ImpCastExprToType(rex, lhsType, CK_BitCast); 6335 return lhsType; 6336 } 6337 6338 ImpCastExprToType(lex, rhsType, CK_BitCast); 6339 return rhsType; 6340 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){ 6341 // If we are allowing lax vector conversions, and LHS and RHS are both 6342 // vectors, the total size only needs to be the same. This is a 6343 // bitcast; no bits are changed but the result type is different. 6344 ImpCastExprToType(rex, lhsType, CK_BitCast); 6345 return lhsType; 6346 } 6347 } 6348 } 6349 } 6350 6351 // Handle the case of equivalent AltiVec and GCC vector types 6352 if (lhsType->isVectorType() && rhsType->isVectorType() && 6353 Context.areCompatibleVectorTypes(lhsType, rhsType)) { 6354 ImpCastExprToType(lex, rhsType, CK_BitCast); 6355 return rhsType; 6356 } 6357 6358 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6359 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6360 bool swapped = false; 6361 if (rhsType->isExtVectorType()) { 6362 swapped = true; 6363 std::swap(rex, lex); 6364 std::swap(rhsType, lhsType); 6365 } 6366 6367 // Handle the case of an ext vector and scalar. 6368 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) { 6369 QualType EltTy = LV->getElementType(); 6370 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) { 6371 int order = Context.getIntegerTypeOrder(EltTy, rhsType); 6372 if (order > 0) 6373 ImpCastExprToType(rex, EltTy, CK_IntegralCast); 6374 if (order >= 0) { 6375 ImpCastExprToType(rex, lhsType, CK_VectorSplat); 6376 if (swapped) std::swap(rex, lex); 6377 return lhsType; 6378 } 6379 } 6380 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 6381 rhsType->isRealFloatingType()) { 6382 int order = Context.getFloatingTypeOrder(EltTy, rhsType); 6383 if (order > 0) 6384 ImpCastExprToType(rex, EltTy, CK_FloatingCast); 6385 if (order >= 0) { 6386 ImpCastExprToType(rex, lhsType, CK_VectorSplat); 6387 if (swapped) std::swap(rex, lex); 6388 return lhsType; 6389 } 6390 } 6391 } 6392 6393 // Vectors of different size or scalar and non-ext-vector are errors. 6394 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6395 << lex->getType() << rex->getType() 6396 << lex->getSourceRange() << rex->getSourceRange(); 6397 return QualType(); 6398} 6399 6400QualType Sema::CheckMultiplyDivideOperands( 6401 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) { 6402 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 6403 return CheckVectorOperands(Loc, lex, rex); 6404 6405 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 6406 6407 if (!lex->getType()->isArithmeticType() || 6408 !rex->getType()->isArithmeticType()) 6409 return InvalidOperands(Loc, lex, rex); 6410 6411 // Check for division by zero. 6412 if (isDiv && 6413 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 6414 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero) 6415 << rex->getSourceRange()); 6416 6417 return compType; 6418} 6419 6420QualType Sema::CheckRemainderOperands( 6421 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 6422 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 6423 if (lex->getType()->hasIntegerRepresentation() && 6424 rex->getType()->hasIntegerRepresentation()) 6425 return CheckVectorOperands(Loc, lex, rex); 6426 return InvalidOperands(Loc, lex, rex); 6427 } 6428 6429 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 6430 6431 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 6432 return InvalidOperands(Loc, lex, rex); 6433 6434 // Check for remainder by zero. 6435 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 6436 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero) 6437 << rex->getSourceRange()); 6438 6439 return compType; 6440} 6441 6442QualType Sema::CheckAdditionOperands( // C99 6.5.6 6443 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { 6444 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 6445 QualType compType = CheckVectorOperands(Loc, lex, rex); 6446 if (CompLHSTy) *CompLHSTy = compType; 6447 return compType; 6448 } 6449 6450 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 6451 6452 // handle the common case first (both operands are arithmetic). 6453 if (lex->getType()->isArithmeticType() && 6454 rex->getType()->isArithmeticType()) { 6455 if (CompLHSTy) *CompLHSTy = compType; 6456 return compType; 6457 } 6458 6459 // Put any potential pointer into PExp 6460 Expr* PExp = lex, *IExp = rex; 6461 if (IExp->getType()->isAnyPointerType()) 6462 std::swap(PExp, IExp); 6463 6464 if (PExp->getType()->isAnyPointerType()) { 6465 6466 if (IExp->getType()->isIntegerType()) { 6467 QualType PointeeTy = PExp->getType()->getPointeeType(); 6468 6469 // Check for arithmetic on pointers to incomplete types. 6470 if (PointeeTy->isVoidType()) { 6471 if (getLangOptions().CPlusPlus) { 6472 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 6473 << lex->getSourceRange() << rex->getSourceRange(); 6474 return QualType(); 6475 } 6476 6477 // GNU extension: arithmetic on pointer to void 6478 Diag(Loc, diag::ext_gnu_void_ptr) 6479 << lex->getSourceRange() << rex->getSourceRange(); 6480 } else if (PointeeTy->isFunctionType()) { 6481 if (getLangOptions().CPlusPlus) { 6482 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 6483 << lex->getType() << lex->getSourceRange(); 6484 return QualType(); 6485 } 6486 6487 // GNU extension: arithmetic on pointer to function 6488 Diag(Loc, diag::ext_gnu_ptr_func_arith) 6489 << lex->getType() << lex->getSourceRange(); 6490 } else { 6491 // Check if we require a complete type. 6492 if (((PExp->getType()->isPointerType() && 6493 !PExp->getType()->isDependentType()) || 6494 PExp->getType()->isObjCObjectPointerType()) && 6495 RequireCompleteType(Loc, PointeeTy, 6496 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 6497 << PExp->getSourceRange() 6498 << PExp->getType())) 6499 return QualType(); 6500 } 6501 // Diagnose bad cases where we step over interface counts. 6502 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6503 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 6504 << PointeeTy << PExp->getSourceRange(); 6505 return QualType(); 6506 } 6507 6508 if (CompLHSTy) { 6509 QualType LHSTy = Context.isPromotableBitField(lex); 6510 if (LHSTy.isNull()) { 6511 LHSTy = lex->getType(); 6512 if (LHSTy->isPromotableIntegerType()) 6513 LHSTy = Context.getPromotedIntegerType(LHSTy); 6514 } 6515 *CompLHSTy = LHSTy; 6516 } 6517 return PExp->getType(); 6518 } 6519 } 6520 6521 return InvalidOperands(Loc, lex, rex); 6522} 6523 6524// C99 6.5.6 6525QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 6526 SourceLocation Loc, QualType* CompLHSTy) { 6527 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 6528 QualType compType = CheckVectorOperands(Loc, lex, rex); 6529 if (CompLHSTy) *CompLHSTy = compType; 6530 return compType; 6531 } 6532 6533 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 6534 6535 // Enforce type constraints: C99 6.5.6p3. 6536 6537 // Handle the common case first (both operands are arithmetic). 6538 if (lex->getType()->isArithmeticType() 6539 && rex->getType()->isArithmeticType()) { 6540 if (CompLHSTy) *CompLHSTy = compType; 6541 return compType; 6542 } 6543 6544 // Either ptr - int or ptr - ptr. 6545 if (lex->getType()->isAnyPointerType()) { 6546 QualType lpointee = lex->getType()->getPointeeType(); 6547 6548 // The LHS must be an completely-defined object type. 6549 6550 bool ComplainAboutVoid = false; 6551 Expr *ComplainAboutFunc = 0; 6552 if (lpointee->isVoidType()) { 6553 if (getLangOptions().CPlusPlus) { 6554 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 6555 << lex->getSourceRange() << rex->getSourceRange(); 6556 return QualType(); 6557 } 6558 6559 // GNU C extension: arithmetic on pointer to void 6560 ComplainAboutVoid = true; 6561 } else if (lpointee->isFunctionType()) { 6562 if (getLangOptions().CPlusPlus) { 6563 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 6564 << lex->getType() << lex->getSourceRange(); 6565 return QualType(); 6566 } 6567 6568 // GNU C extension: arithmetic on pointer to function 6569 ComplainAboutFunc = lex; 6570 } else if (!lpointee->isDependentType() && 6571 RequireCompleteType(Loc, lpointee, 6572 PDiag(diag::err_typecheck_sub_ptr_object) 6573 << lex->getSourceRange() 6574 << lex->getType())) 6575 return QualType(); 6576 6577 // Diagnose bad cases where we step over interface counts. 6578 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6579 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 6580 << lpointee << lex->getSourceRange(); 6581 return QualType(); 6582 } 6583 6584 // The result type of a pointer-int computation is the pointer type. 6585 if (rex->getType()->isIntegerType()) { 6586 if (ComplainAboutVoid) 6587 Diag(Loc, diag::ext_gnu_void_ptr) 6588 << lex->getSourceRange() << rex->getSourceRange(); 6589 if (ComplainAboutFunc) 6590 Diag(Loc, diag::ext_gnu_ptr_func_arith) 6591 << ComplainAboutFunc->getType() 6592 << ComplainAboutFunc->getSourceRange(); 6593 6594 if (CompLHSTy) *CompLHSTy = lex->getType(); 6595 return lex->getType(); 6596 } 6597 6598 // Handle pointer-pointer subtractions. 6599 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 6600 QualType rpointee = RHSPTy->getPointeeType(); 6601 6602 // RHS must be a completely-type object type. 6603 // Handle the GNU void* extension. 6604 if (rpointee->isVoidType()) { 6605 if (getLangOptions().CPlusPlus) { 6606 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 6607 << lex->getSourceRange() << rex->getSourceRange(); 6608 return QualType(); 6609 } 6610 6611 ComplainAboutVoid = true; 6612 } else if (rpointee->isFunctionType()) { 6613 if (getLangOptions().CPlusPlus) { 6614 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 6615 << rex->getType() << rex->getSourceRange(); 6616 return QualType(); 6617 } 6618 6619 // GNU extension: arithmetic on pointer to function 6620 if (!ComplainAboutFunc) 6621 ComplainAboutFunc = rex; 6622 } else if (!rpointee->isDependentType() && 6623 RequireCompleteType(Loc, rpointee, 6624 PDiag(diag::err_typecheck_sub_ptr_object) 6625 << rex->getSourceRange() 6626 << rex->getType())) 6627 return QualType(); 6628 6629 if (getLangOptions().CPlusPlus) { 6630 // Pointee types must be the same: C++ [expr.add] 6631 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6632 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6633 << lex->getType() << rex->getType() 6634 << lex->getSourceRange() << rex->getSourceRange(); 6635 return QualType(); 6636 } 6637 } else { 6638 // Pointee types must be compatible C99 6.5.6p3 6639 if (!Context.typesAreCompatible( 6640 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6641 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6642 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6643 << lex->getType() << rex->getType() 6644 << lex->getSourceRange() << rex->getSourceRange(); 6645 return QualType(); 6646 } 6647 } 6648 6649 if (ComplainAboutVoid) 6650 Diag(Loc, diag::ext_gnu_void_ptr) 6651 << lex->getSourceRange() << rex->getSourceRange(); 6652 if (ComplainAboutFunc) 6653 Diag(Loc, diag::ext_gnu_ptr_func_arith) 6654 << ComplainAboutFunc->getType() 6655 << ComplainAboutFunc->getSourceRange(); 6656 6657 if (CompLHSTy) *CompLHSTy = lex->getType(); 6658 return Context.getPointerDiffType(); 6659 } 6660 } 6661 6662 return InvalidOperands(Loc, lex, rex); 6663} 6664 6665static bool isScopedEnumerationType(QualType T) { 6666 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6667 return ET->getDecl()->isScoped(); 6668 return false; 6669} 6670 6671static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex, 6672 SourceLocation Loc, unsigned Opc, 6673 QualType LHSTy) { 6674 llvm::APSInt Right; 6675 // Check right/shifter operand 6676 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context)) 6677 return; 6678 6679 if (Right.isNegative()) { 6680 S.DiagRuntimeBehavior(Loc, rex, 6681 S.PDiag(diag::warn_shift_negative) 6682 << rex->getSourceRange()); 6683 return; 6684 } 6685 llvm::APInt LeftBits(Right.getBitWidth(), 6686 S.Context.getTypeSize(lex->getType())); 6687 if (Right.uge(LeftBits)) { 6688 S.DiagRuntimeBehavior(Loc, rex, 6689 S.PDiag(diag::warn_shift_gt_typewidth) 6690 << rex->getSourceRange()); 6691 return; 6692 } 6693 if (Opc != BO_Shl) 6694 return; 6695 6696 // When left shifting an ICE which is signed, we can check for overflow which 6697 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6698 // integers have defined behavior modulo one more than the maximum value 6699 // representable in the result type, so never warn for those. 6700 llvm::APSInt Left; 6701 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) || 6702 LHSTy->hasUnsignedIntegerRepresentation()) 6703 return; 6704 llvm::APInt ResultBits = 6705 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6706 if (LeftBits.uge(ResultBits)) 6707 return; 6708 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6709 Result = Result.shl(Right); 6710 6711 // If we are only missing a sign bit, this is less likely to result in actual 6712 // bugs -- if the result is cast back to an unsigned type, it will have the 6713 // expected value. Thus we place this behind a different warning that can be 6714 // turned off separately if needed. 6715 if (LeftBits == ResultBits - 1) { 6716 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit) 6717 << Result.toString(10) << LHSTy 6718 << lex->getSourceRange() << rex->getSourceRange(); 6719 return; 6720 } 6721 6722 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6723 << Result.toString(10) << Result.getMinSignedBits() << LHSTy 6724 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange(); 6725} 6726 6727// C99 6.5.7 6728QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 6729 unsigned Opc, bool isCompAssign) { 6730 // C99 6.5.7p2: Each of the operands shall have integer type. 6731 if (!lex->getType()->hasIntegerRepresentation() || 6732 !rex->getType()->hasIntegerRepresentation()) 6733 return InvalidOperands(Loc, lex, rex); 6734 6735 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6736 // hasIntegerRepresentation() above instead of this. 6737 if (isScopedEnumerationType(lex->getType()) || 6738 isScopedEnumerationType(rex->getType())) { 6739 return InvalidOperands(Loc, lex, rex); 6740 } 6741 6742 // Vector shifts promote their scalar inputs to vector type. 6743 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 6744 return CheckVectorOperands(Loc, lex, rex); 6745 6746 // Shifts don't perform usual arithmetic conversions, they just do integer 6747 // promotions on each operand. C99 6.5.7p3 6748 6749 // For the LHS, do usual unary conversions, but then reset them away 6750 // if this is a compound assignment. 6751 Expr *old_lex = lex; 6752 UsualUnaryConversions(lex); 6753 QualType LHSTy = lex->getType(); 6754 if (isCompAssign) lex = old_lex; 6755 6756 // The RHS is simpler. 6757 UsualUnaryConversions(rex); 6758 6759 // Sanity-check shift operands 6760 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy); 6761 6762 // "The type of the result is that of the promoted left operand." 6763 return LHSTy; 6764} 6765 6766static bool IsWithinTemplateSpecialization(Decl *D) { 6767 if (DeclContext *DC = D->getDeclContext()) { 6768 if (isa<ClassTemplateSpecializationDecl>(DC)) 6769 return true; 6770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6771 return FD->isFunctionTemplateSpecialization(); 6772 } 6773 return false; 6774} 6775 6776// C99 6.5.8, C++ [expr.rel] 6777QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 6778 unsigned OpaqueOpc, bool isRelational) { 6779 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6780 6781 // Handle vector comparisons separately. 6782 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 6783 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 6784 6785 QualType lType = lex->getType(); 6786 QualType rType = rex->getType(); 6787 6788 Expr *LHSStripped = lex->IgnoreParenImpCasts(); 6789 Expr *RHSStripped = rex->IgnoreParenImpCasts(); 6790 QualType LHSStrippedType = LHSStripped->getType(); 6791 QualType RHSStrippedType = RHSStripped->getType(); 6792 6793 // Two different enums will raise a warning when compared. 6794 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) { 6795 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) { 6796 if (LHSEnumType->getDecl()->getIdentifier() && 6797 RHSEnumType->getDecl()->getIdentifier() && 6798 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 6799 Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6800 << LHSStrippedType << RHSStrippedType 6801 << lex->getSourceRange() << rex->getSourceRange(); 6802 } 6803 } 6804 } 6805 6806 if (!lType->hasFloatingRepresentation() && 6807 !(lType->isBlockPointerType() && isRelational) && 6808 !lex->getLocStart().isMacroID() && 6809 !rex->getLocStart().isMacroID()) { 6810 // For non-floating point types, check for self-comparisons of the form 6811 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6812 // often indicate logic errors in the program. 6813 // 6814 // NOTE: Don't warn about comparison expressions resulting from macro 6815 // expansion. Also don't warn about comparisons which are only self 6816 // comparisons within a template specialization. The warnings should catch 6817 // obvious cases in the definition of the template anyways. The idea is to 6818 // warn when the typed comparison operator will always evaluate to the same 6819 // result. 6820 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6821 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6822 if (DRL->getDecl() == DRR->getDecl() && 6823 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6824 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6825 << 0 // self- 6826 << (Opc == BO_EQ 6827 || Opc == BO_LE 6828 || Opc == BO_GE)); 6829 } else if (lType->isArrayType() && rType->isArrayType() && 6830 !DRL->getDecl()->getType()->isReferenceType() && 6831 !DRR->getDecl()->getType()->isReferenceType()) { 6832 // what is it always going to eval to? 6833 char always_evals_to; 6834 switch(Opc) { 6835 case BO_EQ: // e.g. array1 == array2 6836 always_evals_to = 0; // false 6837 break; 6838 case BO_NE: // e.g. array1 != array2 6839 always_evals_to = 1; // true 6840 break; 6841 default: 6842 // best we can say is 'a constant' 6843 always_evals_to = 2; // e.g. array1 <= array2 6844 break; 6845 } 6846 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6847 << 1 // array 6848 << always_evals_to); 6849 } 6850 } 6851 } 6852 6853 if (isa<CastExpr>(LHSStripped)) 6854 LHSStripped = LHSStripped->IgnoreParenCasts(); 6855 if (isa<CastExpr>(RHSStripped)) 6856 RHSStripped = RHSStripped->IgnoreParenCasts(); 6857 6858 // Warn about comparisons against a string constant (unless the other 6859 // operand is null), the user probably wants strcmp. 6860 Expr *literalString = 0; 6861 Expr *literalStringStripped = 0; 6862 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6863 !RHSStripped->isNullPointerConstant(Context, 6864 Expr::NPC_ValueDependentIsNull)) { 6865 literalString = lex; 6866 literalStringStripped = LHSStripped; 6867 } else if ((isa<StringLiteral>(RHSStripped) || 6868 isa<ObjCEncodeExpr>(RHSStripped)) && 6869 !LHSStripped->isNullPointerConstant(Context, 6870 Expr::NPC_ValueDependentIsNull)) { 6871 literalString = rex; 6872 literalStringStripped = RHSStripped; 6873 } 6874 6875 if (literalString) { 6876 std::string resultComparison; 6877 switch (Opc) { 6878 case BO_LT: resultComparison = ") < 0"; break; 6879 case BO_GT: resultComparison = ") > 0"; break; 6880 case BO_LE: resultComparison = ") <= 0"; break; 6881 case BO_GE: resultComparison = ") >= 0"; break; 6882 case BO_EQ: resultComparison = ") == 0"; break; 6883 case BO_NE: resultComparison = ") != 0"; break; 6884 default: assert(false && "Invalid comparison operator"); 6885 } 6886 6887 DiagRuntimeBehavior(Loc, 0, 6888 PDiag(diag::warn_stringcompare) 6889 << isa<ObjCEncodeExpr>(literalStringStripped) 6890 << literalString->getSourceRange()); 6891 } 6892 } 6893 6894 // C99 6.5.8p3 / C99 6.5.9p4 6895 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 6896 UsualArithmeticConversions(lex, rex); 6897 else { 6898 UsualUnaryConversions(lex); 6899 UsualUnaryConversions(rex); 6900 } 6901 6902 lType = lex->getType(); 6903 rType = rex->getType(); 6904 6905 // The result of comparisons is 'bool' in C++, 'int' in C. 6906 QualType ResultTy = Context.getLogicalOperationType(); 6907 6908 if (isRelational) { 6909 if (lType->isRealType() && rType->isRealType()) 6910 return ResultTy; 6911 } else { 6912 // Check for comparisons of floating point operands using != and ==. 6913 if (lType->hasFloatingRepresentation()) 6914 CheckFloatComparison(Loc,lex,rex); 6915 6916 if (lType->isArithmeticType() && rType->isArithmeticType()) 6917 return ResultTy; 6918 } 6919 6920 bool LHSIsNull = lex->isNullPointerConstant(Context, 6921 Expr::NPC_ValueDependentIsNull); 6922 bool RHSIsNull = rex->isNullPointerConstant(Context, 6923 Expr::NPC_ValueDependentIsNull); 6924 6925 // All of the following pointer-related warnings are GCC extensions, except 6926 // when handling null pointer constants. 6927 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 6928 QualType LCanPointeeTy = 6929 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 6930 QualType RCanPointeeTy = 6931 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 6932 6933 if (getLangOptions().CPlusPlus) { 6934 if (LCanPointeeTy == RCanPointeeTy) 6935 return ResultTy; 6936 if (!isRelational && 6937 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6938 // Valid unless comparison between non-null pointer and function pointer 6939 // This is a gcc extension compatibility comparison. 6940 // In a SFINAE context, we treat this as a hard error to maintain 6941 // conformance with the C++ standard. 6942 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6943 && !LHSIsNull && !RHSIsNull) { 6944 Diag(Loc, 6945 isSFINAEContext()? 6946 diag::err_typecheck_comparison_of_fptr_to_void 6947 : diag::ext_typecheck_comparison_of_fptr_to_void) 6948 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 6949 6950 if (isSFINAEContext()) 6951 return QualType(); 6952 6953 ImpCastExprToType(rex, lType, CK_BitCast); 6954 return ResultTy; 6955 } 6956 } 6957 6958 // C++ [expr.rel]p2: 6959 // [...] Pointer conversions (4.10) and qualification 6960 // conversions (4.4) are performed on pointer operands (or on 6961 // a pointer operand and a null pointer constant) to bring 6962 // them to their composite pointer type. [...] 6963 // 6964 // C++ [expr.eq]p1 uses the same notion for (in)equality 6965 // comparisons of pointers. 6966 bool NonStandardCompositeType = false; 6967 QualType T = FindCompositePointerType(Loc, lex, rex, 6968 isSFINAEContext()? 0 : &NonStandardCompositeType); 6969 if (T.isNull()) { 6970 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 6971 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 6972 return QualType(); 6973 } else if (NonStandardCompositeType) { 6974 Diag(Loc, 6975 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6976 << lType << rType << T 6977 << lex->getSourceRange() << rex->getSourceRange(); 6978 } 6979 6980 ImpCastExprToType(lex, T, CK_BitCast); 6981 ImpCastExprToType(rex, T, CK_BitCast); 6982 return ResultTy; 6983 } 6984 // C99 6.5.9p2 and C99 6.5.8p2 6985 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 6986 RCanPointeeTy.getUnqualifiedType())) { 6987 // Valid unless a relational comparison of function pointers 6988 if (isRelational && LCanPointeeTy->isFunctionType()) { 6989 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 6990 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 6991 } 6992 } else if (!isRelational && 6993 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6994 // Valid unless comparison between non-null pointer and function pointer 6995 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6996 && !LHSIsNull && !RHSIsNull) { 6997 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 6998 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 6999 } 7000 } else { 7001 // Invalid 7002 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 7003 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7004 } 7005 if (LCanPointeeTy != RCanPointeeTy) { 7006 if (LHSIsNull && !RHSIsNull) 7007 ImpCastExprToType(lex, rType, CK_BitCast); 7008 else 7009 ImpCastExprToType(rex, lType, CK_BitCast); 7010 } 7011 return ResultTy; 7012 } 7013 7014 if (getLangOptions().CPlusPlus) { 7015 // Comparison of nullptr_t with itself. 7016 if (lType->isNullPtrType() && rType->isNullPtrType()) 7017 return ResultTy; 7018 7019 // Comparison of pointers with null pointer constants and equality 7020 // comparisons of member pointers to null pointer constants. 7021 if (RHSIsNull && 7022 ((lType->isPointerType() || lType->isNullPtrType()) || 7023 (!isRelational && lType->isMemberPointerType()))) { 7024 ImpCastExprToType(rex, lType, 7025 lType->isMemberPointerType() 7026 ? CK_NullToMemberPointer 7027 : CK_NullToPointer); 7028 return ResultTy; 7029 } 7030 if (LHSIsNull && 7031 ((rType->isPointerType() || rType->isNullPtrType()) || 7032 (!isRelational && rType->isMemberPointerType()))) { 7033 ImpCastExprToType(lex, rType, 7034 rType->isMemberPointerType() 7035 ? CK_NullToMemberPointer 7036 : CK_NullToPointer); 7037 return ResultTy; 7038 } 7039 7040 // Comparison of member pointers. 7041 if (!isRelational && 7042 lType->isMemberPointerType() && rType->isMemberPointerType()) { 7043 // C++ [expr.eq]p2: 7044 // In addition, pointers to members can be compared, or a pointer to 7045 // member and a null pointer constant. Pointer to member conversions 7046 // (4.11) and qualification conversions (4.4) are performed to bring 7047 // them to a common type. If one operand is a null pointer constant, 7048 // the common type is the type of the other operand. Otherwise, the 7049 // common type is a pointer to member type similar (4.4) to the type 7050 // of one of the operands, with a cv-qualification signature (4.4) 7051 // that is the union of the cv-qualification signatures of the operand 7052 // types. 7053 bool NonStandardCompositeType = false; 7054 QualType T = FindCompositePointerType(Loc, lex, rex, 7055 isSFINAEContext()? 0 : &NonStandardCompositeType); 7056 if (T.isNull()) { 7057 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 7058 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7059 return QualType(); 7060 } else if (NonStandardCompositeType) { 7061 Diag(Loc, 7062 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7063 << lType << rType << T 7064 << lex->getSourceRange() << rex->getSourceRange(); 7065 } 7066 7067 ImpCastExprToType(lex, T, CK_BitCast); 7068 ImpCastExprToType(rex, T, CK_BitCast); 7069 return ResultTy; 7070 } 7071 7072 // Handle scoped enumeration types specifically, since they don't promote 7073 // to integers. 7074 if (lex->getType()->isEnumeralType() && 7075 Context.hasSameUnqualifiedType(lex->getType(), rex->getType())) 7076 return ResultTy; 7077 } 7078 7079 // Handle block pointer types. 7080 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 7081 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 7082 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 7083 7084 if (!LHSIsNull && !RHSIsNull && 7085 !Context.typesAreCompatible(lpointee, rpointee)) { 7086 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7087 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7088 } 7089 ImpCastExprToType(rex, lType, CK_BitCast); 7090 return ResultTy; 7091 } 7092 // Allow block pointers to be compared with null pointer constants. 7093 if (!isRelational 7094 && ((lType->isBlockPointerType() && rType->isPointerType()) 7095 || (lType->isPointerType() && rType->isBlockPointerType()))) { 7096 if (!LHSIsNull && !RHSIsNull) { 7097 if (!((rType->isPointerType() && rType->castAs<PointerType>() 7098 ->getPointeeType()->isVoidType()) 7099 || (lType->isPointerType() && lType->castAs<PointerType>() 7100 ->getPointeeType()->isVoidType()))) 7101 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7102 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7103 } 7104 if (LHSIsNull && !RHSIsNull) 7105 ImpCastExprToType(lex, rType, CK_BitCast); 7106 else 7107 ImpCastExprToType(rex, lType, CK_BitCast); 7108 return ResultTy; 7109 } 7110 7111 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) { 7112 const PointerType *LPT = lType->getAs<PointerType>(); 7113 const PointerType *RPT = rType->getAs<PointerType>(); 7114 if (LPT || RPT) { 7115 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7116 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7117 7118 if (!LPtrToVoid && !RPtrToVoid && 7119 !Context.typesAreCompatible(lType, rType)) { 7120 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 7121 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7122 } 7123 if (LHSIsNull && !RHSIsNull) 7124 ImpCastExprToType(lex, rType, CK_BitCast); 7125 else 7126 ImpCastExprToType(rex, lType, CK_BitCast); 7127 return ResultTy; 7128 } 7129 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 7130 if (!Context.areComparableObjCPointerTypes(lType, rType)) 7131 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 7132 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7133 if (LHSIsNull && !RHSIsNull) 7134 ImpCastExprToType(lex, rType, CK_BitCast); 7135 else 7136 ImpCastExprToType(rex, lType, CK_BitCast); 7137 return ResultTy; 7138 } 7139 } 7140 if ((lType->isAnyPointerType() && rType->isIntegerType()) || 7141 (lType->isIntegerType() && rType->isAnyPointerType())) { 7142 unsigned DiagID = 0; 7143 bool isError = false; 7144 if ((LHSIsNull && lType->isIntegerType()) || 7145 (RHSIsNull && rType->isIntegerType())) { 7146 if (isRelational && !getLangOptions().CPlusPlus) 7147 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7148 } else if (isRelational && !getLangOptions().CPlusPlus) 7149 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7150 else if (getLangOptions().CPlusPlus) { 7151 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7152 isError = true; 7153 } else 7154 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7155 7156 if (DiagID) { 7157 Diag(Loc, DiagID) 7158 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 7159 if (isError) 7160 return QualType(); 7161 } 7162 7163 if (lType->isIntegerType()) 7164 ImpCastExprToType(lex, rType, 7165 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7166 else 7167 ImpCastExprToType(rex, lType, 7168 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7169 return ResultTy; 7170 } 7171 7172 // Handle block pointers. 7173 if (!isRelational && RHSIsNull 7174 && lType->isBlockPointerType() && rType->isIntegerType()) { 7175 ImpCastExprToType(rex, lType, CK_NullToPointer); 7176 return ResultTy; 7177 } 7178 if (!isRelational && LHSIsNull 7179 && lType->isIntegerType() && rType->isBlockPointerType()) { 7180 ImpCastExprToType(lex, rType, CK_NullToPointer); 7181 return ResultTy; 7182 } 7183 7184 return InvalidOperands(Loc, lex, rex); 7185} 7186 7187/// CheckVectorCompareOperands - vector comparisons are a clang extension that 7188/// operates on extended vector types. Instead of producing an IntTy result, 7189/// like a scalar comparison, a vector comparison produces a vector of integer 7190/// types. 7191QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 7192 SourceLocation Loc, 7193 bool isRelational) { 7194 // Check to make sure we're operating on vectors of the same type and width, 7195 // Allowing one side to be a scalar of element type. 7196 QualType vType = CheckVectorOperands(Loc, lex, rex); 7197 if (vType.isNull()) 7198 return vType; 7199 7200 // If AltiVec, the comparison results in a numeric type, i.e. 7201 // bool for C++, int for C 7202 if (getLangOptions().AltiVec) 7203 return Context.getLogicalOperationType(); 7204 7205 QualType lType = lex->getType(); 7206 QualType rType = rex->getType(); 7207 7208 // For non-floating point types, check for self-comparisons of the form 7209 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7210 // often indicate logic errors in the program. 7211 if (!lType->hasFloatingRepresentation()) { 7212 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 7213 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 7214 if (DRL->getDecl() == DRR->getDecl()) 7215 DiagRuntimeBehavior(Loc, 0, 7216 PDiag(diag::warn_comparison_always) 7217 << 0 // self- 7218 << 2 // "a constant" 7219 ); 7220 } 7221 7222 // Check for comparisons of floating point operands using != and ==. 7223 if (!isRelational && lType->hasFloatingRepresentation()) { 7224 assert (rType->hasFloatingRepresentation()); 7225 CheckFloatComparison(Loc,lex,rex); 7226 } 7227 7228 // Return the type for the comparison, which is the same as vector type for 7229 // integer vectors, or an integer type of identical size and number of 7230 // elements for floating point vectors. 7231 if (lType->hasIntegerRepresentation()) 7232 return lType; 7233 7234 const VectorType *VTy = lType->getAs<VectorType>(); 7235 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7236 if (TypeSize == Context.getTypeSize(Context.IntTy)) 7237 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7238 if (TypeSize == Context.getTypeSize(Context.LongTy)) 7239 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7240 7241 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7242 "Unhandled vector element size in vector compare"); 7243 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7244} 7245 7246inline QualType Sema::CheckBitwiseOperands( 7247 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 7248 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 7249 if (lex->getType()->hasIntegerRepresentation() && 7250 rex->getType()->hasIntegerRepresentation()) 7251 return CheckVectorOperands(Loc, lex, rex); 7252 7253 return InvalidOperands(Loc, lex, rex); 7254 } 7255 7256 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 7257 7258 if (lex->getType()->isIntegralOrUnscopedEnumerationType() && 7259 rex->getType()->isIntegralOrUnscopedEnumerationType()) 7260 return compType; 7261 return InvalidOperands(Loc, lex, rex); 7262} 7263 7264inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7265 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) { 7266 7267 // Diagnose cases where the user write a logical and/or but probably meant a 7268 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7269 // is a constant. 7270 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() && 7271 rex->getType()->isIntegerType() && !rex->isValueDependent() && 7272 // Don't warn in macros. 7273 !Loc.isMacroID()) { 7274 // If the RHS can be constant folded, and if it constant folds to something 7275 // that isn't 0 or 1 (which indicate a potential logical operation that 7276 // happened to fold to true/false) then warn. 7277 Expr::EvalResult Result; 7278 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects && 7279 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) { 7280 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7281 << rex->getSourceRange() 7282 << (Opc == BO_LAnd ? "&&" : "||") 7283 << (Opc == BO_LAnd ? "&" : "|"); 7284 } 7285 } 7286 7287 if (!Context.getLangOptions().CPlusPlus) { 7288 UsualUnaryConversions(lex); 7289 UsualUnaryConversions(rex); 7290 7291 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType()) 7292 return InvalidOperands(Loc, lex, rex); 7293 7294 return Context.IntTy; 7295 } 7296 7297 // The following is safe because we only use this method for 7298 // non-overloadable operands. 7299 7300 // C++ [expr.log.and]p1 7301 // C++ [expr.log.or]p1 7302 // The operands are both contextually converted to type bool. 7303 if (PerformContextuallyConvertToBool(lex) || 7304 PerformContextuallyConvertToBool(rex)) 7305 return InvalidOperands(Loc, lex, rex); 7306 7307 // C++ [expr.log.and]p2 7308 // C++ [expr.log.or]p2 7309 // The result is a bool. 7310 return Context.BoolTy; 7311} 7312 7313/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7314/// is a read-only property; return true if so. A readonly property expression 7315/// depends on various declarations and thus must be treated specially. 7316/// 7317static bool IsReadonlyProperty(Expr *E, Sema &S) { 7318 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 7319 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 7320 if (PropExpr->isImplicitProperty()) return false; 7321 7322 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7323 QualType BaseType = PropExpr->isSuperReceiver() ? 7324 PropExpr->getSuperReceiverType() : 7325 PropExpr->getBase()->getType(); 7326 7327 if (const ObjCObjectPointerType *OPT = 7328 BaseType->getAsObjCInterfacePointerType()) 7329 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7330 if (S.isPropertyReadonly(PDecl, IFace)) 7331 return true; 7332 } 7333 return false; 7334} 7335 7336/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7337/// emit an error and return true. If so, return false. 7338static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7339 SourceLocation OrigLoc = Loc; 7340 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7341 &Loc); 7342 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7343 IsLV = Expr::MLV_ReadonlyProperty; 7344 if (IsLV == Expr::MLV_Valid) 7345 return false; 7346 7347 unsigned Diag = 0; 7348 bool NeedType = false; 7349 switch (IsLV) { // C99 6.5.16p2 7350 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 7351 case Expr::MLV_ArrayType: 7352 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7353 NeedType = true; 7354 break; 7355 case Expr::MLV_NotObjectType: 7356 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7357 NeedType = true; 7358 break; 7359 case Expr::MLV_LValueCast: 7360 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7361 break; 7362 case Expr::MLV_Valid: 7363 llvm_unreachable("did not take early return for MLV_Valid"); 7364 case Expr::MLV_InvalidExpression: 7365 case Expr::MLV_MemberFunction: 7366 case Expr::MLV_ClassTemporary: 7367 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7368 break; 7369 case Expr::MLV_IncompleteType: 7370 case Expr::MLV_IncompleteVoidType: 7371 return S.RequireCompleteType(Loc, E->getType(), 7372 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 7373 << E->getSourceRange()); 7374 case Expr::MLV_DuplicateVectorComponents: 7375 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7376 break; 7377 case Expr::MLV_NotBlockQualified: 7378 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7379 break; 7380 case Expr::MLV_ReadonlyProperty: 7381 Diag = diag::error_readonly_property_assignment; 7382 break; 7383 case Expr::MLV_NoSetterProperty: 7384 Diag = diag::error_nosetter_property_assignment; 7385 break; 7386 case Expr::MLV_SubObjCPropertySetting: 7387 Diag = diag::error_no_subobject_property_setting; 7388 break; 7389 } 7390 7391 SourceRange Assign; 7392 if (Loc != OrigLoc) 7393 Assign = SourceRange(OrigLoc, OrigLoc); 7394 if (NeedType) 7395 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7396 else 7397 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7398 return true; 7399} 7400 7401 7402 7403// C99 6.5.16.1 7404QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 7405 SourceLocation Loc, 7406 QualType CompoundType) { 7407 // Verify that LHS is a modifiable lvalue, and emit error if not. 7408 if (CheckForModifiableLvalue(LHS, Loc, *this)) 7409 return QualType(); 7410 7411 QualType LHSType = LHS->getType(); 7412 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 7413 AssignConvertType ConvTy; 7414 if (CompoundType.isNull()) { 7415 QualType LHSTy(LHSType); 7416 // Simple assignment "x = y". 7417 if (LHS->getObjectKind() == OK_ObjCProperty) 7418 ConvertPropertyForLValue(LHS, RHS, LHSTy); 7419 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7420 // Special case of NSObject attributes on c-style pointer types. 7421 if (ConvTy == IncompatiblePointer && 7422 ((Context.isObjCNSObjectType(LHSType) && 7423 RHSType->isObjCObjectPointerType()) || 7424 (Context.isObjCNSObjectType(RHSType) && 7425 LHSType->isObjCObjectPointerType()))) 7426 ConvTy = Compatible; 7427 7428 if (ConvTy == Compatible && 7429 getLangOptions().ObjCNonFragileABI && 7430 LHSType->isObjCObjectType()) 7431 Diag(Loc, diag::err_assignment_requires_nonfragile_object) 7432 << LHSType; 7433 7434 // If the RHS is a unary plus or minus, check to see if they = and + are 7435 // right next to each other. If so, the user may have typo'd "x =+ 4" 7436 // instead of "x += 4". 7437 Expr *RHSCheck = RHS; 7438 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7439 RHSCheck = ICE->getSubExpr(); 7440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7441 if ((UO->getOpcode() == UO_Plus || 7442 UO->getOpcode() == UO_Minus) && 7443 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7444 // Only if the two operators are exactly adjacent. 7445 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 7446 // And there is a space or other character before the subexpr of the 7447 // unary +/-. We don't want to warn on "x=-1". 7448 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7449 UO->getSubExpr()->getLocStart().isFileID()) { 7450 Diag(Loc, diag::warn_not_compound_assign) 7451 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7452 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7453 } 7454 } 7455 } else { 7456 // Compound assignment "x += y" 7457 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7458 } 7459 7460 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7461 RHS, AA_Assigning)) 7462 return QualType(); 7463 7464 7465 // Check to see if the destination operand is a dereferenced null pointer. If 7466 // so, and if not volatile-qualified, this is undefined behavior that the 7467 // optimizer will delete, so warn about it. People sometimes try to use this 7468 // to get a deterministic trap and are surprised by clang's behavior. This 7469 // only handles the pattern "*null = whatever", which is a very syntactic 7470 // check. 7471 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts())) 7472 if (UO->getOpcode() == UO_Deref && 7473 UO->getSubExpr()->IgnoreParenCasts()-> 7474 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) && 7475 !UO->getType().isVolatileQualified()) { 7476 DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 7477 PDiag(diag::warn_indirection_through_null) 7478 << UO->getSubExpr()->getSourceRange()); 7479 DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 7480 PDiag(diag::note_indirection_through_null)); 7481 } 7482 7483 // Check for trivial buffer overflows. 7484 CheckArrayAccess(LHS->IgnoreParenCasts()); 7485 7486 // C99 6.5.16p3: The type of an assignment expression is the type of the 7487 // left operand unless the left operand has qualified type, in which case 7488 // it is the unqualified version of the type of the left operand. 7489 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7490 // is converted to the type of the assignment expression (above). 7491 // C++ 5.17p1: the type of the assignment expression is that of its left 7492 // operand. 7493 return (getLangOptions().CPlusPlus 7494 ? LHSType : LHSType.getUnqualifiedType()); 7495} 7496 7497// C99 6.5.17 7498static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS, 7499 SourceLocation Loc) { 7500 S.DiagnoseUnusedExprResult(LHS); 7501 7502 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc); 7503 if (LHSResult.isInvalid()) 7504 return QualType(); 7505 7506 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc); 7507 if (RHSResult.isInvalid()) 7508 return QualType(); 7509 RHS = RHSResult.take(); 7510 7511 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7512 // operands, but not unary promotions. 7513 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7514 7515 // So we treat the LHS as a ignored value, and in C++ we allow the 7516 // containing site to determine what should be done with the RHS. 7517 S.IgnoredValueConversions(LHS); 7518 7519 if (!S.getLangOptions().CPlusPlus) { 7520 S.DefaultFunctionArrayLvalueConversion(RHS); 7521 if (!RHS->getType()->isVoidType()) 7522 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type); 7523 } 7524 7525 return RHS->getType(); 7526} 7527 7528/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7529/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7530static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7531 ExprValueKind &VK, 7532 SourceLocation OpLoc, 7533 bool isInc, bool isPrefix) { 7534 if (Op->isTypeDependent()) 7535 return S.Context.DependentTy; 7536 7537 QualType ResType = Op->getType(); 7538 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7539 7540 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) { 7541 // Decrement of bool is not allowed. 7542 if (!isInc) { 7543 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7544 return QualType(); 7545 } 7546 // Increment of bool sets it to true, but is deprecated. 7547 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7548 } else if (ResType->isRealType()) { 7549 // OK! 7550 } else if (ResType->isAnyPointerType()) { 7551 QualType PointeeTy = ResType->getPointeeType(); 7552 7553 // C99 6.5.2.4p2, 6.5.6p2 7554 if (PointeeTy->isVoidType()) { 7555 if (S.getLangOptions().CPlusPlus) { 7556 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 7557 << Op->getSourceRange(); 7558 return QualType(); 7559 } 7560 7561 // Pointer to void is a GNU extension in C. 7562 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 7563 } else if (PointeeTy->isFunctionType()) { 7564 if (S.getLangOptions().CPlusPlus) { 7565 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 7566 << Op->getType() << Op->getSourceRange(); 7567 return QualType(); 7568 } 7569 7570 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 7571 << ResType << Op->getSourceRange(); 7572 } else if (S.RequireCompleteType(OpLoc, PointeeTy, 7573 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type) 7574 << Op->getSourceRange() 7575 << ResType)) 7576 return QualType(); 7577 // Diagnose bad cases where we step over interface counts. 7578 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) { 7579 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 7580 << PointeeTy << Op->getSourceRange(); 7581 return QualType(); 7582 } 7583 } else if (ResType->isAnyComplexType()) { 7584 // C99 does not support ++/-- on complex types, we allow as an extension. 7585 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7586 << ResType << Op->getSourceRange(); 7587 } else if (ResType->isPlaceholderType()) { 7588 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc); 7589 if (PR.isInvalid()) return QualType(); 7590 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7591 isInc, isPrefix); 7592 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) { 7593 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7594 } else { 7595 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7596 << ResType << int(isInc) << Op->getSourceRange(); 7597 return QualType(); 7598 } 7599 // At this point, we know we have a real, complex or pointer type. 7600 // Now make sure the operand is a modifiable lvalue. 7601 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7602 return QualType(); 7603 // In C++, a prefix increment is the same type as the operand. Otherwise 7604 // (in C or with postfix), the increment is the unqualified type of the 7605 // operand. 7606 if (isPrefix && S.getLangOptions().CPlusPlus) { 7607 VK = VK_LValue; 7608 return ResType; 7609 } else { 7610 VK = VK_RValue; 7611 return ResType.getUnqualifiedType(); 7612 } 7613} 7614 7615void Sema::ConvertPropertyForRValue(Expr *&E) { 7616 assert(E->getValueKind() == VK_LValue && 7617 E->getObjectKind() == OK_ObjCProperty); 7618 const ObjCPropertyRefExpr *PRE = E->getObjCProperty(); 7619 7620 ExprValueKind VK = VK_RValue; 7621 if (PRE->isImplicitProperty()) { 7622 if (const ObjCMethodDecl *GetterMethod = 7623 PRE->getImplicitPropertyGetter()) { 7624 QualType Result = GetterMethod->getResultType(); 7625 VK = Expr::getValueKindForType(Result); 7626 } 7627 else { 7628 Diag(PRE->getLocation(), diag::err_getter_not_found) 7629 << PRE->getBase()->getType(); 7630 } 7631 } 7632 7633 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty, 7634 E, 0, VK); 7635 7636 ExprResult Result = MaybeBindToTemporary(E); 7637 if (!Result.isInvalid()) 7638 E = Result.take(); 7639} 7640 7641void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) { 7642 assert(LHS->getValueKind() == VK_LValue && 7643 LHS->getObjectKind() == OK_ObjCProperty); 7644 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty(); 7645 7646 if (PRE->isImplicitProperty()) { 7647 // If using property-dot syntax notation for assignment, and there is a 7648 // setter, RHS expression is being passed to the setter argument. So, 7649 // type conversion (and comparison) is RHS to setter's argument type. 7650 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) { 7651 ObjCMethodDecl::param_iterator P = SetterMD->param_begin(); 7652 LHSTy = (*P)->getType(); 7653 7654 // Otherwise, if the getter returns an l-value, just call that. 7655 } else { 7656 QualType Result = PRE->getImplicitPropertyGetter()->getResultType(); 7657 ExprValueKind VK = Expr::getValueKindForType(Result); 7658 if (VK == VK_LValue) { 7659 LHS = ImplicitCastExpr::Create(Context, LHS->getType(), 7660 CK_GetObjCProperty, LHS, 0, VK); 7661 return; 7662 } 7663 } 7664 } 7665 7666 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) { 7667 InitializedEntity Entity = 7668 InitializedEntity::InitializeParameter(Context, LHSTy); 7669 Expr *Arg = RHS; 7670 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), 7671 Owned(Arg)); 7672 if (!ArgE.isInvalid()) 7673 RHS = ArgE.takeAs<Expr>(); 7674 } 7675} 7676 7677 7678/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7679/// This routine allows us to typecheck complex/recursive expressions 7680/// where the declaration is needed for type checking. We only need to 7681/// handle cases when the expression references a function designator 7682/// or is an lvalue. Here are some examples: 7683/// - &(x) => x 7684/// - &*****f => f for f a function designator. 7685/// - &s.xx => s 7686/// - &s.zz[1].yy -> s, if zz is an array 7687/// - *(x + 1) -> x, if x is an array 7688/// - &"123"[2] -> 0 7689/// - & __real__ x -> x 7690static ValueDecl *getPrimaryDecl(Expr *E) { 7691 switch (E->getStmtClass()) { 7692 case Stmt::DeclRefExprClass: 7693 return cast<DeclRefExpr>(E)->getDecl(); 7694 case Stmt::MemberExprClass: 7695 // If this is an arrow operator, the address is an offset from 7696 // the base's value, so the object the base refers to is 7697 // irrelevant. 7698 if (cast<MemberExpr>(E)->isArrow()) 7699 return 0; 7700 // Otherwise, the expression refers to a part of the base 7701 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7702 case Stmt::ArraySubscriptExprClass: { 7703 // FIXME: This code shouldn't be necessary! We should catch the implicit 7704 // promotion of register arrays earlier. 7705 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7706 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7707 if (ICE->getSubExpr()->getType()->isArrayType()) 7708 return getPrimaryDecl(ICE->getSubExpr()); 7709 } 7710 return 0; 7711 } 7712 case Stmt::UnaryOperatorClass: { 7713 UnaryOperator *UO = cast<UnaryOperator>(E); 7714 7715 switch(UO->getOpcode()) { 7716 case UO_Real: 7717 case UO_Imag: 7718 case UO_Extension: 7719 return getPrimaryDecl(UO->getSubExpr()); 7720 default: 7721 return 0; 7722 } 7723 } 7724 case Stmt::ParenExprClass: 7725 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7726 case Stmt::ImplicitCastExprClass: 7727 // If the result of an implicit cast is an l-value, we care about 7728 // the sub-expression; otherwise, the result here doesn't matter. 7729 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7730 default: 7731 return 0; 7732 } 7733} 7734 7735/// CheckAddressOfOperand - The operand of & must be either a function 7736/// designator or an lvalue designating an object. If it is an lvalue, the 7737/// object cannot be declared with storage class register or be a bit field. 7738/// Note: The usual conversions are *not* applied to the operand of the & 7739/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7740/// In C++, the operand might be an overloaded function name, in which case 7741/// we allow the '&' but retain the overloaded-function type. 7742static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp, 7743 SourceLocation OpLoc) { 7744 if (OrigOp->isTypeDependent()) 7745 return S.Context.DependentTy; 7746 if (OrigOp->getType() == S.Context.OverloadTy) 7747 return S.Context.OverloadTy; 7748 7749 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc); 7750 if (PR.isInvalid()) return QualType(); 7751 OrigOp = PR.take(); 7752 7753 // Make sure to ignore parentheses in subsequent checks 7754 Expr *op = OrigOp->IgnoreParens(); 7755 7756 if (S.getLangOptions().C99) { 7757 // Implement C99-only parts of addressof rules. 7758 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7759 if (uOp->getOpcode() == UO_Deref) 7760 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7761 // (assuming the deref expression is valid). 7762 return uOp->getSubExpr()->getType(); 7763 } 7764 // Technically, there should be a check for array subscript 7765 // expressions here, but the result of one is always an lvalue anyway. 7766 } 7767 ValueDecl *dcl = getPrimaryDecl(op); 7768 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7769 7770 if (lval == Expr::LV_ClassTemporary) { 7771 bool sfinae = S.isSFINAEContext(); 7772 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7773 : diag::ext_typecheck_addrof_class_temporary) 7774 << op->getType() << op->getSourceRange(); 7775 if (sfinae) 7776 return QualType(); 7777 } else if (isa<ObjCSelectorExpr>(op)) { 7778 return S.Context.getPointerType(op->getType()); 7779 } else if (lval == Expr::LV_MemberFunction) { 7780 // If it's an instance method, make a member pointer. 7781 // The expression must have exactly the form &A::foo. 7782 7783 // If the underlying expression isn't a decl ref, give up. 7784 if (!isa<DeclRefExpr>(op)) { 7785 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7786 << OrigOp->getSourceRange(); 7787 return QualType(); 7788 } 7789 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7790 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7791 7792 // The id-expression was parenthesized. 7793 if (OrigOp != DRE) { 7794 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7795 << OrigOp->getSourceRange(); 7796 7797 // The method was named without a qualifier. 7798 } else if (!DRE->getQualifier()) { 7799 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7800 << op->getSourceRange(); 7801 } 7802 7803 return S.Context.getMemberPointerType(op->getType(), 7804 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7805 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7806 // C99 6.5.3.2p1 7807 // The operand must be either an l-value or a function designator 7808 if (!op->getType()->isFunctionType()) { 7809 // FIXME: emit more specific diag... 7810 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7811 << op->getSourceRange(); 7812 return QualType(); 7813 } 7814 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7815 // The operand cannot be a bit-field 7816 S.Diag(OpLoc, diag::err_typecheck_address_of) 7817 << "bit-field" << op->getSourceRange(); 7818 return QualType(); 7819 } else if (op->getObjectKind() == OK_VectorComponent) { 7820 // The operand cannot be an element of a vector 7821 S.Diag(OpLoc, diag::err_typecheck_address_of) 7822 << "vector element" << op->getSourceRange(); 7823 return QualType(); 7824 } else if (op->getObjectKind() == OK_ObjCProperty) { 7825 // cannot take address of a property expression. 7826 S.Diag(OpLoc, diag::err_typecheck_address_of) 7827 << "property expression" << op->getSourceRange(); 7828 return QualType(); 7829 } else if (dcl) { // C99 6.5.3.2p1 7830 // We have an lvalue with a decl. Make sure the decl is not declared 7831 // with the register storage-class specifier. 7832 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7833 // in C++ it is not error to take address of a register 7834 // variable (c++03 7.1.1P3) 7835 if (vd->getStorageClass() == SC_Register && 7836 !S.getLangOptions().CPlusPlus) { 7837 S.Diag(OpLoc, diag::err_typecheck_address_of) 7838 << "register variable" << op->getSourceRange(); 7839 return QualType(); 7840 } 7841 } else if (isa<FunctionTemplateDecl>(dcl)) { 7842 return S.Context.OverloadTy; 7843 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7844 // Okay: we can take the address of a field. 7845 // Could be a pointer to member, though, if there is an explicit 7846 // scope qualifier for the class. 7847 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7848 DeclContext *Ctx = dcl->getDeclContext(); 7849 if (Ctx && Ctx->isRecord()) { 7850 if (dcl->getType()->isReferenceType()) { 7851 S.Diag(OpLoc, 7852 diag::err_cannot_form_pointer_to_member_of_reference_type) 7853 << dcl->getDeclName() << dcl->getType(); 7854 return QualType(); 7855 } 7856 7857 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7858 Ctx = Ctx->getParent(); 7859 return S.Context.getMemberPointerType(op->getType(), 7860 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7861 } 7862 } 7863 } else if (!isa<FunctionDecl>(dcl)) 7864 assert(0 && "Unknown/unexpected decl type"); 7865 } 7866 7867 if (lval == Expr::LV_IncompleteVoidType) { 7868 // Taking the address of a void variable is technically illegal, but we 7869 // allow it in cases which are otherwise valid. 7870 // Example: "extern void x; void* y = &x;". 7871 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 7872 } 7873 7874 // If the operand has type "type", the result has type "pointer to type". 7875 if (op->getType()->isObjCObjectType()) 7876 return S.Context.getObjCObjectPointerType(op->getType()); 7877 return S.Context.getPointerType(op->getType()); 7878} 7879 7880/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 7881static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 7882 SourceLocation OpLoc) { 7883 if (Op->isTypeDependent()) 7884 return S.Context.DependentTy; 7885 7886 S.UsualUnaryConversions(Op); 7887 QualType OpTy = Op->getType(); 7888 QualType Result; 7889 7890 // Note that per both C89 and C99, indirection is always legal, even if OpTy 7891 // is an incomplete type or void. It would be possible to warn about 7892 // dereferencing a void pointer, but it's completely well-defined, and such a 7893 // warning is unlikely to catch any mistakes. 7894 if (const PointerType *PT = OpTy->getAs<PointerType>()) 7895 Result = PT->getPointeeType(); 7896 else if (const ObjCObjectPointerType *OPT = 7897 OpTy->getAs<ObjCObjectPointerType>()) 7898 Result = OPT->getPointeeType(); 7899 else { 7900 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc); 7901 if (PR.isInvalid()) return QualType(); 7902 if (PR.take() != Op) 7903 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 7904 } 7905 7906 if (Result.isNull()) { 7907 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 7908 << OpTy << Op->getSourceRange(); 7909 return QualType(); 7910 } 7911 7912 // Dereferences are usually l-values... 7913 VK = VK_LValue; 7914 7915 // ...except that certain expressions are never l-values in C. 7916 if (!S.getLangOptions().CPlusPlus && 7917 IsCForbiddenLValueType(S.Context, Result)) 7918 VK = VK_RValue; 7919 7920 return Result; 7921} 7922 7923static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 7924 tok::TokenKind Kind) { 7925 BinaryOperatorKind Opc; 7926 switch (Kind) { 7927 default: assert(0 && "Unknown binop!"); 7928 case tok::periodstar: Opc = BO_PtrMemD; break; 7929 case tok::arrowstar: Opc = BO_PtrMemI; break; 7930 case tok::star: Opc = BO_Mul; break; 7931 case tok::slash: Opc = BO_Div; break; 7932 case tok::percent: Opc = BO_Rem; break; 7933 case tok::plus: Opc = BO_Add; break; 7934 case tok::minus: Opc = BO_Sub; break; 7935 case tok::lessless: Opc = BO_Shl; break; 7936 case tok::greatergreater: Opc = BO_Shr; break; 7937 case tok::lessequal: Opc = BO_LE; break; 7938 case tok::less: Opc = BO_LT; break; 7939 case tok::greaterequal: Opc = BO_GE; break; 7940 case tok::greater: Opc = BO_GT; break; 7941 case tok::exclaimequal: Opc = BO_NE; break; 7942 case tok::equalequal: Opc = BO_EQ; break; 7943 case tok::amp: Opc = BO_And; break; 7944 case tok::caret: Opc = BO_Xor; break; 7945 case tok::pipe: Opc = BO_Or; break; 7946 case tok::ampamp: Opc = BO_LAnd; break; 7947 case tok::pipepipe: Opc = BO_LOr; break; 7948 case tok::equal: Opc = BO_Assign; break; 7949 case tok::starequal: Opc = BO_MulAssign; break; 7950 case tok::slashequal: Opc = BO_DivAssign; break; 7951 case tok::percentequal: Opc = BO_RemAssign; break; 7952 case tok::plusequal: Opc = BO_AddAssign; break; 7953 case tok::minusequal: Opc = BO_SubAssign; break; 7954 case tok::lesslessequal: Opc = BO_ShlAssign; break; 7955 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 7956 case tok::ampequal: Opc = BO_AndAssign; break; 7957 case tok::caretequal: Opc = BO_XorAssign; break; 7958 case tok::pipeequal: Opc = BO_OrAssign; break; 7959 case tok::comma: Opc = BO_Comma; break; 7960 } 7961 return Opc; 7962} 7963 7964static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 7965 tok::TokenKind Kind) { 7966 UnaryOperatorKind Opc; 7967 switch (Kind) { 7968 default: assert(0 && "Unknown unary op!"); 7969 case tok::plusplus: Opc = UO_PreInc; break; 7970 case tok::minusminus: Opc = UO_PreDec; break; 7971 case tok::amp: Opc = UO_AddrOf; break; 7972 case tok::star: Opc = UO_Deref; break; 7973 case tok::plus: Opc = UO_Plus; break; 7974 case tok::minus: Opc = UO_Minus; break; 7975 case tok::tilde: Opc = UO_Not; break; 7976 case tok::exclaim: Opc = UO_LNot; break; 7977 case tok::kw___real: Opc = UO_Real; break; 7978 case tok::kw___imag: Opc = UO_Imag; break; 7979 case tok::kw___extension__: Opc = UO_Extension; break; 7980 } 7981 return Opc; 7982} 7983 7984/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 7985/// This warning is only emitted for builtin assignment operations. It is also 7986/// suppressed in the event of macro expansions. 7987static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs, 7988 SourceLocation OpLoc) { 7989 if (!S.ActiveTemplateInstantiations.empty()) 7990 return; 7991 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 7992 return; 7993 lhs = lhs->IgnoreParenImpCasts(); 7994 rhs = rhs->IgnoreParenImpCasts(); 7995 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs); 7996 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs); 7997 if (!LeftDeclRef || !RightDeclRef || 7998 LeftDeclRef->getLocation().isMacroID() || 7999 RightDeclRef->getLocation().isMacroID()) 8000 return; 8001 const ValueDecl *LeftDecl = 8002 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl()); 8003 const ValueDecl *RightDecl = 8004 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl()); 8005 if (LeftDecl != RightDecl) 8006 return; 8007 if (LeftDecl->getType().isVolatileQualified()) 8008 return; 8009 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>()) 8010 if (RefTy->getPointeeType().isVolatileQualified()) 8011 return; 8012 8013 S.Diag(OpLoc, diag::warn_self_assignment) 8014 << LeftDeclRef->getType() 8015 << lhs->getSourceRange() << rhs->getSourceRange(); 8016} 8017 8018/// CreateBuiltinBinOp - Creates a new built-in binary operation with 8019/// operator @p Opc at location @c TokLoc. This routine only supports 8020/// built-in operations; ActOnBinOp handles overloaded operators. 8021ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8022 BinaryOperatorKind Opc, 8023 Expr *lhs, Expr *rhs) { 8024 QualType ResultTy; // Result type of the binary operator. 8025 // The following two variables are used for compound assignment operators 8026 QualType CompLHSTy; // Type of LHS after promotions for computation 8027 QualType CompResultTy; // Type of computation result 8028 ExprValueKind VK = VK_RValue; 8029 ExprObjectKind OK = OK_Ordinary; 8030 8031 switch (Opc) { 8032 case BO_Assign: 8033 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 8034 if (getLangOptions().CPlusPlus && 8035 lhs->getObjectKind() != OK_ObjCProperty) { 8036 VK = lhs->getValueKind(); 8037 OK = lhs->getObjectKind(); 8038 } 8039 if (!ResultTy.isNull()) 8040 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc); 8041 break; 8042 case BO_PtrMemD: 8043 case BO_PtrMemI: 8044 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc, 8045 Opc == BO_PtrMemI); 8046 break; 8047 case BO_Mul: 8048 case BO_Div: 8049 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false, 8050 Opc == BO_Div); 8051 break; 8052 case BO_Rem: 8053 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 8054 break; 8055 case BO_Add: 8056 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 8057 break; 8058 case BO_Sub: 8059 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 8060 break; 8061 case BO_Shl: 8062 case BO_Shr: 8063 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc); 8064 break; 8065 case BO_LE: 8066 case BO_LT: 8067 case BO_GE: 8068 case BO_GT: 8069 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 8070 break; 8071 case BO_EQ: 8072 case BO_NE: 8073 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 8074 break; 8075 case BO_And: 8076 case BO_Xor: 8077 case BO_Or: 8078 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 8079 break; 8080 case BO_LAnd: 8081 case BO_LOr: 8082 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc); 8083 break; 8084 case BO_MulAssign: 8085 case BO_DivAssign: 8086 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true, 8087 Opc == BO_DivAssign); 8088 CompLHSTy = CompResultTy; 8089 if (!CompResultTy.isNull()) 8090 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8091 break; 8092 case BO_RemAssign: 8093 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 8094 CompLHSTy = CompResultTy; 8095 if (!CompResultTy.isNull()) 8096 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8097 break; 8098 case BO_AddAssign: 8099 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 8100 if (!CompResultTy.isNull()) 8101 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8102 break; 8103 case BO_SubAssign: 8104 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 8105 if (!CompResultTy.isNull()) 8106 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8107 break; 8108 case BO_ShlAssign: 8109 case BO_ShrAssign: 8110 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true); 8111 CompLHSTy = CompResultTy; 8112 if (!CompResultTy.isNull()) 8113 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8114 break; 8115 case BO_AndAssign: 8116 case BO_XorAssign: 8117 case BO_OrAssign: 8118 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 8119 CompLHSTy = CompResultTy; 8120 if (!CompResultTy.isNull()) 8121 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 8122 break; 8123 case BO_Comma: 8124 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc); 8125 if (getLangOptions().CPlusPlus) { 8126 VK = rhs->getValueKind(); 8127 OK = rhs->getObjectKind(); 8128 } 8129 break; 8130 } 8131 if (ResultTy.isNull()) 8132 return ExprError(); 8133 if (CompResultTy.isNull()) 8134 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, 8135 VK, OK, OpLoc)); 8136 8137 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) { 8138 VK = VK_LValue; 8139 OK = lhs->getObjectKind(); 8140 } 8141 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 8142 VK, OK, CompLHSTy, 8143 CompResultTy, OpLoc)); 8144} 8145 8146/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps 8147/// ParenRange in parentheses. 8148static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8149 const PartialDiagnostic &PD, 8150 const PartialDiagnostic &FirstNote, 8151 SourceRange FirstParenRange, 8152 const PartialDiagnostic &SecondNote, 8153 SourceRange SecondParenRange) { 8154 Self.Diag(Loc, PD); 8155 8156 if (!FirstNote.getDiagID()) 8157 return; 8158 8159 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd()); 8160 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 8161 // We can't display the parentheses, so just return. 8162 return; 8163 } 8164 8165 Self.Diag(Loc, FirstNote) 8166 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(") 8167 << FixItHint::CreateInsertion(EndLoc, ")"); 8168 8169 if (!SecondNote.getDiagID()) 8170 return; 8171 8172 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd()); 8173 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 8174 // We can't display the parentheses, so just dig the 8175 // warning/error and return. 8176 Self.Diag(Loc, SecondNote); 8177 return; 8178 } 8179 8180 Self.Diag(Loc, SecondNote) 8181 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(") 8182 << FixItHint::CreateInsertion(EndLoc, ")"); 8183} 8184 8185/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8186/// operators are mixed in a way that suggests that the programmer forgot that 8187/// comparison operators have higher precedence. The most typical example of 8188/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8189static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8190 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 8191 typedef BinaryOperator BinOp; 8192 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 8193 rhsopc = static_cast<BinOp::Opcode>(-1); 8194 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 8195 lhsopc = BO->getOpcode(); 8196 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 8197 rhsopc = BO->getOpcode(); 8198 8199 // Subs are not binary operators. 8200 if (lhsopc == -1 && rhsopc == -1) 8201 return; 8202 8203 // Bitwise operations are sometimes used as eager logical ops. 8204 // Don't diagnose this. 8205 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 8206 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 8207 return; 8208 8209 if (BinOp::isComparisonOp(lhsopc)) 8210 SuggestParentheses(Self, OpLoc, 8211 Self.PDiag(diag::warn_precedence_bitwise_rel) 8212 << SourceRange(lhs->getLocStart(), OpLoc) 8213 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc), 8214 Self.PDiag(diag::note_precedence_bitwise_first) 8215 << BinOp::getOpcodeStr(Opc), 8216 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()), 8217 Self.PDiag(diag::note_precedence_bitwise_silence) 8218 << BinOp::getOpcodeStr(lhsopc), 8219 lhs->getSourceRange()); 8220 else if (BinOp::isComparisonOp(rhsopc)) 8221 SuggestParentheses(Self, OpLoc, 8222 Self.PDiag(diag::warn_precedence_bitwise_rel) 8223 << SourceRange(OpLoc, rhs->getLocEnd()) 8224 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc), 8225 Self.PDiag(diag::note_precedence_bitwise_first) 8226 << BinOp::getOpcodeStr(Opc), 8227 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()), 8228 Self.PDiag(diag::note_precedence_bitwise_silence) 8229 << BinOp::getOpcodeStr(rhsopc), 8230 rhs->getSourceRange()); 8231} 8232 8233/// \brief It accepts a '&&' expr that is inside a '||' one. 8234/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8235/// in parentheses. 8236static void 8237EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8238 Expr *E) { 8239 assert(isa<BinaryOperator>(E) && 8240 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd); 8241 SuggestParentheses(Self, OpLoc, 8242 Self.PDiag(diag::warn_logical_and_in_logical_or) 8243 << E->getSourceRange(), 8244 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 8245 E->getSourceRange(), 8246 Self.PDiag(0), SourceRange()); 8247} 8248 8249/// \brief Returns true if the given expression can be evaluated as a constant 8250/// 'true'. 8251static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8252 bool Res; 8253 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8254} 8255 8256/// \brief Returns true if the given expression can be evaluated as a constant 8257/// 'false'. 8258static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8259 bool Res; 8260 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8261} 8262 8263/// \brief Look for '&&' in the left hand of a '||' expr. 8264static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8265 Expr *OrLHS, Expr *OrRHS) { 8266 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) { 8267 if (Bop->getOpcode() == BO_LAnd) { 8268 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8269 if (EvaluatesAsFalse(S, OrRHS)) 8270 return; 8271 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8272 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8273 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8274 } else if (Bop->getOpcode() == BO_LOr) { 8275 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8276 // If it's "a || b && 1 || c" we didn't warn earlier for 8277 // "a || b && 1", but warn now. 8278 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8279 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8280 } 8281 } 8282 } 8283} 8284 8285/// \brief Look for '&&' in the right hand of a '||' expr. 8286static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8287 Expr *OrLHS, Expr *OrRHS) { 8288 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) { 8289 if (Bop->getOpcode() == BO_LAnd) { 8290 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8291 if (EvaluatesAsFalse(S, OrLHS)) 8292 return; 8293 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8294 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8295 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8296 } 8297 } 8298} 8299 8300/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8301/// precedence. 8302static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8303 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 8304 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8305 if (BinaryOperator::isBitwiseOp(Opc)) 8306 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 8307 8308 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8309 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8310 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8311 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs); 8312 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs); 8313 } 8314} 8315 8316// Binary Operators. 'Tok' is the token for the operator. 8317ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8318 tok::TokenKind Kind, 8319 Expr *lhs, Expr *rhs) { 8320 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8321 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 8322 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 8323 8324 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8325 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 8326 8327 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 8328} 8329 8330ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8331 BinaryOperatorKind Opc, 8332 Expr *lhs, Expr *rhs) { 8333 if (getLangOptions().CPlusPlus) { 8334 bool UseBuiltinOperator; 8335 8336 if (lhs->isTypeDependent() || rhs->isTypeDependent()) { 8337 UseBuiltinOperator = false; 8338 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) { 8339 UseBuiltinOperator = true; 8340 } else { 8341 UseBuiltinOperator = !lhs->getType()->isOverloadableType() && 8342 !rhs->getType()->isOverloadableType(); 8343 } 8344 8345 if (!UseBuiltinOperator) { 8346 // Find all of the overloaded operators visible from this 8347 // point. We perform both an operator-name lookup from the local 8348 // scope and an argument-dependent lookup based on the types of 8349 // the arguments. 8350 UnresolvedSet<16> Functions; 8351 OverloadedOperatorKind OverOp 8352 = BinaryOperator::getOverloadedOperator(Opc); 8353 if (S && OverOp != OO_None) 8354 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 8355 Functions); 8356 8357 // Build the (potentially-overloaded, potentially-dependent) 8358 // binary operation. 8359 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 8360 } 8361 } 8362 8363 // Build a built-in binary operation. 8364 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 8365} 8366 8367ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8368 UnaryOperatorKind Opc, 8369 Expr *Input) { 8370 ExprValueKind VK = VK_RValue; 8371 ExprObjectKind OK = OK_Ordinary; 8372 QualType resultType; 8373 switch (Opc) { 8374 case UO_PreInc: 8375 case UO_PreDec: 8376 case UO_PostInc: 8377 case UO_PostDec: 8378 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc, 8379 Opc == UO_PreInc || 8380 Opc == UO_PostInc, 8381 Opc == UO_PreInc || 8382 Opc == UO_PreDec); 8383 break; 8384 case UO_AddrOf: 8385 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8386 break; 8387 case UO_Deref: 8388 DefaultFunctionArrayLvalueConversion(Input); 8389 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc); 8390 break; 8391 case UO_Plus: 8392 case UO_Minus: 8393 UsualUnaryConversions(Input); 8394 resultType = Input->getType(); 8395 if (resultType->isDependentType()) 8396 break; 8397 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8398 resultType->isVectorType()) 8399 break; 8400 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 8401 resultType->isEnumeralType()) 8402 break; 8403 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 8404 Opc == UO_Plus && 8405 resultType->isPointerType()) 8406 break; 8407 else if (resultType->isPlaceholderType()) { 8408 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 8409 if (PR.isInvalid()) return ExprError(); 8410 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take()); 8411 } 8412 8413 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8414 << resultType << Input->getSourceRange()); 8415 case UO_Not: // bitwise complement 8416 UsualUnaryConversions(Input); 8417 resultType = Input->getType(); 8418 if (resultType->isDependentType()) 8419 break; 8420 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8421 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8422 // C99 does not support '~' for complex conjugation. 8423 Diag(OpLoc, diag::ext_integer_complement_complex) 8424 << resultType << Input->getSourceRange(); 8425 else if (resultType->hasIntegerRepresentation()) 8426 break; 8427 else if (resultType->isPlaceholderType()) { 8428 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 8429 if (PR.isInvalid()) return ExprError(); 8430 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take()); 8431 } else { 8432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8433 << resultType << Input->getSourceRange()); 8434 } 8435 break; 8436 case UO_LNot: // logical negation 8437 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8438 DefaultFunctionArrayLvalueConversion(Input); 8439 resultType = Input->getType(); 8440 if (resultType->isDependentType()) 8441 break; 8442 if (resultType->isScalarType()) { // C99 6.5.3.3p1 8443 // ok, fallthrough 8444 } else if (resultType->isPlaceholderType()) { 8445 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 8446 if (PR.isInvalid()) return ExprError(); 8447 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take()); 8448 } else { 8449 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8450 << resultType << Input->getSourceRange()); 8451 } 8452 8453 // LNot always has type int. C99 6.5.3.3p5. 8454 // In C++, it's bool. C++ 5.3.1p8 8455 resultType = Context.getLogicalOperationType(); 8456 break; 8457 case UO_Real: 8458 case UO_Imag: 8459 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8460 // _Real and _Imag map ordinary l-values into ordinary l-values. 8461 if (Input->getValueKind() != VK_RValue && 8462 Input->getObjectKind() == OK_Ordinary) 8463 VK = Input->getValueKind(); 8464 break; 8465 case UO_Extension: 8466 resultType = Input->getType(); 8467 VK = Input->getValueKind(); 8468 OK = Input->getObjectKind(); 8469 break; 8470 } 8471 if (resultType.isNull()) 8472 return ExprError(); 8473 8474 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, 8475 VK, OK, OpLoc)); 8476} 8477 8478ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8479 UnaryOperatorKind Opc, 8480 Expr *Input) { 8481 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 8482 UnaryOperator::getOverloadedOperator(Opc) != OO_None) { 8483 // Find all of the overloaded operators visible from this 8484 // point. We perform both an operator-name lookup from the local 8485 // scope and an argument-dependent lookup based on the types of 8486 // the arguments. 8487 UnresolvedSet<16> Functions; 8488 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8489 if (S && OverOp != OO_None) 8490 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8491 Functions); 8492 8493 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8494 } 8495 8496 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8497} 8498 8499// Unary Operators. 'Tok' is the token for the operator. 8500ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8501 tok::TokenKind Op, Expr *Input) { 8502 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8503} 8504 8505/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8506ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8507 LabelDecl *TheDecl) { 8508 TheDecl->setUsed(); 8509 // Create the AST node. The address of a label always has type 'void*'. 8510 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8511 Context.getPointerType(Context.VoidTy))); 8512} 8513 8514ExprResult 8515Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8516 SourceLocation RPLoc) { // "({..})" 8517 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8518 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8519 8520 bool isFileScope 8521 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8522 if (isFileScope) 8523 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8524 8525 // FIXME: there are a variety of strange constraints to enforce here, for 8526 // example, it is not possible to goto into a stmt expression apparently. 8527 // More semantic analysis is needed. 8528 8529 // If there are sub stmts in the compound stmt, take the type of the last one 8530 // as the type of the stmtexpr. 8531 QualType Ty = Context.VoidTy; 8532 bool StmtExprMayBindToTemp = false; 8533 if (!Compound->body_empty()) { 8534 Stmt *LastStmt = Compound->body_back(); 8535 LabelStmt *LastLabelStmt = 0; 8536 // If LastStmt is a label, skip down through into the body. 8537 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8538 LastLabelStmt = Label; 8539 LastStmt = Label->getSubStmt(); 8540 } 8541 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) { 8542 // Do function/array conversion on the last expression, but not 8543 // lvalue-to-rvalue. However, initialize an unqualified type. 8544 DefaultFunctionArrayConversion(LastExpr); 8545 Ty = LastExpr->getType().getUnqualifiedType(); 8546 8547 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) { 8548 ExprResult Res = PerformCopyInitialization( 8549 InitializedEntity::InitializeResult(LPLoc, 8550 Ty, 8551 false), 8552 SourceLocation(), 8553 Owned(LastExpr)); 8554 if (Res.isInvalid()) 8555 return ExprError(); 8556 if ((LastExpr = Res.takeAs<Expr>())) { 8557 if (!LastLabelStmt) 8558 Compound->setLastStmt(LastExpr); 8559 else 8560 LastLabelStmt->setSubStmt(LastExpr); 8561 StmtExprMayBindToTemp = true; 8562 } 8563 } 8564 } 8565 } 8566 8567 // FIXME: Check that expression type is complete/non-abstract; statement 8568 // expressions are not lvalues. 8569 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8570 if (StmtExprMayBindToTemp) 8571 return MaybeBindToTemporary(ResStmtExpr); 8572 return Owned(ResStmtExpr); 8573} 8574 8575ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8576 TypeSourceInfo *TInfo, 8577 OffsetOfComponent *CompPtr, 8578 unsigned NumComponents, 8579 SourceLocation RParenLoc) { 8580 QualType ArgTy = TInfo->getType(); 8581 bool Dependent = ArgTy->isDependentType(); 8582 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8583 8584 // We must have at least one component that refers to the type, and the first 8585 // one is known to be a field designator. Verify that the ArgTy represents 8586 // a struct/union/class. 8587 if (!Dependent && !ArgTy->isRecordType()) 8588 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8589 << ArgTy << TypeRange); 8590 8591 // Type must be complete per C99 7.17p3 because a declaring a variable 8592 // with an incomplete type would be ill-formed. 8593 if (!Dependent 8594 && RequireCompleteType(BuiltinLoc, ArgTy, 8595 PDiag(diag::err_offsetof_incomplete_type) 8596 << TypeRange)) 8597 return ExprError(); 8598 8599 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8600 // GCC extension, diagnose them. 8601 // FIXME: This diagnostic isn't actually visible because the location is in 8602 // a system header! 8603 if (NumComponents != 1) 8604 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8605 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8606 8607 bool DidWarnAboutNonPOD = false; 8608 QualType CurrentType = ArgTy; 8609 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8610 llvm::SmallVector<OffsetOfNode, 4> Comps; 8611 llvm::SmallVector<Expr*, 4> Exprs; 8612 for (unsigned i = 0; i != NumComponents; ++i) { 8613 const OffsetOfComponent &OC = CompPtr[i]; 8614 if (OC.isBrackets) { 8615 // Offset of an array sub-field. TODO: Should we allow vector elements? 8616 if (!CurrentType->isDependentType()) { 8617 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8618 if(!AT) 8619 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8620 << CurrentType); 8621 CurrentType = AT->getElementType(); 8622 } else 8623 CurrentType = Context.DependentTy; 8624 8625 // The expression must be an integral expression. 8626 // FIXME: An integral constant expression? 8627 Expr *Idx = static_cast<Expr*>(OC.U.E); 8628 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 8629 !Idx->getType()->isIntegerType()) 8630 return ExprError(Diag(Idx->getLocStart(), 8631 diag::err_typecheck_subscript_not_integer) 8632 << Idx->getSourceRange()); 8633 8634 // Record this array index. 8635 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 8636 Exprs.push_back(Idx); 8637 continue; 8638 } 8639 8640 // Offset of a field. 8641 if (CurrentType->isDependentType()) { 8642 // We have the offset of a field, but we can't look into the dependent 8643 // type. Just record the identifier of the field. 8644 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 8645 CurrentType = Context.DependentTy; 8646 continue; 8647 } 8648 8649 // We need to have a complete type to look into. 8650 if (RequireCompleteType(OC.LocStart, CurrentType, 8651 diag::err_offsetof_incomplete_type)) 8652 return ExprError(); 8653 8654 // Look for the designated field. 8655 const RecordType *RC = CurrentType->getAs<RecordType>(); 8656 if (!RC) 8657 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 8658 << CurrentType); 8659 RecordDecl *RD = RC->getDecl(); 8660 8661 // C++ [lib.support.types]p5: 8662 // The macro offsetof accepts a restricted set of type arguments in this 8663 // International Standard. type shall be a POD structure or a POD union 8664 // (clause 9). 8665 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8666 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 8667 DiagRuntimeBehavior(BuiltinLoc, 0, 8668 PDiag(diag::warn_offsetof_non_pod_type) 8669 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 8670 << CurrentType)) 8671 DidWarnAboutNonPOD = true; 8672 } 8673 8674 // Look for the field. 8675 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 8676 LookupQualifiedName(R, RD); 8677 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 8678 IndirectFieldDecl *IndirectMemberDecl = 0; 8679 if (!MemberDecl) { 8680 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 8681 MemberDecl = IndirectMemberDecl->getAnonField(); 8682 } 8683 8684 if (!MemberDecl) 8685 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 8686 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 8687 OC.LocEnd)); 8688 8689 // C99 7.17p3: 8690 // (If the specified member is a bit-field, the behavior is undefined.) 8691 // 8692 // We diagnose this as an error. 8693 if (MemberDecl->getBitWidth()) { 8694 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 8695 << MemberDecl->getDeclName() 8696 << SourceRange(BuiltinLoc, RParenLoc); 8697 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 8698 return ExprError(); 8699 } 8700 8701 RecordDecl *Parent = MemberDecl->getParent(); 8702 if (IndirectMemberDecl) 8703 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 8704 8705 // If the member was found in a base class, introduce OffsetOfNodes for 8706 // the base class indirections. 8707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8708 /*DetectVirtual=*/false); 8709 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 8710 CXXBasePath &Path = Paths.front(); 8711 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 8712 B != BEnd; ++B) 8713 Comps.push_back(OffsetOfNode(B->Base)); 8714 } 8715 8716 if (IndirectMemberDecl) { 8717 for (IndirectFieldDecl::chain_iterator FI = 8718 IndirectMemberDecl->chain_begin(), 8719 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 8720 assert(isa<FieldDecl>(*FI)); 8721 Comps.push_back(OffsetOfNode(OC.LocStart, 8722 cast<FieldDecl>(*FI), OC.LocEnd)); 8723 } 8724 } else 8725 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 8726 8727 CurrentType = MemberDecl->getType().getNonReferenceType(); 8728 } 8729 8730 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 8731 TInfo, Comps.data(), Comps.size(), 8732 Exprs.data(), Exprs.size(), RParenLoc)); 8733} 8734 8735ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 8736 SourceLocation BuiltinLoc, 8737 SourceLocation TypeLoc, 8738 ParsedType argty, 8739 OffsetOfComponent *CompPtr, 8740 unsigned NumComponents, 8741 SourceLocation RPLoc) { 8742 8743 TypeSourceInfo *ArgTInfo; 8744 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo); 8745 if (ArgTy.isNull()) 8746 return ExprError(); 8747 8748 if (!ArgTInfo) 8749 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 8750 8751 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 8752 RPLoc); 8753} 8754 8755 8756ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 8757 Expr *CondExpr, 8758 Expr *LHSExpr, Expr *RHSExpr, 8759 SourceLocation RPLoc) { 8760 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 8761 8762 ExprValueKind VK = VK_RValue; 8763 ExprObjectKind OK = OK_Ordinary; 8764 QualType resType; 8765 bool ValueDependent = false; 8766 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 8767 resType = Context.DependentTy; 8768 ValueDependent = true; 8769 } else { 8770 // The conditional expression is required to be a constant expression. 8771 llvm::APSInt condEval(32); 8772 SourceLocation ExpLoc; 8773 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 8774 return ExprError(Diag(ExpLoc, 8775 diag::err_typecheck_choose_expr_requires_constant) 8776 << CondExpr->getSourceRange()); 8777 8778 // If the condition is > zero, then the AST type is the same as the LSHExpr. 8779 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 8780 8781 resType = ActiveExpr->getType(); 8782 ValueDependent = ActiveExpr->isValueDependent(); 8783 VK = ActiveExpr->getValueKind(); 8784 OK = ActiveExpr->getObjectKind(); 8785 } 8786 8787 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 8788 resType, VK, OK, RPLoc, 8789 resType->isDependentType(), 8790 ValueDependent)); 8791} 8792 8793//===----------------------------------------------------------------------===// 8794// Clang Extensions. 8795//===----------------------------------------------------------------------===// 8796 8797/// ActOnBlockStart - This callback is invoked when a block literal is started. 8798void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 8799 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 8800 PushBlockScope(BlockScope, Block); 8801 CurContext->addDecl(Block); 8802 if (BlockScope) 8803 PushDeclContext(BlockScope, Block); 8804 else 8805 CurContext = Block; 8806} 8807 8808void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 8809 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 8810 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 8811 BlockScopeInfo *CurBlock = getCurBlock(); 8812 8813 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 8814 QualType T = Sig->getType(); 8815 8816 // GetTypeForDeclarator always produces a function type for a block 8817 // literal signature. Furthermore, it is always a FunctionProtoType 8818 // unless the function was written with a typedef. 8819 assert(T->isFunctionType() && 8820 "GetTypeForDeclarator made a non-function block signature"); 8821 8822 // Look for an explicit signature in that function type. 8823 FunctionProtoTypeLoc ExplicitSignature; 8824 8825 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 8826 if (isa<FunctionProtoTypeLoc>(tmp)) { 8827 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 8828 8829 // Check whether that explicit signature was synthesized by 8830 // GetTypeForDeclarator. If so, don't save that as part of the 8831 // written signature. 8832 if (ExplicitSignature.getLParenLoc() == 8833 ExplicitSignature.getRParenLoc()) { 8834 // This would be much cheaper if we stored TypeLocs instead of 8835 // TypeSourceInfos. 8836 TypeLoc Result = ExplicitSignature.getResultLoc(); 8837 unsigned Size = Result.getFullDataSize(); 8838 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 8839 Sig->getTypeLoc().initializeFullCopy(Result, Size); 8840 8841 ExplicitSignature = FunctionProtoTypeLoc(); 8842 } 8843 } 8844 8845 CurBlock->TheDecl->setSignatureAsWritten(Sig); 8846 CurBlock->FunctionType = T; 8847 8848 const FunctionType *Fn = T->getAs<FunctionType>(); 8849 QualType RetTy = Fn->getResultType(); 8850 bool isVariadic = 8851 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 8852 8853 CurBlock->TheDecl->setIsVariadic(isVariadic); 8854 8855 // Don't allow returning a objc interface by value. 8856 if (RetTy->isObjCObjectType()) { 8857 Diag(ParamInfo.getSourceRange().getBegin(), 8858 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 8859 return; 8860 } 8861 8862 // Context.DependentTy is used as a placeholder for a missing block 8863 // return type. TODO: what should we do with declarators like: 8864 // ^ * { ... } 8865 // If the answer is "apply template argument deduction".... 8866 if (RetTy != Context.DependentTy) 8867 CurBlock->ReturnType = RetTy; 8868 8869 // Push block parameters from the declarator if we had them. 8870 llvm::SmallVector<ParmVarDecl*, 8> Params; 8871 if (ExplicitSignature) { 8872 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 8873 ParmVarDecl *Param = ExplicitSignature.getArg(I); 8874 if (Param->getIdentifier() == 0 && 8875 !Param->isImplicit() && 8876 !Param->isInvalidDecl() && 8877 !getLangOptions().CPlusPlus) 8878 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8879 Params.push_back(Param); 8880 } 8881 8882 // Fake up parameter variables if we have a typedef, like 8883 // ^ fntype { ... } 8884 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 8885 for (FunctionProtoType::arg_type_iterator 8886 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 8887 ParmVarDecl *Param = 8888 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 8889 ParamInfo.getSourceRange().getBegin(), 8890 *I); 8891 Params.push_back(Param); 8892 } 8893 } 8894 8895 // Set the parameters on the block decl. 8896 if (!Params.empty()) { 8897 CurBlock->TheDecl->setParams(Params.data(), Params.size()); 8898 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 8899 CurBlock->TheDecl->param_end(), 8900 /*CheckParameterNames=*/false); 8901 } 8902 8903 // Finally we can process decl attributes. 8904 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 8905 8906 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) { 8907 Diag(ParamInfo.getAttributes()->getLoc(), 8908 diag::warn_attribute_sentinel_not_variadic) << 1; 8909 // FIXME: remove the attribute. 8910 } 8911 8912 // Put the parameter variables in scope. We can bail out immediately 8913 // if we don't have any. 8914 if (Params.empty()) 8915 return; 8916 8917 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 8918 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 8919 (*AI)->setOwningFunction(CurBlock->TheDecl); 8920 8921 // If this has an identifier, add it to the scope stack. 8922 if ((*AI)->getIdentifier()) { 8923 CheckShadow(CurBlock->TheScope, *AI); 8924 8925 PushOnScopeChains(*AI, CurBlock->TheScope); 8926 } 8927 } 8928} 8929 8930/// ActOnBlockError - If there is an error parsing a block, this callback 8931/// is invoked to pop the information about the block from the action impl. 8932void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 8933 // Pop off CurBlock, handle nested blocks. 8934 PopDeclContext(); 8935 PopFunctionOrBlockScope(); 8936} 8937 8938/// ActOnBlockStmtExpr - This is called when the body of a block statement 8939/// literal was successfully completed. ^(int x){...} 8940ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 8941 Stmt *Body, Scope *CurScope) { 8942 // If blocks are disabled, emit an error. 8943 if (!LangOpts.Blocks) 8944 Diag(CaretLoc, diag::err_blocks_disable); 8945 8946 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 8947 8948 PopDeclContext(); 8949 8950 QualType RetTy = Context.VoidTy; 8951 if (!BSI->ReturnType.isNull()) 8952 RetTy = BSI->ReturnType; 8953 8954 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 8955 QualType BlockTy; 8956 8957 // Set the captured variables on the block. 8958 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(), 8959 BSI->CapturesCXXThis); 8960 8961 // If the user wrote a function type in some form, try to use that. 8962 if (!BSI->FunctionType.isNull()) { 8963 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 8964 8965 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 8966 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 8967 8968 // Turn protoless block types into nullary block types. 8969 if (isa<FunctionNoProtoType>(FTy)) { 8970 FunctionProtoType::ExtProtoInfo EPI; 8971 EPI.ExtInfo = Ext; 8972 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8973 8974 // Otherwise, if we don't need to change anything about the function type, 8975 // preserve its sugar structure. 8976 } else if (FTy->getResultType() == RetTy && 8977 (!NoReturn || FTy->getNoReturnAttr())) { 8978 BlockTy = BSI->FunctionType; 8979 8980 // Otherwise, make the minimal modifications to the function type. 8981 } else { 8982 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 8983 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8984 EPI.TypeQuals = 0; // FIXME: silently? 8985 EPI.ExtInfo = Ext; 8986 BlockTy = Context.getFunctionType(RetTy, 8987 FPT->arg_type_begin(), 8988 FPT->getNumArgs(), 8989 EPI); 8990 } 8991 8992 // If we don't have a function type, just build one from nothing. 8993 } else { 8994 FunctionProtoType::ExtProtoInfo EPI; 8995 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default); 8996 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8997 } 8998 8999 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9000 BSI->TheDecl->param_end()); 9001 BlockTy = Context.getBlockPointerType(BlockTy); 9002 9003 // If needed, diagnose invalid gotos and switches in the block. 9004 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction()) 9005 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9006 9007 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9008 9009 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9010 9011 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9012 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result); 9013 return Owned(Result); 9014} 9015 9016ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9017 Expr *expr, ParsedType type, 9018 SourceLocation RPLoc) { 9019 TypeSourceInfo *TInfo; 9020 GetTypeFromParser(type, &TInfo); 9021 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc); 9022} 9023 9024ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9025 Expr *E, TypeSourceInfo *TInfo, 9026 SourceLocation RPLoc) { 9027 Expr *OrigExpr = E; 9028 9029 // Get the va_list type 9030 QualType VaListType = Context.getBuiltinVaListType(); 9031 if (VaListType->isArrayType()) { 9032 // Deal with implicit array decay; for example, on x86-64, 9033 // va_list is an array, but it's supposed to decay to 9034 // a pointer for va_arg. 9035 VaListType = Context.getArrayDecayedType(VaListType); 9036 // Make sure the input expression also decays appropriately. 9037 UsualUnaryConversions(E); 9038 } else { 9039 // Otherwise, the va_list argument must be an l-value because 9040 // it is modified by va_arg. 9041 if (!E->isTypeDependent() && 9042 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9043 return ExprError(); 9044 } 9045 9046 if (!E->isTypeDependent() && 9047 !Context.hasSameType(VaListType, E->getType())) { 9048 return ExprError(Diag(E->getLocStart(), 9049 diag::err_first_argument_to_va_arg_not_of_type_va_list) 9050 << OrigExpr->getType() << E->getSourceRange()); 9051 } 9052 9053 // FIXME: Check that type is complete/non-abstract 9054 // FIXME: Warn if a non-POD type is passed in. 9055 9056 QualType T = TInfo->getType().getNonLValueExprType(Context); 9057 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 9058} 9059 9060ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 9061 // The type of __null will be int or long, depending on the size of 9062 // pointers on the target. 9063 QualType Ty; 9064 unsigned pw = Context.Target.getPointerWidth(0); 9065 if (pw == Context.Target.getIntWidth()) 9066 Ty = Context.IntTy; 9067 else if (pw == Context.Target.getLongWidth()) 9068 Ty = Context.LongTy; 9069 else if (pw == Context.Target.getLongLongWidth()) 9070 Ty = Context.LongLongTy; 9071 else { 9072 assert(!"I don't know size of pointer!"); 9073 Ty = Context.IntTy; 9074 } 9075 9076 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 9077} 9078 9079static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 9080 Expr *SrcExpr, FixItHint &Hint) { 9081 if (!SemaRef.getLangOptions().ObjC1) 9082 return; 9083 9084 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 9085 if (!PT) 9086 return; 9087 9088 // Check if the destination is of type 'id'. 9089 if (!PT->isObjCIdType()) { 9090 // Check if the destination is the 'NSString' interface. 9091 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 9092 if (!ID || !ID->getIdentifier()->isStr("NSString")) 9093 return; 9094 } 9095 9096 // Strip off any parens and casts. 9097 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 9098 if (!SL || SL->isWide()) 9099 return; 9100 9101 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 9102} 9103 9104bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 9105 SourceLocation Loc, 9106 QualType DstType, QualType SrcType, 9107 Expr *SrcExpr, AssignmentAction Action, 9108 bool *Complained) { 9109 if (Complained) 9110 *Complained = false; 9111 9112 // Decode the result (notice that AST's are still created for extensions). 9113 bool isInvalid = false; 9114 unsigned DiagKind; 9115 FixItHint Hint; 9116 9117 switch (ConvTy) { 9118 default: assert(0 && "Unknown conversion type"); 9119 case Compatible: return false; 9120 case PointerToInt: 9121 DiagKind = diag::ext_typecheck_convert_pointer_int; 9122 break; 9123 case IntToPointer: 9124 DiagKind = diag::ext_typecheck_convert_int_pointer; 9125 break; 9126 case IncompatiblePointer: 9127 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9128 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9129 break; 9130 case IncompatiblePointerSign: 9131 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9132 break; 9133 case FunctionVoidPointer: 9134 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9135 break; 9136 case IncompatiblePointerDiscardsQualifiers: { 9137 // Perform array-to-pointer decay if necessary. 9138 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9139 9140 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9141 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9142 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9143 DiagKind = diag::err_typecheck_incompatible_address_space; 9144 break; 9145 } 9146 9147 llvm_unreachable("unknown error case for discarding qualifiers!"); 9148 // fallthrough 9149 } 9150 case CompatiblePointerDiscardsQualifiers: 9151 // If the qualifiers lost were because we were applying the 9152 // (deprecated) C++ conversion from a string literal to a char* 9153 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9154 // Ideally, this check would be performed in 9155 // checkPointerTypesForAssignment. However, that would require a 9156 // bit of refactoring (so that the second argument is an 9157 // expression, rather than a type), which should be done as part 9158 // of a larger effort to fix checkPointerTypesForAssignment for 9159 // C++ semantics. 9160 if (getLangOptions().CPlusPlus && 9161 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9162 return false; 9163 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9164 break; 9165 case IncompatibleNestedPointerQualifiers: 9166 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9167 break; 9168 case IntToBlockPointer: 9169 DiagKind = diag::err_int_to_block_pointer; 9170 break; 9171 case IncompatibleBlockPointer: 9172 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9173 break; 9174 case IncompatibleObjCQualifiedId: 9175 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9176 // it can give a more specific diagnostic. 9177 DiagKind = diag::warn_incompatible_qualified_id; 9178 break; 9179 case IncompatibleVectors: 9180 DiagKind = diag::warn_incompatible_vectors; 9181 break; 9182 case Incompatible: 9183 DiagKind = diag::err_typecheck_convert_incompatible; 9184 isInvalid = true; 9185 break; 9186 } 9187 9188 QualType FirstType, SecondType; 9189 switch (Action) { 9190 case AA_Assigning: 9191 case AA_Initializing: 9192 // The destination type comes first. 9193 FirstType = DstType; 9194 SecondType = SrcType; 9195 break; 9196 9197 case AA_Returning: 9198 case AA_Passing: 9199 case AA_Converting: 9200 case AA_Sending: 9201 case AA_Casting: 9202 // The source type comes first. 9203 FirstType = SrcType; 9204 SecondType = DstType; 9205 break; 9206 } 9207 9208 Diag(Loc, DiagKind) << FirstType << SecondType << Action 9209 << SrcExpr->getSourceRange() << Hint; 9210 if (Complained) 9211 *Complained = true; 9212 return isInvalid; 9213} 9214 9215bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 9216 llvm::APSInt ICEResult; 9217 if (E->isIntegerConstantExpr(ICEResult, Context)) { 9218 if (Result) 9219 *Result = ICEResult; 9220 return false; 9221 } 9222 9223 Expr::EvalResult EvalResult; 9224 9225 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 9226 EvalResult.HasSideEffects) { 9227 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 9228 9229 if (EvalResult.Diag) { 9230 // We only show the note if it's not the usual "invalid subexpression" 9231 // or if it's actually in a subexpression. 9232 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 9233 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 9234 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9235 } 9236 9237 return true; 9238 } 9239 9240 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 9241 E->getSourceRange(); 9242 9243 if (EvalResult.Diag && 9244 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc) 9245 != Diagnostic::Ignored) 9246 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9247 9248 if (Result) 9249 *Result = EvalResult.Val.getInt(); 9250 return false; 9251} 9252 9253void 9254Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 9255 ExprEvalContexts.push_back( 9256 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size())); 9257} 9258 9259void 9260Sema::PopExpressionEvaluationContext() { 9261 // Pop the current expression evaluation context off the stack. 9262 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 9263 ExprEvalContexts.pop_back(); 9264 9265 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 9266 if (Rec.PotentiallyReferenced) { 9267 // Mark any remaining declarations in the current position of the stack 9268 // as "referenced". If they were not meant to be referenced, semantic 9269 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 9270 for (PotentiallyReferencedDecls::iterator 9271 I = Rec.PotentiallyReferenced->begin(), 9272 IEnd = Rec.PotentiallyReferenced->end(); 9273 I != IEnd; ++I) 9274 MarkDeclarationReferenced(I->first, I->second); 9275 } 9276 9277 if (Rec.PotentiallyDiagnosed) { 9278 // Emit any pending diagnostics. 9279 for (PotentiallyEmittedDiagnostics::iterator 9280 I = Rec.PotentiallyDiagnosed->begin(), 9281 IEnd = Rec.PotentiallyDiagnosed->end(); 9282 I != IEnd; ++I) 9283 Diag(I->first, I->second); 9284 } 9285 } 9286 9287 // When are coming out of an unevaluated context, clear out any 9288 // temporaries that we may have created as part of the evaluation of 9289 // the expression in that context: they aren't relevant because they 9290 // will never be constructed. 9291 if (Rec.Context == Unevaluated && 9292 ExprTemporaries.size() > Rec.NumTemporaries) 9293 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 9294 ExprTemporaries.end()); 9295 9296 // Destroy the popped expression evaluation record. 9297 Rec.Destroy(); 9298} 9299 9300/// \brief Note that the given declaration was referenced in the source code. 9301/// 9302/// This routine should be invoke whenever a given declaration is referenced 9303/// in the source code, and where that reference occurred. If this declaration 9304/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 9305/// C99 6.9p3), then the declaration will be marked as used. 9306/// 9307/// \param Loc the location where the declaration was referenced. 9308/// 9309/// \param D the declaration that has been referenced by the source code. 9310void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 9311 assert(D && "No declaration?"); 9312 9313 if (D->isUsed(false)) 9314 return; 9315 9316 // Mark a parameter or variable declaration "used", regardless of whether we're in a 9317 // template or not. The reason for this is that unevaluated expressions 9318 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and 9319 // -Wunused-parameters) 9320 if (isa<ParmVarDecl>(D) || 9321 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) { 9322 D->setUsed(); 9323 return; 9324 } 9325 9326 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) 9327 return; 9328 9329 // Do not mark anything as "used" within a dependent context; wait for 9330 // an instantiation. 9331 if (CurContext->isDependentContext()) 9332 return; 9333 9334 switch (ExprEvalContexts.back().Context) { 9335 case Unevaluated: 9336 // We are in an expression that is not potentially evaluated; do nothing. 9337 return; 9338 9339 case PotentiallyEvaluated: 9340 // We are in a potentially-evaluated expression, so this declaration is 9341 // "used"; handle this below. 9342 break; 9343 9344 case PotentiallyPotentiallyEvaluated: 9345 // We are in an expression that may be potentially evaluated; queue this 9346 // declaration reference until we know whether the expression is 9347 // potentially evaluated. 9348 ExprEvalContexts.back().addReferencedDecl(Loc, D); 9349 return; 9350 9351 case PotentiallyEvaluatedIfUsed: 9352 // Referenced declarations will only be used if the construct in the 9353 // containing expression is used. 9354 return; 9355 } 9356 9357 // Note that this declaration has been used. 9358 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 9359 unsigned TypeQuals; 9360 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 9361 if (Constructor->getParent()->hasTrivialConstructor()) 9362 return; 9363 if (!Constructor->isUsed(false)) 9364 DefineImplicitDefaultConstructor(Loc, Constructor); 9365 } else if (Constructor->isImplicit() && 9366 Constructor->isCopyConstructor(TypeQuals)) { 9367 if (!Constructor->isUsed(false)) 9368 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 9369 } 9370 9371 MarkVTableUsed(Loc, Constructor->getParent()); 9372 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 9373 if (Destructor->isImplicit() && !Destructor->isUsed(false)) 9374 DefineImplicitDestructor(Loc, Destructor); 9375 if (Destructor->isVirtual()) 9376 MarkVTableUsed(Loc, Destructor->getParent()); 9377 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 9378 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 9379 MethodDecl->getOverloadedOperator() == OO_Equal) { 9380 if (!MethodDecl->isUsed(false)) 9381 DefineImplicitCopyAssignment(Loc, MethodDecl); 9382 } else if (MethodDecl->isVirtual()) 9383 MarkVTableUsed(Loc, MethodDecl->getParent()); 9384 } 9385 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 9386 // Recursive functions should be marked when used from another function. 9387 if (CurContext == Function) return; 9388 9389 // Implicit instantiation of function templates and member functions of 9390 // class templates. 9391 if (Function->isImplicitlyInstantiable()) { 9392 bool AlreadyInstantiated = false; 9393 if (FunctionTemplateSpecializationInfo *SpecInfo 9394 = Function->getTemplateSpecializationInfo()) { 9395 if (SpecInfo->getPointOfInstantiation().isInvalid()) 9396 SpecInfo->setPointOfInstantiation(Loc); 9397 else if (SpecInfo->getTemplateSpecializationKind() 9398 == TSK_ImplicitInstantiation) 9399 AlreadyInstantiated = true; 9400 } else if (MemberSpecializationInfo *MSInfo 9401 = Function->getMemberSpecializationInfo()) { 9402 if (MSInfo->getPointOfInstantiation().isInvalid()) 9403 MSInfo->setPointOfInstantiation(Loc); 9404 else if (MSInfo->getTemplateSpecializationKind() 9405 == TSK_ImplicitInstantiation) 9406 AlreadyInstantiated = true; 9407 } 9408 9409 if (!AlreadyInstantiated) { 9410 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 9411 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 9412 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 9413 Loc)); 9414 else 9415 PendingInstantiations.push_back(std::make_pair(Function, Loc)); 9416 } 9417 } else { 9418 // Walk redefinitions, as some of them may be instantiable. 9419 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()), 9420 e(Function->redecls_end()); i != e; ++i) { 9421 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 9422 MarkDeclarationReferenced(Loc, *i); 9423 } 9424 } 9425 9426 // Keep track of used but undefined functions. 9427 if (!Function->isPure() && !Function->hasBody() && 9428 Function->getLinkage() != ExternalLinkage) { 9429 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()]; 9430 if (old.isInvalid()) old = Loc; 9431 } 9432 9433 Function->setUsed(true); 9434 return; 9435 } 9436 9437 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 9438 // Implicit instantiation of static data members of class templates. 9439 if (Var->isStaticDataMember() && 9440 Var->getInstantiatedFromStaticDataMember()) { 9441 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 9442 assert(MSInfo && "Missing member specialization information?"); 9443 if (MSInfo->getPointOfInstantiation().isInvalid() && 9444 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 9445 MSInfo->setPointOfInstantiation(Loc); 9446 PendingInstantiations.push_back(std::make_pair(Var, Loc)); 9447 } 9448 } 9449 9450 // Keep track of used but undefined variables. We make a hole in 9451 // the warning for static const data members with in-line 9452 // initializers. 9453 if (Var->hasDefinition() == VarDecl::DeclarationOnly 9454 && Var->getLinkage() != ExternalLinkage 9455 && !(Var->isStaticDataMember() && Var->hasInit())) { 9456 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()]; 9457 if (old.isInvalid()) old = Loc; 9458 } 9459 9460 D->setUsed(true); 9461 return; 9462 } 9463} 9464 9465namespace { 9466 // Mark all of the declarations referenced 9467 // FIXME: Not fully implemented yet! We need to have a better understanding 9468 // of when we're entering 9469 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 9470 Sema &S; 9471 SourceLocation Loc; 9472 9473 public: 9474 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 9475 9476 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 9477 9478 bool TraverseTemplateArgument(const TemplateArgument &Arg); 9479 bool TraverseRecordType(RecordType *T); 9480 }; 9481} 9482 9483bool MarkReferencedDecls::TraverseTemplateArgument( 9484 const TemplateArgument &Arg) { 9485 if (Arg.getKind() == TemplateArgument::Declaration) { 9486 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl()); 9487 } 9488 9489 return Inherited::TraverseTemplateArgument(Arg); 9490} 9491 9492bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 9493 if (ClassTemplateSpecializationDecl *Spec 9494 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 9495 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 9496 return TraverseTemplateArguments(Args.data(), Args.size()); 9497 } 9498 9499 return true; 9500} 9501 9502void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 9503 MarkReferencedDecls Marker(*this, Loc); 9504 Marker.TraverseType(Context.getCanonicalType(T)); 9505} 9506 9507namespace { 9508 /// \brief Helper class that marks all of the declarations referenced by 9509 /// potentially-evaluated subexpressions as "referenced". 9510 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 9511 Sema &S; 9512 9513 public: 9514 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 9515 9516 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { } 9517 9518 void VisitDeclRefExpr(DeclRefExpr *E) { 9519 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9520 } 9521 9522 void VisitMemberExpr(MemberExpr *E) { 9523 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl()); 9524 Inherited::VisitMemberExpr(E); 9525 } 9526 9527 void VisitCXXNewExpr(CXXNewExpr *E) { 9528 if (E->getConstructor()) 9529 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9530 if (E->getOperatorNew()) 9531 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew()); 9532 if (E->getOperatorDelete()) 9533 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9534 Inherited::VisitCXXNewExpr(E); 9535 } 9536 9537 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 9538 if (E->getOperatorDelete()) 9539 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9540 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 9541 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 9542 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 9543 S.MarkDeclarationReferenced(E->getLocStart(), 9544 S.LookupDestructor(Record)); 9545 } 9546 9547 Inherited::VisitCXXDeleteExpr(E); 9548 } 9549 9550 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9551 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9552 Inherited::VisitCXXConstructExpr(E); 9553 } 9554 9555 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { 9556 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9557 } 9558 9559 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 9560 Visit(E->getExpr()); 9561 } 9562 }; 9563} 9564 9565/// \brief Mark any declarations that appear within this expression or any 9566/// potentially-evaluated subexpressions as "referenced". 9567void Sema::MarkDeclarationsReferencedInExpr(Expr *E) { 9568 EvaluatedExprMarker(*this).Visit(E); 9569} 9570 9571/// \brief Emit a diagnostic that describes an effect on the run-time behavior 9572/// of the program being compiled. 9573/// 9574/// This routine emits the given diagnostic when the code currently being 9575/// type-checked is "potentially evaluated", meaning that there is a 9576/// possibility that the code will actually be executable. Code in sizeof() 9577/// expressions, code used only during overload resolution, etc., are not 9578/// potentially evaluated. This routine will suppress such diagnostics or, 9579/// in the absolutely nutty case of potentially potentially evaluated 9580/// expressions (C++ typeid), queue the diagnostic to potentially emit it 9581/// later. 9582/// 9583/// This routine should be used for all diagnostics that describe the run-time 9584/// behavior of a program, such as passing a non-POD value through an ellipsis. 9585/// Failure to do so will likely result in spurious diagnostics or failures 9586/// during overload resolution or within sizeof/alignof/typeof/typeid. 9587bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt, 9588 const PartialDiagnostic &PD) { 9589 switch (ExprEvalContexts.back().Context ) { 9590 case Unevaluated: 9591 // The argument will never be evaluated, so don't complain. 9592 break; 9593 9594 case PotentiallyEvaluated: 9595 case PotentiallyEvaluatedIfUsed: 9596 if (stmt && getCurFunctionOrMethodDecl()) { 9597 FunctionScopes.back()->PossiblyUnreachableDiags. 9598 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt)); 9599 } 9600 else 9601 Diag(Loc, PD); 9602 9603 return true; 9604 9605 case PotentiallyPotentiallyEvaluated: 9606 ExprEvalContexts.back().addDiagnostic(Loc, PD); 9607 break; 9608 } 9609 9610 return false; 9611} 9612 9613bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 9614 CallExpr *CE, FunctionDecl *FD) { 9615 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 9616 return false; 9617 9618 PartialDiagnostic Note = 9619 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 9620 << FD->getDeclName() : PDiag(); 9621 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 9622 9623 if (RequireCompleteType(Loc, ReturnType, 9624 FD ? 9625 PDiag(diag::err_call_function_incomplete_return) 9626 << CE->getSourceRange() << FD->getDeclName() : 9627 PDiag(diag::err_call_incomplete_return) 9628 << CE->getSourceRange(), 9629 std::make_pair(NoteLoc, Note))) 9630 return true; 9631 9632 return false; 9633} 9634 9635// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 9636// will prevent this condition from triggering, which is what we want. 9637void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 9638 SourceLocation Loc; 9639 9640 unsigned diagnostic = diag::warn_condition_is_assignment; 9641 bool IsOrAssign = false; 9642 9643 if (isa<BinaryOperator>(E)) { 9644 BinaryOperator *Op = cast<BinaryOperator>(E); 9645 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 9646 return; 9647 9648 IsOrAssign = Op->getOpcode() == BO_OrAssign; 9649 9650 // Greylist some idioms by putting them into a warning subcategory. 9651 if (ObjCMessageExpr *ME 9652 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 9653 Selector Sel = ME->getSelector(); 9654 9655 // self = [<foo> init...] 9656 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 9657 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9658 9659 // <foo> = [<bar> nextObject] 9660 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 9661 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9662 } 9663 9664 Loc = Op->getOperatorLoc(); 9665 } else if (isa<CXXOperatorCallExpr>(E)) { 9666 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E); 9667 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 9668 return; 9669 9670 IsOrAssign = Op->getOperator() == OO_PipeEqual; 9671 Loc = Op->getOperatorLoc(); 9672 } else { 9673 // Not an assignment. 9674 return; 9675 } 9676 9677 SourceLocation Open = E->getSourceRange().getBegin(); 9678 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 9679 9680 Diag(Loc, diagnostic) << E->getSourceRange(); 9681 9682 if (IsOrAssign) 9683 Diag(Loc, diag::note_condition_or_assign_to_comparison) 9684 << FixItHint::CreateReplacement(Loc, "!="); 9685 else 9686 Diag(Loc, diag::note_condition_assign_to_comparison) 9687 << FixItHint::CreateReplacement(Loc, "=="); 9688 9689 Diag(Loc, diag::note_condition_assign_silence) 9690 << FixItHint::CreateInsertion(Open, "(") 9691 << FixItHint::CreateInsertion(Close, ")"); 9692} 9693 9694/// \brief Redundant parentheses over an equality comparison can indicate 9695/// that the user intended an assignment used as condition. 9696void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) { 9697 // Don't warn if the parens came from a macro. 9698 SourceLocation parenLoc = parenE->getLocStart(); 9699 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 9700 return; 9701 9702 Expr *E = parenE->IgnoreParens(); 9703 9704 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 9705 if (opE->getOpcode() == BO_EQ && 9706 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 9707 == Expr::MLV_Valid) { 9708 SourceLocation Loc = opE->getOperatorLoc(); 9709 9710 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 9711 Diag(Loc, diag::note_equality_comparison_to_assign) 9712 << FixItHint::CreateReplacement(Loc, "="); 9713 Diag(Loc, diag::note_equality_comparison_silence) 9714 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin()) 9715 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd()); 9716 } 9717} 9718 9719bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) { 9720 DiagnoseAssignmentAsCondition(E); 9721 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 9722 DiagnoseEqualityWithExtraParens(parenE); 9723 9724 if (!E->isTypeDependent()) { 9725 if (E->isBoundMemberFunction(Context)) 9726 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func) 9727 << E->getSourceRange(); 9728 9729 if (getLangOptions().CPlusPlus) 9730 return CheckCXXBooleanCondition(E); // C++ 6.4p4 9731 9732 DefaultFunctionArrayLvalueConversion(E); 9733 9734 QualType T = E->getType(); 9735 if (!T->isScalarType()) // C99 6.8.4.1p1 9736 return Diag(Loc, diag::err_typecheck_statement_requires_scalar) 9737 << T << E->getSourceRange(); 9738 } 9739 9740 return false; 9741} 9742 9743ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 9744 Expr *Sub) { 9745 if (!Sub) 9746 return ExprError(); 9747 9748 if (CheckBooleanCondition(Sub, Loc)) 9749 return ExprError(); 9750 9751 return Owned(Sub); 9752} 9753 9754/// Check for operands with placeholder types and complain if found. 9755/// Returns true if there was an error and no recovery was possible. 9756ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) { 9757 const BuiltinType *BT = E->getType()->getAs<BuiltinType>(); 9758 if (!BT || !BT->isPlaceholderType()) return Owned(E); 9759 9760 // If this is overload, check for a single overload. 9761 assert(BT->getKind() == BuiltinType::Overload); 9762 9763 if (FunctionDecl *Specialization 9764 = ResolveSingleFunctionTemplateSpecialization(E)) { 9765 // The access doesn't really matter in this case. 9766 DeclAccessPair Found = DeclAccessPair::make(Specialization, 9767 Specialization->getAccess()); 9768 E = FixOverloadedFunctionReference(E, Found, Specialization); 9769 if (!E) return ExprError(); 9770 return Owned(E); 9771 } 9772 9773 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange(); 9774 return ExprError(); 9775} 9776