SemaExpr.cpp revision 89ee65fb6f6218b45c46537690ae4691b489cf05
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/Sema.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/Expr.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/ExprObjC.h" 25#include "clang/AST/RecursiveASTVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Basic/SourceManager.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/LiteralSupport.h" 31#include "clang/Lex/Preprocessor.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/Designator.h" 34#include "clang/Sema/Scope.h" 35#include "clang/Sema/ParsedTemplate.h" 36#include "clang/Sema/Template.h" 37using namespace clang; 38 39 40/// \brief Determine whether the use of this declaration is valid, and 41/// emit any corresponding diagnostics. 42/// 43/// This routine diagnoses various problems with referencing 44/// declarations that can occur when using a declaration. For example, 45/// it might warn if a deprecated or unavailable declaration is being 46/// used, or produce an error (and return true) if a C++0x deleted 47/// function is being used. 48/// 49/// If IgnoreDeprecated is set to true, this should not want about deprecated 50/// decls. 51/// 52/// \returns true if there was an error (this declaration cannot be 53/// referenced), false otherwise. 54/// 55bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 56 // See if the decl is deprecated. 57 if (D->getAttr<DeprecatedAttr>()) { 58 EmitDeprecationWarning(D, Loc); 59 } 60 61 // See if the decl is unavailable 62 if (D->getAttr<UnavailableAttr>()) { 63 Diag(Loc, diag::err_unavailable) << D->getDeclName(); 64 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 65 } 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) { 70 Diag(Loc, diag::err_deleted_function_use); 71 Diag(D->getLocation(), diag::note_unavailable_here) << true; 72 return true; 73 } 74 } 75 76 return false; 77} 78 79/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 80/// (and other functions in future), which have been declared with sentinel 81/// attribute. It warns if call does not have the sentinel argument. 82/// 83void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 84 Expr **Args, unsigned NumArgs) { 85 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 86 if (!attr) 87 return; 88 89 // FIXME: In C++0x, if any of the arguments are parameter pack 90 // expansions, we can't check for the sentinel now. 91 int sentinelPos = attr->getSentinel(); 92 int nullPos = attr->getNullPos(); 93 94 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 95 // base class. Then we won't be needing two versions of the same code. 96 unsigned int i = 0; 97 bool warnNotEnoughArgs = false; 98 int isMethod = 0; 99 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 100 // skip over named parameters. 101 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 102 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 103 if (nullPos) 104 --nullPos; 105 else 106 ++i; 107 } 108 warnNotEnoughArgs = (P != E || i >= NumArgs); 109 isMethod = 1; 110 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 111 // skip over named parameters. 112 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 113 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 114 if (nullPos) 115 --nullPos; 116 else 117 ++i; 118 } 119 warnNotEnoughArgs = (P != E || i >= NumArgs); 120 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 121 // block or function pointer call. 122 QualType Ty = V->getType(); 123 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 124 const FunctionType *FT = Ty->isFunctionPointerType() 125 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 126 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 127 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 128 unsigned NumArgsInProto = Proto->getNumArgs(); 129 unsigned k; 130 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 131 if (nullPos) 132 --nullPos; 133 else 134 ++i; 135 } 136 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 137 } 138 if (Ty->isBlockPointerType()) 139 isMethod = 2; 140 } else 141 return; 142 } else 143 return; 144 145 if (warnNotEnoughArgs) { 146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 148 return; 149 } 150 int sentinel = i; 151 while (sentinelPos > 0 && i < NumArgs-1) { 152 --sentinelPos; 153 ++i; 154 } 155 if (sentinelPos > 0) { 156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 158 return; 159 } 160 while (i < NumArgs-1) { 161 ++i; 162 ++sentinel; 163 } 164 Expr *sentinelExpr = Args[sentinel]; 165 if (!sentinelExpr) return; 166 if (sentinelExpr->isTypeDependent()) return; 167 if (sentinelExpr->isValueDependent()) return; 168 if (sentinelExpr->getType()->isAnyPointerType() && 169 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context, 170 Expr::NPC_ValueDependentIsNull)) 171 return; 172 173 // Unfortunately, __null has type 'int'. 174 if (isa<GNUNullExpr>(sentinelExpr)) return; 175 176 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 177 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 178} 179 180SourceRange Sema::getExprRange(ExprTy *E) const { 181 Expr *Ex = (Expr *)E; 182 return Ex? Ex->getSourceRange() : SourceRange(); 183} 184 185//===----------------------------------------------------------------------===// 186// Standard Promotions and Conversions 187//===----------------------------------------------------------------------===// 188 189/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 190void Sema::DefaultFunctionArrayConversion(Expr *&E) { 191 QualType Ty = E->getType(); 192 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 193 194 if (Ty->isFunctionType()) 195 ImpCastExprToType(E, Context.getPointerType(Ty), 196 CastExpr::CK_FunctionToPointerDecay); 197 else if (Ty->isArrayType()) { 198 // In C90 mode, arrays only promote to pointers if the array expression is 199 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 200 // type 'array of type' is converted to an expression that has type 'pointer 201 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 202 // that has type 'array of type' ...". The relevant change is "an lvalue" 203 // (C90) to "an expression" (C99). 204 // 205 // C++ 4.2p1: 206 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 207 // T" can be converted to an rvalue of type "pointer to T". 208 // 209 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 210 E->isLvalue(Context) == Expr::LV_Valid) 211 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 212 CastExpr::CK_ArrayToPointerDecay); 213 } 214} 215 216void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) { 217 DefaultFunctionArrayConversion(E); 218 219 QualType Ty = E->getType(); 220 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type"); 221 if (!Ty->isDependentType() && Ty.hasQualifiers() && 222 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) && 223 E->isLvalue(Context) == Expr::LV_Valid) { 224 // C++ [conv.lval]p1: 225 // [...] If T is a non-class type, the type of the rvalue is the 226 // cv-unqualified version of T. Otherwise, the type of the 227 // rvalue is T 228 // 229 // C99 6.3.2.1p2: 230 // If the lvalue has qualified type, the value has the unqualified 231 // version of the type of the lvalue; otherwise, the value has the 232 // type of the lvalue. 233 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp); 234 } 235} 236 237 238/// UsualUnaryConversions - Performs various conversions that are common to most 239/// operators (C99 6.3). The conversions of array and function types are 240/// sometimes surpressed. For example, the array->pointer conversion doesn't 241/// apply if the array is an argument to the sizeof or address (&) operators. 242/// In these instances, this routine should *not* be called. 243Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 244 QualType Ty = Expr->getType(); 245 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 246 247 // C99 6.3.1.1p2: 248 // 249 // The following may be used in an expression wherever an int or 250 // unsigned int may be used: 251 // - an object or expression with an integer type whose integer 252 // conversion rank is less than or equal to the rank of int 253 // and unsigned int. 254 // - A bit-field of type _Bool, int, signed int, or unsigned int. 255 // 256 // If an int can represent all values of the original type, the 257 // value is converted to an int; otherwise, it is converted to an 258 // unsigned int. These are called the integer promotions. All 259 // other types are unchanged by the integer promotions. 260 QualType PTy = Context.isPromotableBitField(Expr); 261 if (!PTy.isNull()) { 262 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast); 263 return Expr; 264 } 265 if (Ty->isPromotableIntegerType()) { 266 QualType PT = Context.getPromotedIntegerType(Ty); 267 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast); 268 return Expr; 269 } 270 271 DefaultFunctionArrayLvalueConversion(Expr); 272 return Expr; 273} 274 275/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 276/// do not have a prototype. Arguments that have type float are promoted to 277/// double. All other argument types are converted by UsualUnaryConversions(). 278void Sema::DefaultArgumentPromotion(Expr *&Expr) { 279 QualType Ty = Expr->getType(); 280 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 281 282 // If this is a 'float' (CVR qualified or typedef) promote to double. 283 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 284 return ImpCastExprToType(Expr, Context.DoubleTy, 285 CastExpr::CK_FloatingCast); 286 287 UsualUnaryConversions(Expr); 288} 289 290/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 291/// will warn if the resulting type is not a POD type, and rejects ObjC 292/// interfaces passed by value. This returns true if the argument type is 293/// completely illegal. 294bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT, 295 FunctionDecl *FDecl) { 296 DefaultArgumentPromotion(Expr); 297 298 // __builtin_va_start takes the second argument as a "varargs" argument, but 299 // it doesn't actually do anything with it. It doesn't need to be non-pod 300 // etc. 301 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start) 302 return false; 303 304 if (Expr->getType()->isObjCObjectType() && 305 DiagRuntimeBehavior(Expr->getLocStart(), 306 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 307 << Expr->getType() << CT)) 308 return true; 309 310 if (!Expr->getType()->isPODType() && 311 DiagRuntimeBehavior(Expr->getLocStart(), 312 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 313 << Expr->getType() << CT)) 314 return true; 315 316 return false; 317} 318 319 320/// UsualArithmeticConversions - Performs various conversions that are common to 321/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 322/// routine returns the first non-arithmetic type found. The client is 323/// responsible for emitting appropriate error diagnostics. 324/// FIXME: verify the conversion rules for "complex int" are consistent with 325/// GCC. 326QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 327 bool isCompAssign) { 328 if (!isCompAssign) 329 UsualUnaryConversions(lhsExpr); 330 331 UsualUnaryConversions(rhsExpr); 332 333 // For conversion purposes, we ignore any qualifiers. 334 // For example, "const float" and "float" are equivalent. 335 QualType lhs = 336 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 337 QualType rhs = 338 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 339 340 // If both types are identical, no conversion is needed. 341 if (lhs == rhs) 342 return lhs; 343 344 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 345 // The caller can deal with this (e.g. pointer + int). 346 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 347 return lhs; 348 349 // Perform bitfield promotions. 350 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 351 if (!LHSBitfieldPromoteTy.isNull()) 352 lhs = LHSBitfieldPromoteTy; 353 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr); 354 if (!RHSBitfieldPromoteTy.isNull()) 355 rhs = RHSBitfieldPromoteTy; 356 357 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs); 358 if (!isCompAssign) 359 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown); 360 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown); 361 return destType; 362} 363 364//===----------------------------------------------------------------------===// 365// Semantic Analysis for various Expression Types 366//===----------------------------------------------------------------------===// 367 368 369/// ActOnStringLiteral - The specified tokens were lexed as pasted string 370/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 371/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 372/// multiple tokens. However, the common case is that StringToks points to one 373/// string. 374/// 375ExprResult 376Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 377 assert(NumStringToks && "Must have at least one string!"); 378 379 StringLiteralParser Literal(StringToks, NumStringToks, PP); 380 if (Literal.hadError) 381 return ExprError(); 382 383 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 384 for (unsigned i = 0; i != NumStringToks; ++i) 385 StringTokLocs.push_back(StringToks[i].getLocation()); 386 387 QualType StrTy = Context.CharTy; 388 if (Literal.AnyWide) StrTy = Context.getWCharType(); 389 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 390 391 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 392 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 393 StrTy.addConst(); 394 395 // Get an array type for the string, according to C99 6.4.5. This includes 396 // the nul terminator character as well as the string length for pascal 397 // strings. 398 StrTy = Context.getConstantArrayType(StrTy, 399 llvm::APInt(32, Literal.GetNumStringChars()+1), 400 ArrayType::Normal, 0); 401 402 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 403 return Owned(StringLiteral::Create(Context, Literal.GetString(), 404 Literal.GetStringLength(), 405 Literal.AnyWide, StrTy, 406 &StringTokLocs[0], 407 StringTokLocs.size())); 408} 409 410/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 411/// CurBlock to VD should cause it to be snapshotted (as we do for auto 412/// variables defined outside the block) or false if this is not needed (e.g. 413/// for values inside the block or for globals). 414/// 415/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records 416/// up-to-date. 417/// 418static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock, 419 ValueDecl *VD) { 420 // If the value is defined inside the block, we couldn't snapshot it even if 421 // we wanted to. 422 if (CurBlock->TheDecl == VD->getDeclContext()) 423 return false; 424 425 // If this is an enum constant or function, it is constant, don't snapshot. 426 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 427 return false; 428 429 // If this is a reference to an extern, static, or global variable, no need to 430 // snapshot it. 431 // FIXME: What about 'const' variables in C++? 432 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 433 if (!Var->hasLocalStorage()) 434 return false; 435 436 // Blocks that have these can't be constant. 437 CurBlock->hasBlockDeclRefExprs = true; 438 439 // If we have nested blocks, the decl may be declared in an outer block (in 440 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 441 // be defined outside all of the current blocks (in which case the blocks do 442 // all get the bit). Walk the nesting chain. 443 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) { 444 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]); 445 446 if (!NextBlock) 447 continue; 448 449 // If we found the defining block for the variable, don't mark the block as 450 // having a reference outside it. 451 if (NextBlock->TheDecl == VD->getDeclContext()) 452 break; 453 454 // Otherwise, the DeclRef from the inner block causes the outer one to need 455 // a snapshot as well. 456 NextBlock->hasBlockDeclRefExprs = true; 457 } 458 459 return true; 460} 461 462 463ExprResult 464Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc, 465 const CXXScopeSpec *SS) { 466 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 467 return BuildDeclRefExpr(D, Ty, NameInfo, SS); 468} 469 470/// BuildDeclRefExpr - Build a DeclRefExpr. 471ExprResult 472Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, 473 const DeclarationNameInfo &NameInfo, 474 const CXXScopeSpec *SS) { 475 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 476 Diag(NameInfo.getLoc(), 477 diag::err_auto_variable_cannot_appear_in_own_initializer) 478 << D->getDeclName(); 479 return ExprError(); 480 } 481 482 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 483 if (isa<NonTypeTemplateParmDecl>(VD)) { 484 // Non-type template parameters can be referenced anywhere they are 485 // visible. 486 Ty = Ty.getNonLValueExprType(Context); 487 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 488 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 489 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 490 Diag(NameInfo.getLoc(), 491 diag::err_reference_to_local_var_in_enclosing_function) 492 << D->getIdentifier() << FD->getDeclName(); 493 Diag(D->getLocation(), diag::note_local_variable_declared_here) 494 << D->getIdentifier(); 495 return ExprError(); 496 } 497 } 498 } 499 } 500 501 MarkDeclarationReferenced(NameInfo.getLoc(), D); 502 503 return Owned(DeclRefExpr::Create(Context, 504 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0, 505 SS? SS->getRange() : SourceRange(), 506 D, NameInfo, Ty)); 507} 508 509/// \brief Given a field that represents a member of an anonymous 510/// struct/union, build the path from that field's context to the 511/// actual member. 512/// 513/// Construct the sequence of field member references we'll have to 514/// perform to get to the field in the anonymous union/struct. The 515/// list of members is built from the field outward, so traverse it 516/// backwards to go from an object in the current context to the field 517/// we found. 518/// 519/// \returns The variable from which the field access should begin, 520/// for an anonymous struct/union that is not a member of another 521/// class. Otherwise, returns NULL. 522VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 523 llvm::SmallVectorImpl<FieldDecl *> &Path) { 524 assert(Field->getDeclContext()->isRecord() && 525 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 526 && "Field must be stored inside an anonymous struct or union"); 527 528 Path.push_back(Field); 529 VarDecl *BaseObject = 0; 530 DeclContext *Ctx = Field->getDeclContext(); 531 do { 532 RecordDecl *Record = cast<RecordDecl>(Ctx); 533 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject(); 534 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 535 Path.push_back(AnonField); 536 else { 537 BaseObject = cast<VarDecl>(AnonObject); 538 break; 539 } 540 Ctx = Ctx->getParent(); 541 } while (Ctx->isRecord() && 542 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 543 544 return BaseObject; 545} 546 547ExprResult 548Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 549 FieldDecl *Field, 550 Expr *BaseObjectExpr, 551 SourceLocation OpLoc) { 552 llvm::SmallVector<FieldDecl *, 4> AnonFields; 553 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 554 AnonFields); 555 556 // Build the expression that refers to the base object, from 557 // which we will build a sequence of member references to each 558 // of the anonymous union objects and, eventually, the field we 559 // found via name lookup. 560 bool BaseObjectIsPointer = false; 561 Qualifiers BaseQuals; 562 if (BaseObject) { 563 // BaseObject is an anonymous struct/union variable (and is, 564 // therefore, not part of another non-anonymous record). 565 MarkDeclarationReferenced(Loc, BaseObject); 566 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 567 SourceLocation()); 568 BaseQuals 569 = Context.getCanonicalType(BaseObject->getType()).getQualifiers(); 570 } else if (BaseObjectExpr) { 571 // The caller provided the base object expression. Determine 572 // whether its a pointer and whether it adds any qualifiers to the 573 // anonymous struct/union fields we're looking into. 574 QualType ObjectType = BaseObjectExpr->getType(); 575 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) { 576 BaseObjectIsPointer = true; 577 ObjectType = ObjectPtr->getPointeeType(); 578 } 579 BaseQuals 580 = Context.getCanonicalType(ObjectType).getQualifiers(); 581 } else { 582 // We've found a member of an anonymous struct/union that is 583 // inside a non-anonymous struct/union, so in a well-formed 584 // program our base object expression is "this". 585 DeclContext *DC = getFunctionLevelDeclContext(); 586 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 587 if (!MD->isStatic()) { 588 QualType AnonFieldType 589 = Context.getTagDeclType( 590 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 591 QualType ThisType = Context.getTagDeclType(MD->getParent()); 592 if ((Context.getCanonicalType(AnonFieldType) 593 == Context.getCanonicalType(ThisType)) || 594 IsDerivedFrom(ThisType, AnonFieldType)) { 595 // Our base object expression is "this". 596 BaseObjectExpr = new (Context) CXXThisExpr(Loc, 597 MD->getThisType(Context), 598 /*isImplicit=*/true); 599 BaseObjectIsPointer = true; 600 } 601 } else { 602 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 603 << Field->getDeclName()); 604 } 605 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 606 } 607 608 if (!BaseObjectExpr) 609 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 610 << Field->getDeclName()); 611 } 612 613 // Build the implicit member references to the field of the 614 // anonymous struct/union. 615 Expr *Result = BaseObjectExpr; 616 Qualifiers ResultQuals = BaseQuals; 617 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 618 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 619 FI != FIEnd; ++FI) { 620 QualType MemberType = (*FI)->getType(); 621 Qualifiers MemberTypeQuals = 622 Context.getCanonicalType(MemberType).getQualifiers(); 623 624 // CVR attributes from the base are picked up by members, 625 // except that 'mutable' members don't pick up 'const'. 626 if ((*FI)->isMutable()) 627 ResultQuals.removeConst(); 628 629 // GC attributes are never picked up by members. 630 ResultQuals.removeObjCGCAttr(); 631 632 // TR 18037 does not allow fields to be declared with address spaces. 633 assert(!MemberTypeQuals.hasAddressSpace()); 634 635 Qualifiers NewQuals = ResultQuals + MemberTypeQuals; 636 if (NewQuals != MemberTypeQuals) 637 MemberType = Context.getQualifiedType(MemberType, NewQuals); 638 639 MarkDeclarationReferenced(Loc, *FI); 640 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI); 641 // FIXME: Might this end up being a qualified name? 642 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 643 OpLoc, MemberType); 644 BaseObjectIsPointer = false; 645 ResultQuals = NewQuals; 646 } 647 648 return Owned(Result); 649} 650 651/// Decomposes the given name into a DeclarationNameInfo, its location, and 652/// possibly a list of template arguments. 653/// 654/// If this produces template arguments, it is permitted to call 655/// DecomposeTemplateName. 656/// 657/// This actually loses a lot of source location information for 658/// non-standard name kinds; we should consider preserving that in 659/// some way. 660static void DecomposeUnqualifiedId(Sema &SemaRef, 661 const UnqualifiedId &Id, 662 TemplateArgumentListInfo &Buffer, 663 DeclarationNameInfo &NameInfo, 664 const TemplateArgumentListInfo *&TemplateArgs) { 665 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 666 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 667 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 668 669 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef, 670 Id.TemplateId->getTemplateArgs(), 671 Id.TemplateId->NumArgs); 672 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer); 673 TemplateArgsPtr.release(); 674 675 TemplateName TName = Id.TemplateId->Template.get(); 676 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 677 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc); 678 TemplateArgs = &Buffer; 679 } else { 680 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id); 681 TemplateArgs = 0; 682 } 683} 684 685/// Determines whether the given record is "fully-formed" at the given 686/// location, i.e. whether a qualified lookup into it is assured of 687/// getting consistent results already. 688static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) { 689 if (!Record->hasDefinition()) 690 return false; 691 692 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 693 E = Record->bases_end(); I != E; ++I) { 694 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 695 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 696 if (!BaseRT) return false; 697 698 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 699 if (!BaseRecord->hasDefinition() || 700 !IsFullyFormedScope(SemaRef, BaseRecord)) 701 return false; 702 } 703 704 return true; 705} 706 707/// Determines if the given class is provably not derived from all of 708/// the prospective base classes. 709static bool IsProvablyNotDerivedFrom(Sema &SemaRef, 710 CXXRecordDecl *Record, 711 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) { 712 if (Bases.count(Record->getCanonicalDecl())) 713 return false; 714 715 RecordDecl *RD = Record->getDefinition(); 716 if (!RD) return false; 717 Record = cast<CXXRecordDecl>(RD); 718 719 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 720 E = Record->bases_end(); I != E; ++I) { 721 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 722 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 723 if (!BaseRT) return false; 724 725 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 726 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases)) 727 return false; 728 } 729 730 return true; 731} 732 733enum IMAKind { 734 /// The reference is definitely not an instance member access. 735 IMA_Static, 736 737 /// The reference may be an implicit instance member access. 738 IMA_Mixed, 739 740 /// The reference may be to an instance member, but it is invalid if 741 /// so, because the context is not an instance method. 742 IMA_Mixed_StaticContext, 743 744 /// The reference may be to an instance member, but it is invalid if 745 /// so, because the context is from an unrelated class. 746 IMA_Mixed_Unrelated, 747 748 /// The reference is definitely an implicit instance member access. 749 IMA_Instance, 750 751 /// The reference may be to an unresolved using declaration. 752 IMA_Unresolved, 753 754 /// The reference may be to an unresolved using declaration and the 755 /// context is not an instance method. 756 IMA_Unresolved_StaticContext, 757 758 /// The reference is to a member of an anonymous structure in a 759 /// non-class context. 760 IMA_AnonymousMember, 761 762 /// All possible referrents are instance members and the current 763 /// context is not an instance method. 764 IMA_Error_StaticContext, 765 766 /// All possible referrents are instance members of an unrelated 767 /// class. 768 IMA_Error_Unrelated 769}; 770 771/// The given lookup names class member(s) and is not being used for 772/// an address-of-member expression. Classify the type of access 773/// according to whether it's possible that this reference names an 774/// instance member. This is best-effort; it is okay to 775/// conservatively answer "yes", in which case some errors will simply 776/// not be caught until template-instantiation. 777static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, 778 const LookupResult &R) { 779 assert(!R.empty() && (*R.begin())->isCXXClassMember()); 780 781 DeclContext *DC = SemaRef.getFunctionLevelDeclContext(); 782 bool isStaticContext = 783 (!isa<CXXMethodDecl>(DC) || 784 cast<CXXMethodDecl>(DC)->isStatic()); 785 786 if (R.isUnresolvableResult()) 787 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 788 789 // Collect all the declaring classes of instance members we find. 790 bool hasNonInstance = false; 791 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes; 792 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 793 NamedDecl *D = *I; 794 if (D->isCXXInstanceMember()) { 795 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 796 797 // If this is a member of an anonymous record, move out to the 798 // innermost non-anonymous struct or union. If there isn't one, 799 // that's a special case. 800 while (R->isAnonymousStructOrUnion()) { 801 R = dyn_cast<CXXRecordDecl>(R->getParent()); 802 if (!R) return IMA_AnonymousMember; 803 } 804 Classes.insert(R->getCanonicalDecl()); 805 } 806 else 807 hasNonInstance = true; 808 } 809 810 // If we didn't find any instance members, it can't be an implicit 811 // member reference. 812 if (Classes.empty()) 813 return IMA_Static; 814 815 // If the current context is not an instance method, it can't be 816 // an implicit member reference. 817 if (isStaticContext) 818 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext); 819 820 // If we can prove that the current context is unrelated to all the 821 // declaring classes, it can't be an implicit member reference (in 822 // which case it's an error if any of those members are selected). 823 if (IsProvablyNotDerivedFrom(SemaRef, 824 cast<CXXMethodDecl>(DC)->getParent(), 825 Classes)) 826 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated); 827 828 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 829} 830 831/// Diagnose a reference to a field with no object available. 832static void DiagnoseInstanceReference(Sema &SemaRef, 833 const CXXScopeSpec &SS, 834 const LookupResult &R) { 835 SourceLocation Loc = R.getNameLoc(); 836 SourceRange Range(Loc); 837 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 838 839 if (R.getAsSingle<FieldDecl>()) { 840 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) { 841 if (MD->isStatic()) { 842 // "invalid use of member 'x' in static member function" 843 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 844 << Range << R.getLookupName(); 845 return; 846 } 847 } 848 849 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 850 << R.getLookupName() << Range; 851 return; 852 } 853 854 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range; 855} 856 857/// Diagnose an empty lookup. 858/// 859/// \return false if new lookup candidates were found 860bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 861 CorrectTypoContext CTC) { 862 DeclarationName Name = R.getLookupName(); 863 864 unsigned diagnostic = diag::err_undeclared_var_use; 865 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 866 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 867 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 868 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 869 diagnostic = diag::err_undeclared_use; 870 diagnostic_suggest = diag::err_undeclared_use_suggest; 871 } 872 873 // If the original lookup was an unqualified lookup, fake an 874 // unqualified lookup. This is useful when (for example) the 875 // original lookup would not have found something because it was a 876 // dependent name. 877 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0; 878 DC; DC = DC->getParent()) { 879 if (isa<CXXRecordDecl>(DC)) { 880 LookupQualifiedName(R, DC); 881 882 if (!R.empty()) { 883 // Don't give errors about ambiguities in this lookup. 884 R.suppressDiagnostics(); 885 886 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 887 bool isInstance = CurMethod && 888 CurMethod->isInstance() && 889 DC == CurMethod->getParent(); 890 891 // Give a code modification hint to insert 'this->'. 892 // TODO: fixit for inserting 'Base<T>::' in the other cases. 893 // Actually quite difficult! 894 if (isInstance) { 895 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 896 CallsUndergoingInstantiation.back()->getCallee()); 897 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 898 CurMethod->getInstantiatedFromMemberFunction()); 899 if (DepMethod) { 900 Diag(R.getNameLoc(), diagnostic) << Name 901 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 902 QualType DepThisType = DepMethod->getThisType(Context); 903 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 904 R.getNameLoc(), DepThisType, false); 905 TemplateArgumentListInfo TList; 906 if (ULE->hasExplicitTemplateArgs()) 907 ULE->copyTemplateArgumentsInto(TList); 908 CXXDependentScopeMemberExpr *DepExpr = 909 CXXDependentScopeMemberExpr::Create( 910 Context, DepThis, DepThisType, true, SourceLocation(), 911 ULE->getQualifier(), ULE->getQualifierRange(), NULL, 912 R.getLookupNameInfo(), &TList); 913 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 914 } else { 915 // FIXME: we should be able to handle this case too. It is correct 916 // to add this-> here. This is a workaround for PR7947. 917 Diag(R.getNameLoc(), diagnostic) << Name; 918 } 919 } else { 920 Diag(R.getNameLoc(), diagnostic) << Name; 921 } 922 923 // Do we really want to note all of these? 924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 925 Diag((*I)->getLocation(), diag::note_dependent_var_use); 926 927 // Tell the callee to try to recover. 928 return false; 929 } 930 931 R.clear(); 932 } 933 } 934 935 // We didn't find anything, so try to correct for a typo. 936 DeclarationName Corrected; 937 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) { 938 if (!R.empty()) { 939 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) { 940 if (SS.isEmpty()) 941 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName() 942 << FixItHint::CreateReplacement(R.getNameLoc(), 943 R.getLookupName().getAsString()); 944 else 945 Diag(R.getNameLoc(), diag::err_no_member_suggest) 946 << Name << computeDeclContext(SS, false) << R.getLookupName() 947 << SS.getRange() 948 << FixItHint::CreateReplacement(R.getNameLoc(), 949 R.getLookupName().getAsString()); 950 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 951 Diag(ND->getLocation(), diag::note_previous_decl) 952 << ND->getDeclName(); 953 954 // Tell the callee to try to recover. 955 return false; 956 } 957 958 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) { 959 // FIXME: If we ended up with a typo for a type name or 960 // Objective-C class name, we're in trouble because the parser 961 // is in the wrong place to recover. Suggest the typo 962 // correction, but don't make it a fix-it since we're not going 963 // to recover well anyway. 964 if (SS.isEmpty()) 965 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName(); 966 else 967 Diag(R.getNameLoc(), diag::err_no_member_suggest) 968 << Name << computeDeclContext(SS, false) << R.getLookupName() 969 << SS.getRange(); 970 971 // Don't try to recover; it won't work. 972 return true; 973 } 974 } else { 975 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 976 // because we aren't able to recover. 977 if (SS.isEmpty()) 978 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected; 979 else 980 Diag(R.getNameLoc(), diag::err_no_member_suggest) 981 << Name << computeDeclContext(SS, false) << Corrected 982 << SS.getRange(); 983 return true; 984 } 985 R.clear(); 986 } 987 988 // Emit a special diagnostic for failed member lookups. 989 // FIXME: computing the declaration context might fail here (?) 990 if (!SS.isEmpty()) { 991 Diag(R.getNameLoc(), diag::err_no_member) 992 << Name << computeDeclContext(SS, false) 993 << SS.getRange(); 994 return true; 995 } 996 997 // Give up, we can't recover. 998 Diag(R.getNameLoc(), diagnostic) << Name; 999 return true; 1000} 1001 1002static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef, 1003 IdentifierInfo *II, 1004 SourceLocation NameLoc) { 1005 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl(); 1006 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1007 if (!IDecl) 1008 return 0; 1009 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1010 if (!ClassImpDecl) 1011 return 0; 1012 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II); 1013 if (!property) 1014 return 0; 1015 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) 1016 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 1017 return 0; 1018 return property; 1019} 1020 1021static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef, 1022 LookupResult &Lookup, 1023 IdentifierInfo *II, 1024 SourceLocation NameLoc) { 1025 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl(); 1026 bool LookForIvars; 1027 if (Lookup.empty()) 1028 LookForIvars = true; 1029 else if (CurMeth->isClassMethod()) 1030 LookForIvars = false; 1031 else 1032 LookForIvars = (Lookup.isSingleResult() && 1033 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1034 if (!LookForIvars) 1035 return 0; 1036 1037 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1038 if (!IDecl) 1039 return 0; 1040 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1041 if (!ClassImpDecl) 1042 return 0; 1043 bool DynamicImplSeen = false; 1044 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II); 1045 if (!property) 1046 return 0; 1047 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) 1048 DynamicImplSeen = 1049 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 1050 if (!DynamicImplSeen) { 1051 QualType PropType = SemaRef.Context.getCanonicalType(property->getType()); 1052 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl, 1053 NameLoc, 1054 II, PropType, /*Dinfo=*/0, 1055 ObjCIvarDecl::Protected, 1056 (Expr *)0, true); 1057 ClassImpDecl->addDecl(Ivar); 1058 IDecl->makeDeclVisibleInContext(Ivar, false); 1059 property->setPropertyIvarDecl(Ivar); 1060 return Ivar; 1061 } 1062 return 0; 1063} 1064 1065ExprResult Sema::ActOnIdExpression(Scope *S, 1066 CXXScopeSpec &SS, 1067 UnqualifiedId &Id, 1068 bool HasTrailingLParen, 1069 bool isAddressOfOperand) { 1070 assert(!(isAddressOfOperand && HasTrailingLParen) && 1071 "cannot be direct & operand and have a trailing lparen"); 1072 1073 if (SS.isInvalid()) 1074 return ExprError(); 1075 1076 TemplateArgumentListInfo TemplateArgsBuffer; 1077 1078 // Decompose the UnqualifiedId into the following data. 1079 DeclarationNameInfo NameInfo; 1080 const TemplateArgumentListInfo *TemplateArgs; 1081 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1082 1083 DeclarationName Name = NameInfo.getName(); 1084 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1085 SourceLocation NameLoc = NameInfo.getLoc(); 1086 1087 // C++ [temp.dep.expr]p3: 1088 // An id-expression is type-dependent if it contains: 1089 // -- an identifier that was declared with a dependent type, 1090 // (note: handled after lookup) 1091 // -- a template-id that is dependent, 1092 // (note: handled in BuildTemplateIdExpr) 1093 // -- a conversion-function-id that specifies a dependent type, 1094 // -- a nested-name-specifier that contains a class-name that 1095 // names a dependent type. 1096 // Determine whether this is a member of an unknown specialization; 1097 // we need to handle these differently. 1098 bool DependentID = false; 1099 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1100 Name.getCXXNameType()->isDependentType()) { 1101 DependentID = true; 1102 } else if (SS.isSet()) { 1103 DeclContext *DC = computeDeclContext(SS, false); 1104 if (DC) { 1105 if (RequireCompleteDeclContext(SS, DC)) 1106 return ExprError(); 1107 // FIXME: We should be checking whether DC is the current instantiation. 1108 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) 1109 DependentID = !IsFullyFormedScope(*this, RD); 1110 } else { 1111 DependentID = true; 1112 } 1113 } 1114 1115 if (DependentID) { 1116 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1117 TemplateArgs); 1118 } 1119 bool IvarLookupFollowUp = false; 1120 // Perform the required lookup. 1121 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1122 if (TemplateArgs) { 1123 // Lookup the template name again to correctly establish the context in 1124 // which it was found. This is really unfortunate as we already did the 1125 // lookup to determine that it was a template name in the first place. If 1126 // this becomes a performance hit, we can work harder to preserve those 1127 // results until we get here but it's likely not worth it. 1128 bool MemberOfUnknownSpecialization; 1129 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1130 MemberOfUnknownSpecialization); 1131 } else { 1132 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1133 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1134 1135 // If this reference is in an Objective-C method, then we need to do 1136 // some special Objective-C lookup, too. 1137 if (IvarLookupFollowUp) { 1138 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1139 if (E.isInvalid()) 1140 return ExprError(); 1141 1142 Expr *Ex = E.takeAs<Expr>(); 1143 if (Ex) return Owned(Ex); 1144 // Synthesize ivars lazily 1145 if (getLangOptions().ObjCNonFragileABI2) { 1146 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) 1147 return ActOnIdExpression(S, SS, Id, HasTrailingLParen, 1148 isAddressOfOperand); 1149 } 1150 // for further use, this must be set to false if in class method. 1151 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod(); 1152 } 1153 } 1154 1155 if (R.isAmbiguous()) 1156 return ExprError(); 1157 1158 // Determine whether this name might be a candidate for 1159 // argument-dependent lookup. 1160 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1161 1162 if (R.empty() && !ADL) { 1163 // Otherwise, this could be an implicitly declared function reference (legal 1164 // in C90, extension in C99, forbidden in C++). 1165 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1166 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1167 if (D) R.addDecl(D); 1168 } 1169 1170 // If this name wasn't predeclared and if this is not a function 1171 // call, diagnose the problem. 1172 if (R.empty()) { 1173 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown)) 1174 return ExprError(); 1175 1176 assert(!R.empty() && 1177 "DiagnoseEmptyLookup returned false but added no results"); 1178 1179 // If we found an Objective-C instance variable, let 1180 // LookupInObjCMethod build the appropriate expression to 1181 // reference the ivar. 1182 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1183 R.clear(); 1184 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1185 assert(E.isInvalid() || E.get()); 1186 return move(E); 1187 } 1188 } 1189 } 1190 1191 // This is guaranteed from this point on. 1192 assert(!R.empty() || ADL); 1193 1194 if (VarDecl *Var = R.getAsSingle<VarDecl>()) { 1195 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp && 1196 !getLangOptions().ObjCNonFragileABI2 && 1197 Var->isFileVarDecl()) { 1198 ObjCPropertyDecl *Property = 1199 OkToSynthesizeProvisionalIvar(*this, II, NameLoc); 1200 if (Property) { 1201 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName(); 1202 Diag(Property->getLocation(), diag::note_property_declare); 1203 Diag(Var->getLocation(), diag::note_global_declared_at); 1204 } 1205 } 1206 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) { 1207 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 1208 // C99 DR 316 says that, if a function type comes from a 1209 // function definition (without a prototype), that type is only 1210 // used for checking compatibility. Therefore, when referencing 1211 // the function, we pretend that we don't have the full function 1212 // type. 1213 if (DiagnoseUseOfDecl(Func, NameLoc)) 1214 return ExprError(); 1215 1216 QualType T = Func->getType(); 1217 QualType NoProtoType = T; 1218 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>()) 1219 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(), 1220 Proto->getExtInfo()); 1221 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS); 1222 } 1223 } 1224 1225 // Check whether this might be a C++ implicit instance member access. 1226 // C++ [expr.prim.general]p6: 1227 // Within the definition of a non-static member function, an 1228 // identifier that names a non-static member is transformed to a 1229 // class member access expression. 1230 // But note that &SomeClass::foo is grammatically distinct, even 1231 // though we don't parse it that way. 1232 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1233 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty()); 1234 if (!isAbstractMemberPointer) 1235 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1236 } 1237 1238 if (TemplateArgs) 1239 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1240 1241 return BuildDeclarationNameExpr(SS, R, ADL); 1242} 1243 1244/// Builds an expression which might be an implicit member expression. 1245ExprResult 1246Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 1247 LookupResult &R, 1248 const TemplateArgumentListInfo *TemplateArgs) { 1249 switch (ClassifyImplicitMemberAccess(*this, R)) { 1250 case IMA_Instance: 1251 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true); 1252 1253 case IMA_AnonymousMember: 1254 assert(R.isSingleResult()); 1255 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(), 1256 R.getAsSingle<FieldDecl>()); 1257 1258 case IMA_Mixed: 1259 case IMA_Mixed_Unrelated: 1260 case IMA_Unresolved: 1261 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false); 1262 1263 case IMA_Static: 1264 case IMA_Mixed_StaticContext: 1265 case IMA_Unresolved_StaticContext: 1266 if (TemplateArgs) 1267 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs); 1268 return BuildDeclarationNameExpr(SS, R, false); 1269 1270 case IMA_Error_StaticContext: 1271 case IMA_Error_Unrelated: 1272 DiagnoseInstanceReference(*this, SS, R); 1273 return ExprError(); 1274 } 1275 1276 llvm_unreachable("unexpected instance member access kind"); 1277 return ExprError(); 1278} 1279 1280/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1281/// declaration name, generally during template instantiation. 1282/// There's a large number of things which don't need to be done along 1283/// this path. 1284ExprResult 1285Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1286 const DeclarationNameInfo &NameInfo) { 1287 DeclContext *DC; 1288 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1289 return BuildDependentDeclRefExpr(SS, NameInfo, 0); 1290 1291 if (RequireCompleteDeclContext(SS, DC)) 1292 return ExprError(); 1293 1294 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1295 LookupQualifiedName(R, DC); 1296 1297 if (R.isAmbiguous()) 1298 return ExprError(); 1299 1300 if (R.empty()) { 1301 Diag(NameInfo.getLoc(), diag::err_no_member) 1302 << NameInfo.getName() << DC << SS.getRange(); 1303 return ExprError(); 1304 } 1305 1306 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1307} 1308 1309/// LookupInObjCMethod - The parser has read a name in, and Sema has 1310/// detected that we're currently inside an ObjC method. Perform some 1311/// additional lookup. 1312/// 1313/// Ideally, most of this would be done by lookup, but there's 1314/// actually quite a lot of extra work involved. 1315/// 1316/// Returns a null sentinel to indicate trivial success. 1317ExprResult 1318Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1319 IdentifierInfo *II, bool AllowBuiltinCreation) { 1320 SourceLocation Loc = Lookup.getNameLoc(); 1321 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1322 1323 // There are two cases to handle here. 1) scoped lookup could have failed, 1324 // in which case we should look for an ivar. 2) scoped lookup could have 1325 // found a decl, but that decl is outside the current instance method (i.e. 1326 // a global variable). In these two cases, we do a lookup for an ivar with 1327 // this name, if the lookup sucedes, we replace it our current decl. 1328 1329 // If we're in a class method, we don't normally want to look for 1330 // ivars. But if we don't find anything else, and there's an 1331 // ivar, that's an error. 1332 bool IsClassMethod = CurMethod->isClassMethod(); 1333 1334 bool LookForIvars; 1335 if (Lookup.empty()) 1336 LookForIvars = true; 1337 else if (IsClassMethod) 1338 LookForIvars = false; 1339 else 1340 LookForIvars = (Lookup.isSingleResult() && 1341 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1342 ObjCInterfaceDecl *IFace = 0; 1343 if (LookForIvars) { 1344 IFace = CurMethod->getClassInterface(); 1345 ObjCInterfaceDecl *ClassDeclared; 1346 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1347 // Diagnose using an ivar in a class method. 1348 if (IsClassMethod) 1349 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1350 << IV->getDeclName()); 1351 1352 // If we're referencing an invalid decl, just return this as a silent 1353 // error node. The error diagnostic was already emitted on the decl. 1354 if (IV->isInvalidDecl()) 1355 return ExprError(); 1356 1357 // Check if referencing a field with __attribute__((deprecated)). 1358 if (DiagnoseUseOfDecl(IV, Loc)) 1359 return ExprError(); 1360 1361 // Diagnose the use of an ivar outside of the declaring class. 1362 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1363 ClassDeclared != IFace) 1364 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1365 1366 // FIXME: This should use a new expr for a direct reference, don't 1367 // turn this into Self->ivar, just return a BareIVarExpr or something. 1368 IdentifierInfo &II = Context.Idents.get("self"); 1369 UnqualifiedId SelfName; 1370 SelfName.setIdentifier(&II, SourceLocation()); 1371 CXXScopeSpec SelfScopeSpec; 1372 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1373 SelfName, false, false); 1374 MarkDeclarationReferenced(Loc, IV); 1375 return Owned(new (Context) 1376 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1377 SelfExpr.takeAs<Expr>(), true, true)); 1378 } 1379 } else if (CurMethod->isInstanceMethod()) { 1380 // We should warn if a local variable hides an ivar. 1381 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 1382 ObjCInterfaceDecl *ClassDeclared; 1383 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1384 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1385 IFace == ClassDeclared) 1386 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1387 } 1388 } 1389 1390 if (Lookup.empty() && II && AllowBuiltinCreation) { 1391 // FIXME. Consolidate this with similar code in LookupName. 1392 if (unsigned BuiltinID = II->getBuiltinID()) { 1393 if (!(getLangOptions().CPlusPlus && 1394 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1395 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1396 S, Lookup.isForRedeclaration(), 1397 Lookup.getNameLoc()); 1398 if (D) Lookup.addDecl(D); 1399 } 1400 } 1401 } 1402 // Sentinel value saying that we didn't do anything special. 1403 return Owned((Expr*) 0); 1404} 1405 1406/// \brief Cast a base object to a member's actual type. 1407/// 1408/// Logically this happens in three phases: 1409/// 1410/// * First we cast from the base type to the naming class. 1411/// The naming class is the class into which we were looking 1412/// when we found the member; it's the qualifier type if a 1413/// qualifier was provided, and otherwise it's the base type. 1414/// 1415/// * Next we cast from the naming class to the declaring class. 1416/// If the member we found was brought into a class's scope by 1417/// a using declaration, this is that class; otherwise it's 1418/// the class declaring the member. 1419/// 1420/// * Finally we cast from the declaring class to the "true" 1421/// declaring class of the member. This conversion does not 1422/// obey access control. 1423bool 1424Sema::PerformObjectMemberConversion(Expr *&From, 1425 NestedNameSpecifier *Qualifier, 1426 NamedDecl *FoundDecl, 1427 NamedDecl *Member) { 1428 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1429 if (!RD) 1430 return false; 1431 1432 QualType DestRecordType; 1433 QualType DestType; 1434 QualType FromRecordType; 1435 QualType FromType = From->getType(); 1436 bool PointerConversions = false; 1437 if (isa<FieldDecl>(Member)) { 1438 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1439 1440 if (FromType->getAs<PointerType>()) { 1441 DestType = Context.getPointerType(DestRecordType); 1442 FromRecordType = FromType->getPointeeType(); 1443 PointerConversions = true; 1444 } else { 1445 DestType = DestRecordType; 1446 FromRecordType = FromType; 1447 } 1448 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1449 if (Method->isStatic()) 1450 return false; 1451 1452 DestType = Method->getThisType(Context); 1453 DestRecordType = DestType->getPointeeType(); 1454 1455 if (FromType->getAs<PointerType>()) { 1456 FromRecordType = FromType->getPointeeType(); 1457 PointerConversions = true; 1458 } else { 1459 FromRecordType = FromType; 1460 DestType = DestRecordType; 1461 } 1462 } else { 1463 // No conversion necessary. 1464 return false; 1465 } 1466 1467 if (DestType->isDependentType() || FromType->isDependentType()) 1468 return false; 1469 1470 // If the unqualified types are the same, no conversion is necessary. 1471 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1472 return false; 1473 1474 SourceRange FromRange = From->getSourceRange(); 1475 SourceLocation FromLoc = FromRange.getBegin(); 1476 1477 ImplicitCastExpr::ResultCategory Category = CastCategory(From); 1478 1479 // C++ [class.member.lookup]p8: 1480 // [...] Ambiguities can often be resolved by qualifying a name with its 1481 // class name. 1482 // 1483 // If the member was a qualified name and the qualified referred to a 1484 // specific base subobject type, we'll cast to that intermediate type 1485 // first and then to the object in which the member is declared. That allows 1486 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1487 // 1488 // class Base { public: int x; }; 1489 // class Derived1 : public Base { }; 1490 // class Derived2 : public Base { }; 1491 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1492 // 1493 // void VeryDerived::f() { 1494 // x = 17; // error: ambiguous base subobjects 1495 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1496 // } 1497 if (Qualifier) { 1498 QualType QType = QualType(Qualifier->getAsType(), 0); 1499 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 1500 assert(QType->isRecordType() && "lookup done with non-record type"); 1501 1502 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 1503 1504 // In C++98, the qualifier type doesn't actually have to be a base 1505 // type of the object type, in which case we just ignore it. 1506 // Otherwise build the appropriate casts. 1507 if (IsDerivedFrom(FromRecordType, QRecordType)) { 1508 CXXCastPath BasePath; 1509 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 1510 FromLoc, FromRange, &BasePath)) 1511 return true; 1512 1513 if (PointerConversions) 1514 QType = Context.getPointerType(QType); 1515 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase, 1516 Category, &BasePath); 1517 1518 FromType = QType; 1519 FromRecordType = QRecordType; 1520 1521 // If the qualifier type was the same as the destination type, 1522 // we're done. 1523 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1524 return false; 1525 } 1526 } 1527 1528 bool IgnoreAccess = false; 1529 1530 // If we actually found the member through a using declaration, cast 1531 // down to the using declaration's type. 1532 // 1533 // Pointer equality is fine here because only one declaration of a 1534 // class ever has member declarations. 1535 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 1536 assert(isa<UsingShadowDecl>(FoundDecl)); 1537 QualType URecordType = Context.getTypeDeclType( 1538 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 1539 1540 // We only need to do this if the naming-class to declaring-class 1541 // conversion is non-trivial. 1542 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 1543 assert(IsDerivedFrom(FromRecordType, URecordType)); 1544 CXXCastPath BasePath; 1545 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 1546 FromLoc, FromRange, &BasePath)) 1547 return true; 1548 1549 QualType UType = URecordType; 1550 if (PointerConversions) 1551 UType = Context.getPointerType(UType); 1552 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase, 1553 Category, &BasePath); 1554 FromType = UType; 1555 FromRecordType = URecordType; 1556 } 1557 1558 // We don't do access control for the conversion from the 1559 // declaring class to the true declaring class. 1560 IgnoreAccess = true; 1561 } 1562 1563 CXXCastPath BasePath; 1564 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 1565 FromLoc, FromRange, &BasePath, 1566 IgnoreAccess)) 1567 return true; 1568 1569 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase, 1570 Category, &BasePath); 1571 return false; 1572} 1573 1574/// \brief Build a MemberExpr AST node. 1575static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 1576 const CXXScopeSpec &SS, ValueDecl *Member, 1577 DeclAccessPair FoundDecl, 1578 const DeclarationNameInfo &MemberNameInfo, 1579 QualType Ty, 1580 const TemplateArgumentListInfo *TemplateArgs = 0) { 1581 NestedNameSpecifier *Qualifier = 0; 1582 SourceRange QualifierRange; 1583 if (SS.isSet()) { 1584 Qualifier = (NestedNameSpecifier *) SS.getScopeRep(); 1585 QualifierRange = SS.getRange(); 1586 } 1587 1588 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange, 1589 Member, FoundDecl, MemberNameInfo, 1590 TemplateArgs, Ty); 1591} 1592 1593/// Builds an implicit member access expression. The current context 1594/// is known to be an instance method, and the given unqualified lookup 1595/// set is known to contain only instance members, at least one of which 1596/// is from an appropriate type. 1597ExprResult 1598Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1599 LookupResult &R, 1600 const TemplateArgumentListInfo *TemplateArgs, 1601 bool IsKnownInstance) { 1602 assert(!R.empty() && !R.isAmbiguous()); 1603 1604 SourceLocation Loc = R.getNameLoc(); 1605 1606 // We may have found a field within an anonymous union or struct 1607 // (C++ [class.union]). 1608 // FIXME: This needs to happen post-isImplicitMemberReference? 1609 // FIXME: template-ids inside anonymous structs? 1610 if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) 1611 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1612 return BuildAnonymousStructUnionMemberReference(Loc, FD); 1613 1614 // If this is known to be an instance access, go ahead and build a 1615 // 'this' expression now. 1616 DeclContext *DC = getFunctionLevelDeclContext(); 1617 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 1618 Expr *This = 0; // null signifies implicit access 1619 if (IsKnownInstance) { 1620 SourceLocation Loc = R.getNameLoc(); 1621 if (SS.getRange().isValid()) 1622 Loc = SS.getRange().getBegin(); 1623 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true); 1624 } 1625 1626 return BuildMemberReferenceExpr(This, ThisType, 1627 /*OpLoc*/ SourceLocation(), 1628 /*IsArrow*/ true, 1629 SS, 1630 /*FirstQualifierInScope*/ 0, 1631 R, TemplateArgs); 1632} 1633 1634bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 1635 const LookupResult &R, 1636 bool HasTrailingLParen) { 1637 // Only when used directly as the postfix-expression of a call. 1638 if (!HasTrailingLParen) 1639 return false; 1640 1641 // Never if a scope specifier was provided. 1642 if (SS.isSet()) 1643 return false; 1644 1645 // Only in C++ or ObjC++. 1646 if (!getLangOptions().CPlusPlus) 1647 return false; 1648 1649 // Turn off ADL when we find certain kinds of declarations during 1650 // normal lookup: 1651 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1652 NamedDecl *D = *I; 1653 1654 // C++0x [basic.lookup.argdep]p3: 1655 // -- a declaration of a class member 1656 // Since using decls preserve this property, we check this on the 1657 // original decl. 1658 if (D->isCXXClassMember()) 1659 return false; 1660 1661 // C++0x [basic.lookup.argdep]p3: 1662 // -- a block-scope function declaration that is not a 1663 // using-declaration 1664 // NOTE: we also trigger this for function templates (in fact, we 1665 // don't check the decl type at all, since all other decl types 1666 // turn off ADL anyway). 1667 if (isa<UsingShadowDecl>(D)) 1668 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1669 else if (D->getDeclContext()->isFunctionOrMethod()) 1670 return false; 1671 1672 // C++0x [basic.lookup.argdep]p3: 1673 // -- a declaration that is neither a function or a function 1674 // template 1675 // And also for builtin functions. 1676 if (isa<FunctionDecl>(D)) { 1677 FunctionDecl *FDecl = cast<FunctionDecl>(D); 1678 1679 // But also builtin functions. 1680 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 1681 return false; 1682 } else if (!isa<FunctionTemplateDecl>(D)) 1683 return false; 1684 } 1685 1686 return true; 1687} 1688 1689 1690/// Diagnoses obvious problems with the use of the given declaration 1691/// as an expression. This is only actually called for lookups that 1692/// were not overloaded, and it doesn't promise that the declaration 1693/// will in fact be used. 1694static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 1695 if (isa<TypedefDecl>(D)) { 1696 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 1697 return true; 1698 } 1699 1700 if (isa<ObjCInterfaceDecl>(D)) { 1701 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 1702 return true; 1703 } 1704 1705 if (isa<NamespaceDecl>(D)) { 1706 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 1707 return true; 1708 } 1709 1710 return false; 1711} 1712 1713ExprResult 1714Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1715 LookupResult &R, 1716 bool NeedsADL) { 1717 // If this is a single, fully-resolved result and we don't need ADL, 1718 // just build an ordinary singleton decl ref. 1719 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 1720 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 1721 R.getFoundDecl()); 1722 1723 // We only need to check the declaration if there's exactly one 1724 // result, because in the overloaded case the results can only be 1725 // functions and function templates. 1726 if (R.isSingleResult() && 1727 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 1728 return ExprError(); 1729 1730 // Otherwise, just build an unresolved lookup expression. Suppress 1731 // any lookup-related diagnostics; we'll hash these out later, when 1732 // we've picked a target. 1733 R.suppressDiagnostics(); 1734 1735 bool Dependent 1736 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0); 1737 UnresolvedLookupExpr *ULE 1738 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(), 1739 (NestedNameSpecifier*) SS.getScopeRep(), 1740 SS.getRange(), R.getLookupNameInfo(), 1741 NeedsADL, R.isOverloadedResult(), 1742 R.begin(), R.end()); 1743 1744 return Owned(ULE); 1745} 1746 1747 1748/// \brief Complete semantic analysis for a reference to the given declaration. 1749ExprResult 1750Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1751 const DeclarationNameInfo &NameInfo, 1752 NamedDecl *D) { 1753 assert(D && "Cannot refer to a NULL declaration"); 1754 assert(!isa<FunctionTemplateDecl>(D) && 1755 "Cannot refer unambiguously to a function template"); 1756 1757 SourceLocation Loc = NameInfo.getLoc(); 1758 if (CheckDeclInExpr(*this, Loc, D)) 1759 return ExprError(); 1760 1761 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 1762 // Specifically diagnose references to class templates that are missing 1763 // a template argument list. 1764 Diag(Loc, diag::err_template_decl_ref) 1765 << Template << SS.getRange(); 1766 Diag(Template->getLocation(), diag::note_template_decl_here); 1767 return ExprError(); 1768 } 1769 1770 // Make sure that we're referring to a value. 1771 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1772 if (!VD) { 1773 Diag(Loc, diag::err_ref_non_value) 1774 << D << SS.getRange(); 1775 Diag(D->getLocation(), diag::note_declared_at); 1776 return ExprError(); 1777 } 1778 1779 // Check whether this declaration can be used. Note that we suppress 1780 // this check when we're going to perform argument-dependent lookup 1781 // on this function name, because this might not be the function 1782 // that overload resolution actually selects. 1783 if (DiagnoseUseOfDecl(VD, Loc)) 1784 return ExprError(); 1785 1786 // Only create DeclRefExpr's for valid Decl's. 1787 if (VD->isInvalidDecl()) 1788 return ExprError(); 1789 1790 // If the identifier reference is inside a block, and it refers to a value 1791 // that is outside the block, create a BlockDeclRefExpr instead of a 1792 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1793 // the block is formed. 1794 // 1795 // We do not do this for things like enum constants, global variables, etc, 1796 // as they do not get snapshotted. 1797 // 1798 if (getCurBlock() && 1799 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) { 1800 if (VD->getType().getTypePtr()->isVariablyModifiedType()) { 1801 Diag(Loc, diag::err_ref_vm_type); 1802 Diag(D->getLocation(), diag::note_declared_at); 1803 return ExprError(); 1804 } 1805 1806 if (VD->getType()->isArrayType()) { 1807 Diag(Loc, diag::err_ref_array_type); 1808 Diag(D->getLocation(), diag::note_declared_at); 1809 return ExprError(); 1810 } 1811 1812 MarkDeclarationReferenced(Loc, VD); 1813 QualType ExprTy = VD->getType().getNonReferenceType(); 1814 // The BlocksAttr indicates the variable is bound by-reference. 1815 if (VD->getAttr<BlocksAttr>()) 1816 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1817 // This is to record that a 'const' was actually synthesize and added. 1818 bool constAdded = !ExprTy.isConstQualified(); 1819 // Variable will be bound by-copy, make it const within the closure. 1820 1821 ExprTy.addConst(); 1822 QualType T = VD->getType(); 1823 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD, 1824 ExprTy, Loc, false, 1825 constAdded); 1826 if (getLangOptions().CPlusPlus) { 1827 if (!T->isDependentType() && !T->isReferenceType()) { 1828 Expr *E = new (Context) 1829 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T, 1830 SourceLocation()); 1831 1832 ExprResult Res = PerformCopyInitialization( 1833 InitializedEntity::InitializeBlock(VD->getLocation(), 1834 T, false), 1835 SourceLocation(), 1836 Owned(E)); 1837 if (!Res.isInvalid()) { 1838 Res = MaybeCreateCXXExprWithTemporaries(Res.get()); 1839 Expr *Init = Res.takeAs<Expr>(); 1840 BDRE->setCopyConstructorExpr(Init); 1841 } 1842 } 1843 } 1844 return Owned(BDRE); 1845 } 1846 // If this reference is not in a block or if the referenced variable is 1847 // within the block, create a normal DeclRefExpr. 1848 1849 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 1850 NameInfo, &SS); 1851} 1852 1853ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1854 tok::TokenKind Kind) { 1855 PredefinedExpr::IdentType IT; 1856 1857 switch (Kind) { 1858 default: assert(0 && "Unknown simple primary expr!"); 1859 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1860 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1861 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1862 } 1863 1864 // Pre-defined identifiers are of type char[x], where x is the length of the 1865 // string. 1866 1867 Decl *currentDecl = getCurFunctionOrMethodDecl(); 1868 if (!currentDecl && getCurBlock()) 1869 currentDecl = getCurBlock()->TheDecl; 1870 if (!currentDecl) { 1871 Diag(Loc, diag::ext_predef_outside_function); 1872 currentDecl = Context.getTranslationUnitDecl(); 1873 } 1874 1875 QualType ResTy; 1876 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 1877 ResTy = Context.DependentTy; 1878 } else { 1879 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 1880 1881 llvm::APInt LengthI(32, Length + 1); 1882 ResTy = Context.CharTy.withConst(); 1883 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1884 } 1885 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1886} 1887 1888ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1889 llvm::SmallString<16> CharBuffer; 1890 bool Invalid = false; 1891 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 1892 if (Invalid) 1893 return ExprError(); 1894 1895 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 1896 PP); 1897 if (Literal.hadError()) 1898 return ExprError(); 1899 1900 QualType Ty; 1901 if (!getLangOptions().CPlusPlus) 1902 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 1903 else if (Literal.isWide()) 1904 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 1905 else if (Literal.isMultiChar()) 1906 Ty = Context.IntTy; // 'wxyz' -> int in C++. 1907 else 1908 Ty = Context.CharTy; // 'x' -> char in C++ 1909 1910 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1911 Literal.isWide(), 1912 Ty, Tok.getLocation())); 1913} 1914 1915ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1916 // Fast path for a single digit (which is quite common). A single digit 1917 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1918 if (Tok.getLength() == 1) { 1919 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1920 unsigned IntSize = Context.Target.getIntWidth(); 1921 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1922 Context.IntTy, Tok.getLocation())); 1923 } 1924 1925 llvm::SmallString<512> IntegerBuffer; 1926 // Add padding so that NumericLiteralParser can overread by one character. 1927 IntegerBuffer.resize(Tok.getLength()+1); 1928 const char *ThisTokBegin = &IntegerBuffer[0]; 1929 1930 // Get the spelling of the token, which eliminates trigraphs, etc. 1931 bool Invalid = false; 1932 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 1933 if (Invalid) 1934 return ExprError(); 1935 1936 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1937 Tok.getLocation(), PP); 1938 if (Literal.hadError) 1939 return ExprError(); 1940 1941 Expr *Res; 1942 1943 if (Literal.isFloatingLiteral()) { 1944 QualType Ty; 1945 if (Literal.isFloat) 1946 Ty = Context.FloatTy; 1947 else if (!Literal.isLong) 1948 Ty = Context.DoubleTy; 1949 else 1950 Ty = Context.LongDoubleTy; 1951 1952 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1953 1954 using llvm::APFloat; 1955 APFloat Val(Format); 1956 1957 APFloat::opStatus result = Literal.GetFloatValue(Val); 1958 1959 // Overflow is always an error, but underflow is only an error if 1960 // we underflowed to zero (APFloat reports denormals as underflow). 1961 if ((result & APFloat::opOverflow) || 1962 ((result & APFloat::opUnderflow) && Val.isZero())) { 1963 unsigned diagnostic; 1964 llvm::SmallString<20> buffer; 1965 if (result & APFloat::opOverflow) { 1966 diagnostic = diag::warn_float_overflow; 1967 APFloat::getLargest(Format).toString(buffer); 1968 } else { 1969 diagnostic = diag::warn_float_underflow; 1970 APFloat::getSmallest(Format).toString(buffer); 1971 } 1972 1973 Diag(Tok.getLocation(), diagnostic) 1974 << Ty 1975 << llvm::StringRef(buffer.data(), buffer.size()); 1976 } 1977 1978 bool isExact = (result == APFloat::opOK); 1979 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation()); 1980 1981 } else if (!Literal.isIntegerLiteral()) { 1982 return ExprError(); 1983 } else { 1984 QualType Ty; 1985 1986 // long long is a C99 feature. 1987 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1988 Literal.isLongLong) 1989 Diag(Tok.getLocation(), diag::ext_longlong); 1990 1991 // Get the value in the widest-possible width. 1992 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1993 1994 if (Literal.GetIntegerValue(ResultVal)) { 1995 // If this value didn't fit into uintmax_t, warn and force to ull. 1996 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1997 Ty = Context.UnsignedLongLongTy; 1998 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1999 "long long is not intmax_t?"); 2000 } else { 2001 // If this value fits into a ULL, try to figure out what else it fits into 2002 // according to the rules of C99 6.4.4.1p5. 2003 2004 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2005 // be an unsigned int. 2006 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2007 2008 // Check from smallest to largest, picking the smallest type we can. 2009 unsigned Width = 0; 2010 if (!Literal.isLong && !Literal.isLongLong) { 2011 // Are int/unsigned possibilities? 2012 unsigned IntSize = Context.Target.getIntWidth(); 2013 2014 // Does it fit in a unsigned int? 2015 if (ResultVal.isIntN(IntSize)) { 2016 // Does it fit in a signed int? 2017 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2018 Ty = Context.IntTy; 2019 else if (AllowUnsigned) 2020 Ty = Context.UnsignedIntTy; 2021 Width = IntSize; 2022 } 2023 } 2024 2025 // Are long/unsigned long possibilities? 2026 if (Ty.isNull() && !Literal.isLongLong) { 2027 unsigned LongSize = Context.Target.getLongWidth(); 2028 2029 // Does it fit in a unsigned long? 2030 if (ResultVal.isIntN(LongSize)) { 2031 // Does it fit in a signed long? 2032 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2033 Ty = Context.LongTy; 2034 else if (AllowUnsigned) 2035 Ty = Context.UnsignedLongTy; 2036 Width = LongSize; 2037 } 2038 } 2039 2040 // Finally, check long long if needed. 2041 if (Ty.isNull()) { 2042 unsigned LongLongSize = Context.Target.getLongLongWidth(); 2043 2044 // Does it fit in a unsigned long long? 2045 if (ResultVal.isIntN(LongLongSize)) { 2046 // Does it fit in a signed long long? 2047 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 2048 Ty = Context.LongLongTy; 2049 else if (AllowUnsigned) 2050 Ty = Context.UnsignedLongLongTy; 2051 Width = LongLongSize; 2052 } 2053 } 2054 2055 // If we still couldn't decide a type, we probably have something that 2056 // does not fit in a signed long long, but has no U suffix. 2057 if (Ty.isNull()) { 2058 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2059 Ty = Context.UnsignedLongLongTy; 2060 Width = Context.Target.getLongLongWidth(); 2061 } 2062 2063 if (ResultVal.getBitWidth() != Width) 2064 ResultVal.trunc(Width); 2065 } 2066 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 2067 } 2068 2069 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2070 if (Literal.isImaginary) 2071 Res = new (Context) ImaginaryLiteral(Res, 2072 Context.getComplexType(Res->getType())); 2073 2074 return Owned(Res); 2075} 2076 2077ExprResult Sema::ActOnParenExpr(SourceLocation L, 2078 SourceLocation R, Expr *E) { 2079 assert((E != 0) && "ActOnParenExpr() missing expr"); 2080 return Owned(new (Context) ParenExpr(L, R, E)); 2081} 2082 2083/// The UsualUnaryConversions() function is *not* called by this routine. 2084/// See C99 6.3.2.1p[2-4] for more details. 2085bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 2086 SourceLocation OpLoc, 2087 const SourceRange &ExprRange, 2088 bool isSizeof) { 2089 if (exprType->isDependentType()) 2090 return false; 2091 2092 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2093 // the result is the size of the referenced type." 2094 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2095 // result shall be the alignment of the referenced type." 2096 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 2097 exprType = Ref->getPointeeType(); 2098 2099 // C99 6.5.3.4p1: 2100 if (exprType->isFunctionType()) { 2101 // alignof(function) is allowed as an extension. 2102 if (isSizeof) 2103 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 2104 return false; 2105 } 2106 2107 // Allow sizeof(void)/alignof(void) as an extension. 2108 if (exprType->isVoidType()) { 2109 Diag(OpLoc, diag::ext_sizeof_void_type) 2110 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 2111 return false; 2112 } 2113 2114 if (RequireCompleteType(OpLoc, exprType, 2115 PDiag(diag::err_sizeof_alignof_incomplete_type) 2116 << int(!isSizeof) << ExprRange)) 2117 return true; 2118 2119 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2120 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) { 2121 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 2122 << exprType << isSizeof << ExprRange; 2123 return true; 2124 } 2125 2126 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) { 2127 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type) 2128 << !isSizeof << ExprRange; 2129 return true; 2130 } 2131 2132 return false; 2133} 2134 2135bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 2136 const SourceRange &ExprRange) { 2137 E = E->IgnoreParens(); 2138 2139 // alignof decl is always ok. 2140 if (isa<DeclRefExpr>(E)) 2141 return false; 2142 2143 // Cannot know anything else if the expression is dependent. 2144 if (E->isTypeDependent()) 2145 return false; 2146 2147 if (E->getBitField()) { 2148 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 2149 return true; 2150 } 2151 2152 // Alignment of a field access is always okay, so long as it isn't a 2153 // bit-field. 2154 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2155 if (isa<FieldDecl>(ME->getMemberDecl())) 2156 return false; 2157 2158 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 2159} 2160 2161/// \brief Build a sizeof or alignof expression given a type operand. 2162ExprResult 2163Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo, 2164 SourceLocation OpLoc, 2165 bool isSizeOf, SourceRange R) { 2166 if (!TInfo) 2167 return ExprError(); 2168 2169 QualType T = TInfo->getType(); 2170 2171 if (!T->isDependentType() && 2172 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 2173 return ExprError(); 2174 2175 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2176 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo, 2177 Context.getSizeType(), OpLoc, 2178 R.getEnd())); 2179} 2180 2181/// \brief Build a sizeof or alignof expression given an expression 2182/// operand. 2183ExprResult 2184Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 2185 bool isSizeOf, SourceRange R) { 2186 // Verify that the operand is valid. 2187 bool isInvalid = false; 2188 if (E->isTypeDependent()) { 2189 // Delay type-checking for type-dependent expressions. 2190 } else if (!isSizeOf) { 2191 isInvalid = CheckAlignOfExpr(E, OpLoc, R); 2192 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2193 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 2194 isInvalid = true; 2195 } else { 2196 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 2197 } 2198 2199 if (isInvalid) 2200 return ExprError(); 2201 2202 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2203 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 2204 Context.getSizeType(), OpLoc, 2205 R.getEnd())); 2206} 2207 2208/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 2209/// the same for @c alignof and @c __alignof 2210/// Note that the ArgRange is invalid if isType is false. 2211ExprResult 2212Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 2213 void *TyOrEx, const SourceRange &ArgRange) { 2214 // If error parsing type, ignore. 2215 if (TyOrEx == 0) return ExprError(); 2216 2217 if (isType) { 2218 TypeSourceInfo *TInfo; 2219 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 2220 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange); 2221 } 2222 2223 Expr *ArgEx = (Expr *)TyOrEx; 2224 ExprResult Result 2225 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 2226 2227 if (Result.isInvalid()) 2228 DeleteExpr(ArgEx); 2229 2230 return move(Result); 2231} 2232 2233QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 2234 if (V->isTypeDependent()) 2235 return Context.DependentTy; 2236 2237 // These operators return the element type of a complex type. 2238 if (const ComplexType *CT = V->getType()->getAs<ComplexType>()) 2239 return CT->getElementType(); 2240 2241 // Otherwise they pass through real integer and floating point types here. 2242 if (V->getType()->isArithmeticType()) 2243 return V->getType(); 2244 2245 // Reject anything else. 2246 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 2247 << (isReal ? "__real" : "__imag"); 2248 return QualType(); 2249} 2250 2251 2252 2253ExprResult 2254Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2255 tok::TokenKind Kind, Expr *Input) { 2256 UnaryOperator::Opcode Opc; 2257 switch (Kind) { 2258 default: assert(0 && "Unknown unary op!"); 2259 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 2260 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 2261 } 2262 2263 return BuildUnaryOp(S, OpLoc, Opc, Input); 2264} 2265 2266ExprResult 2267Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2268 Expr *Idx, SourceLocation RLoc) { 2269 // Since this might be a postfix expression, get rid of ParenListExprs. 2270 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2271 if (Result.isInvalid()) return ExprError(); 2272 Base = Result.take(); 2273 2274 Expr *LHSExp = Base, *RHSExp = Idx; 2275 2276 if (getLangOptions().CPlusPlus && 2277 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2278 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2279 Context.DependentTy, RLoc)); 2280 } 2281 2282 if (getLangOptions().CPlusPlus && 2283 (LHSExp->getType()->isRecordType() || 2284 LHSExp->getType()->isEnumeralType() || 2285 RHSExp->getType()->isRecordType() || 2286 RHSExp->getType()->isEnumeralType())) { 2287 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 2288 } 2289 2290 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 2291} 2292 2293 2294ExprResult 2295Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2296 Expr *Idx, SourceLocation RLoc) { 2297 Expr *LHSExp = Base; 2298 Expr *RHSExp = Idx; 2299 2300 // Perform default conversions. 2301 if (!LHSExp->getType()->getAs<VectorType>()) 2302 DefaultFunctionArrayLvalueConversion(LHSExp); 2303 DefaultFunctionArrayLvalueConversion(RHSExp); 2304 2305 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 2306 2307 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 2308 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 2309 // in the subscript position. As a result, we need to derive the array base 2310 // and index from the expression types. 2311 Expr *BaseExpr, *IndexExpr; 2312 QualType ResultType; 2313 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 2314 BaseExpr = LHSExp; 2315 IndexExpr = RHSExp; 2316 ResultType = Context.DependentTy; 2317 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 2318 BaseExpr = LHSExp; 2319 IndexExpr = RHSExp; 2320 ResultType = PTy->getPointeeType(); 2321 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 2322 // Handle the uncommon case of "123[Ptr]". 2323 BaseExpr = RHSExp; 2324 IndexExpr = LHSExp; 2325 ResultType = PTy->getPointeeType(); 2326 } else if (const ObjCObjectPointerType *PTy = 2327 LHSTy->getAs<ObjCObjectPointerType>()) { 2328 BaseExpr = LHSExp; 2329 IndexExpr = RHSExp; 2330 ResultType = PTy->getPointeeType(); 2331 } else if (const ObjCObjectPointerType *PTy = 2332 RHSTy->getAs<ObjCObjectPointerType>()) { 2333 // Handle the uncommon case of "123[Ptr]". 2334 BaseExpr = RHSExp; 2335 IndexExpr = LHSExp; 2336 ResultType = PTy->getPointeeType(); 2337 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 2338 BaseExpr = LHSExp; // vectors: V[123] 2339 IndexExpr = RHSExp; 2340 2341 // FIXME: need to deal with const... 2342 ResultType = VTy->getElementType(); 2343 } else if (LHSTy->isArrayType()) { 2344 // If we see an array that wasn't promoted by 2345 // DefaultFunctionArrayLvalueConversion, it must be an array that 2346 // wasn't promoted because of the C90 rule that doesn't 2347 // allow promoting non-lvalue arrays. Warn, then 2348 // force the promotion here. 2349 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2350 LHSExp->getSourceRange(); 2351 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 2352 CastExpr::CK_ArrayToPointerDecay); 2353 LHSTy = LHSExp->getType(); 2354 2355 BaseExpr = LHSExp; 2356 IndexExpr = RHSExp; 2357 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 2358 } else if (RHSTy->isArrayType()) { 2359 // Same as previous, except for 123[f().a] case 2360 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2361 RHSExp->getSourceRange(); 2362 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 2363 CastExpr::CK_ArrayToPointerDecay); 2364 RHSTy = RHSExp->getType(); 2365 2366 BaseExpr = RHSExp; 2367 IndexExpr = LHSExp; 2368 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 2369 } else { 2370 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 2371 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 2372 } 2373 // C99 6.5.2.1p1 2374 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 2375 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 2376 << IndexExpr->getSourceRange()); 2377 2378 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 2379 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 2380 && !IndexExpr->isTypeDependent()) 2381 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 2382 2383 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 2384 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 2385 // type. Note that Functions are not objects, and that (in C99 parlance) 2386 // incomplete types are not object types. 2387 if (ResultType->isFunctionType()) { 2388 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 2389 << ResultType << BaseExpr->getSourceRange(); 2390 return ExprError(); 2391 } 2392 2393 if (!ResultType->isDependentType() && 2394 RequireCompleteType(LLoc, ResultType, 2395 PDiag(diag::err_subscript_incomplete_type) 2396 << BaseExpr->getSourceRange())) 2397 return ExprError(); 2398 2399 // Diagnose bad cases where we step over interface counts. 2400 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 2401 Diag(LLoc, diag::err_subscript_nonfragile_interface) 2402 << ResultType << BaseExpr->getSourceRange(); 2403 return ExprError(); 2404 } 2405 2406 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2407 ResultType, RLoc)); 2408} 2409 2410QualType Sema:: 2411CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 2412 const IdentifierInfo *CompName, 2413 SourceLocation CompLoc) { 2414 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 2415 // see FIXME there. 2416 // 2417 // FIXME: This logic can be greatly simplified by splitting it along 2418 // halving/not halving and reworking the component checking. 2419 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 2420 2421 // The vector accessor can't exceed the number of elements. 2422 const char *compStr = CompName->getNameStart(); 2423 2424 // This flag determines whether or not the component is one of the four 2425 // special names that indicate a subset of exactly half the elements are 2426 // to be selected. 2427 bool HalvingSwizzle = false; 2428 2429 // This flag determines whether or not CompName has an 's' char prefix, 2430 // indicating that it is a string of hex values to be used as vector indices. 2431 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 2432 2433 // Check that we've found one of the special components, or that the component 2434 // names must come from the same set. 2435 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 2436 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 2437 HalvingSwizzle = true; 2438 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 2439 do 2440 compStr++; 2441 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 2442 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 2443 do 2444 compStr++; 2445 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 2446 } 2447 2448 if (!HalvingSwizzle && *compStr) { 2449 // We didn't get to the end of the string. This means the component names 2450 // didn't come from the same set *or* we encountered an illegal name. 2451 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 2452 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc); 2453 return QualType(); 2454 } 2455 2456 // Ensure no component accessor exceeds the width of the vector type it 2457 // operates on. 2458 if (!HalvingSwizzle) { 2459 compStr = CompName->getNameStart(); 2460 2461 if (HexSwizzle) 2462 compStr++; 2463 2464 while (*compStr) { 2465 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 2466 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 2467 << baseType << SourceRange(CompLoc); 2468 return QualType(); 2469 } 2470 } 2471 } 2472 2473 // The component accessor looks fine - now we need to compute the actual type. 2474 // The vector type is implied by the component accessor. For example, 2475 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 2476 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 2477 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 2478 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 2479 : CompName->getLength(); 2480 if (HexSwizzle) 2481 CompSize--; 2482 2483 if (CompSize == 1) 2484 return vecType->getElementType(); 2485 2486 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 2487 // Now look up the TypeDefDecl from the vector type. Without this, 2488 // diagostics look bad. We want extended vector types to appear built-in. 2489 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 2490 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 2491 return Context.getTypedefType(ExtVectorDecls[i]); 2492 } 2493 return VT; // should never get here (a typedef type should always be found). 2494} 2495 2496static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 2497 IdentifierInfo *Member, 2498 const Selector &Sel, 2499 ASTContext &Context) { 2500 2501 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 2502 return PD; 2503 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 2504 return OMD; 2505 2506 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 2507 E = PDecl->protocol_end(); I != E; ++I) { 2508 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, 2509 Context)) 2510 return D; 2511 } 2512 return 0; 2513} 2514 2515static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy, 2516 IdentifierInfo *Member, 2517 const Selector &Sel, 2518 ASTContext &Context) { 2519 // Check protocols on qualified interfaces. 2520 Decl *GDecl = 0; 2521 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2522 E = QIdTy->qual_end(); I != E; ++I) { 2523 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2524 GDecl = PD; 2525 break; 2526 } 2527 // Also must look for a getter name which uses property syntax. 2528 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 2529 GDecl = OMD; 2530 break; 2531 } 2532 } 2533 if (!GDecl) { 2534 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2535 E = QIdTy->qual_end(); I != E; ++I) { 2536 // Search in the protocol-qualifier list of current protocol. 2537 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); 2538 if (GDecl) 2539 return GDecl; 2540 } 2541 } 2542 return GDecl; 2543} 2544 2545ExprResult 2546Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType, 2547 bool IsArrow, SourceLocation OpLoc, 2548 const CXXScopeSpec &SS, 2549 NamedDecl *FirstQualifierInScope, 2550 const DeclarationNameInfo &NameInfo, 2551 const TemplateArgumentListInfo *TemplateArgs) { 2552 // Even in dependent contexts, try to diagnose base expressions with 2553 // obviously wrong types, e.g.: 2554 // 2555 // T* t; 2556 // t.f; 2557 // 2558 // In Obj-C++, however, the above expression is valid, since it could be 2559 // accessing the 'f' property if T is an Obj-C interface. The extra check 2560 // allows this, while still reporting an error if T is a struct pointer. 2561 if (!IsArrow) { 2562 const PointerType *PT = BaseType->getAs<PointerType>(); 2563 if (PT && (!getLangOptions().ObjC1 || 2564 PT->getPointeeType()->isRecordType())) { 2565 assert(BaseExpr && "cannot happen with implicit member accesses"); 2566 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union) 2567 << BaseType << BaseExpr->getSourceRange(); 2568 return ExprError(); 2569 } 2570 } 2571 2572 assert(BaseType->isDependentType() || 2573 NameInfo.getName().isDependentName() || 2574 isDependentScopeSpecifier(SS)); 2575 2576 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 2577 // must have pointer type, and the accessed type is the pointee. 2578 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType, 2579 IsArrow, OpLoc, 2580 SS.getScopeRep(), 2581 SS.getRange(), 2582 FirstQualifierInScope, 2583 NameInfo, TemplateArgs)); 2584} 2585 2586/// We know that the given qualified member reference points only to 2587/// declarations which do not belong to the static type of the base 2588/// expression. Diagnose the problem. 2589static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 2590 Expr *BaseExpr, 2591 QualType BaseType, 2592 const CXXScopeSpec &SS, 2593 const LookupResult &R) { 2594 // If this is an implicit member access, use a different set of 2595 // diagnostics. 2596 if (!BaseExpr) 2597 return DiagnoseInstanceReference(SemaRef, SS, R); 2598 2599 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated) 2600 << SS.getRange() << R.getRepresentativeDecl() << BaseType; 2601} 2602 2603// Check whether the declarations we found through a nested-name 2604// specifier in a member expression are actually members of the base 2605// type. The restriction here is: 2606// 2607// C++ [expr.ref]p2: 2608// ... In these cases, the id-expression shall name a 2609// member of the class or of one of its base classes. 2610// 2611// So it's perfectly legitimate for the nested-name specifier to name 2612// an unrelated class, and for us to find an overload set including 2613// decls from classes which are not superclasses, as long as the decl 2614// we actually pick through overload resolution is from a superclass. 2615bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 2616 QualType BaseType, 2617 const CXXScopeSpec &SS, 2618 const LookupResult &R) { 2619 const RecordType *BaseRT = BaseType->getAs<RecordType>(); 2620 if (!BaseRT) { 2621 // We can't check this yet because the base type is still 2622 // dependent. 2623 assert(BaseType->isDependentType()); 2624 return false; 2625 } 2626 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 2627 2628 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2629 // If this is an implicit member reference and we find a 2630 // non-instance member, it's not an error. 2631 if (!BaseExpr && !(*I)->isCXXInstanceMember()) 2632 return false; 2633 2634 // Note that we use the DC of the decl, not the underlying decl. 2635 DeclContext *DC = (*I)->getDeclContext(); 2636 while (DC->isTransparentContext()) 2637 DC = DC->getParent(); 2638 2639 if (!DC->isRecord()) 2640 continue; 2641 2642 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord; 2643 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl()); 2644 2645 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord)) 2646 return false; 2647 } 2648 2649 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R); 2650 return true; 2651} 2652 2653static bool 2654LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 2655 SourceRange BaseRange, const RecordType *RTy, 2656 SourceLocation OpLoc, CXXScopeSpec &SS, 2657 bool HasTemplateArgs) { 2658 RecordDecl *RDecl = RTy->getDecl(); 2659 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 2660 SemaRef.PDiag(diag::err_typecheck_incomplete_tag) 2661 << BaseRange)) 2662 return true; 2663 2664 if (HasTemplateArgs) { 2665 // LookupTemplateName doesn't expect these both to exist simultaneously. 2666 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); 2667 2668 bool MOUS; 2669 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS); 2670 return false; 2671 } 2672 2673 DeclContext *DC = RDecl; 2674 if (SS.isSet()) { 2675 // If the member name was a qualified-id, look into the 2676 // nested-name-specifier. 2677 DC = SemaRef.computeDeclContext(SS, false); 2678 2679 if (SemaRef.RequireCompleteDeclContext(SS, DC)) { 2680 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 2681 << SS.getRange() << DC; 2682 return true; 2683 } 2684 2685 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 2686 2687 if (!isa<TypeDecl>(DC)) { 2688 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 2689 << DC << SS.getRange(); 2690 return true; 2691 } 2692 } 2693 2694 // The record definition is complete, now look up the member. 2695 SemaRef.LookupQualifiedName(R, DC); 2696 2697 if (!R.empty()) 2698 return false; 2699 2700 // We didn't find anything with the given name, so try to correct 2701 // for typos. 2702 DeclarationName Name = R.getLookupName(); 2703 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) && 2704 !R.empty() && 2705 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) { 2706 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest) 2707 << Name << DC << R.getLookupName() << SS.getRange() 2708 << FixItHint::CreateReplacement(R.getNameLoc(), 2709 R.getLookupName().getAsString()); 2710 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 2711 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl) 2712 << ND->getDeclName(); 2713 return false; 2714 } else { 2715 R.clear(); 2716 R.setLookupName(Name); 2717 } 2718 2719 return false; 2720} 2721 2722ExprResult 2723Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2724 SourceLocation OpLoc, bool IsArrow, 2725 CXXScopeSpec &SS, 2726 NamedDecl *FirstQualifierInScope, 2727 const DeclarationNameInfo &NameInfo, 2728 const TemplateArgumentListInfo *TemplateArgs) { 2729 if (BaseType->isDependentType() || 2730 (SS.isSet() && isDependentScopeSpecifier(SS))) 2731 return ActOnDependentMemberExpr(Base, BaseType, 2732 IsArrow, OpLoc, 2733 SS, FirstQualifierInScope, 2734 NameInfo, TemplateArgs); 2735 2736 LookupResult R(*this, NameInfo, LookupMemberName); 2737 2738 // Implicit member accesses. 2739 if (!Base) { 2740 QualType RecordTy = BaseType; 2741 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 2742 if (LookupMemberExprInRecord(*this, R, SourceRange(), 2743 RecordTy->getAs<RecordType>(), 2744 OpLoc, SS, TemplateArgs != 0)) 2745 return ExprError(); 2746 2747 // Explicit member accesses. 2748 } else { 2749 ExprResult Result = 2750 LookupMemberExpr(R, Base, IsArrow, OpLoc, 2751 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0); 2752 2753 if (Result.isInvalid()) { 2754 Owned(Base); 2755 return ExprError(); 2756 } 2757 2758 if (Result.get()) 2759 return move(Result); 2760 2761 // LookupMemberExpr can modify Base, and thus change BaseType 2762 BaseType = Base->getType(); 2763 } 2764 2765 return BuildMemberReferenceExpr(Base, BaseType, 2766 OpLoc, IsArrow, SS, FirstQualifierInScope, 2767 R, TemplateArgs); 2768} 2769 2770ExprResult 2771Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 2772 SourceLocation OpLoc, bool IsArrow, 2773 const CXXScopeSpec &SS, 2774 NamedDecl *FirstQualifierInScope, 2775 LookupResult &R, 2776 const TemplateArgumentListInfo *TemplateArgs, 2777 bool SuppressQualifierCheck) { 2778 QualType BaseType = BaseExprType; 2779 if (IsArrow) { 2780 assert(BaseType->isPointerType()); 2781 BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 2782 } 2783 R.setBaseObjectType(BaseType); 2784 2785 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 2786 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 2787 DeclarationName MemberName = MemberNameInfo.getName(); 2788 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 2789 2790 if (R.isAmbiguous()) 2791 return ExprError(); 2792 2793 if (R.empty()) { 2794 // Rederive where we looked up. 2795 DeclContext *DC = (SS.isSet() 2796 ? computeDeclContext(SS, false) 2797 : BaseType->getAs<RecordType>()->getDecl()); 2798 2799 Diag(R.getNameLoc(), diag::err_no_member) 2800 << MemberName << DC 2801 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 2802 return ExprError(); 2803 } 2804 2805 // Diagnose lookups that find only declarations from a non-base 2806 // type. This is possible for either qualified lookups (which may 2807 // have been qualified with an unrelated type) or implicit member 2808 // expressions (which were found with unqualified lookup and thus 2809 // may have come from an enclosing scope). Note that it's okay for 2810 // lookup to find declarations from a non-base type as long as those 2811 // aren't the ones picked by overload resolution. 2812 if ((SS.isSet() || !BaseExpr || 2813 (isa<CXXThisExpr>(BaseExpr) && 2814 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 2815 !SuppressQualifierCheck && 2816 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 2817 return ExprError(); 2818 2819 // Construct an unresolved result if we in fact got an unresolved 2820 // result. 2821 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 2822 bool Dependent = 2823 BaseExprType->isDependentType() || 2824 R.isUnresolvableResult() || 2825 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs); 2826 2827 // Suppress any lookup-related diagnostics; we'll do these when we 2828 // pick a member. 2829 R.suppressDiagnostics(); 2830 2831 UnresolvedMemberExpr *MemExpr 2832 = UnresolvedMemberExpr::Create(Context, Dependent, 2833 R.isUnresolvableResult(), 2834 BaseExpr, BaseExprType, 2835 IsArrow, OpLoc, 2836 Qualifier, SS.getRange(), 2837 MemberNameInfo, 2838 TemplateArgs, R.begin(), R.end()); 2839 2840 return Owned(MemExpr); 2841 } 2842 2843 assert(R.isSingleResult()); 2844 DeclAccessPair FoundDecl = R.begin().getPair(); 2845 NamedDecl *MemberDecl = R.getFoundDecl(); 2846 2847 // FIXME: diagnose the presence of template arguments now. 2848 2849 // If the decl being referenced had an error, return an error for this 2850 // sub-expr without emitting another error, in order to avoid cascading 2851 // error cases. 2852 if (MemberDecl->isInvalidDecl()) 2853 return ExprError(); 2854 2855 // Handle the implicit-member-access case. 2856 if (!BaseExpr) { 2857 // If this is not an instance member, convert to a non-member access. 2858 if (!MemberDecl->isCXXInstanceMember()) 2859 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 2860 2861 SourceLocation Loc = R.getNameLoc(); 2862 if (SS.getRange().isValid()) 2863 Loc = SS.getRange().getBegin(); 2864 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 2865 } 2866 2867 bool ShouldCheckUse = true; 2868 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 2869 // Don't diagnose the use of a virtual member function unless it's 2870 // explicitly qualified. 2871 if (MD->isVirtual() && !SS.isSet()) 2872 ShouldCheckUse = false; 2873 } 2874 2875 // Check the use of this member. 2876 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 2877 Owned(BaseExpr); 2878 return ExprError(); 2879 } 2880 2881 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2882 // We may have found a field within an anonymous union or struct 2883 // (C++ [class.union]). 2884 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() && 2885 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion()) 2886 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2887 BaseExpr, OpLoc); 2888 2889 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2890 QualType MemberType = FD->getType(); 2891 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) 2892 MemberType = Ref->getPointeeType(); 2893 else { 2894 Qualifiers BaseQuals = BaseType.getQualifiers(); 2895 BaseQuals.removeObjCGCAttr(); 2896 if (FD->isMutable()) BaseQuals.removeConst(); 2897 2898 Qualifiers MemberQuals 2899 = Context.getCanonicalType(MemberType).getQualifiers(); 2900 2901 Qualifiers Combined = BaseQuals + MemberQuals; 2902 if (Combined != MemberQuals) 2903 MemberType = Context.getQualifiedType(MemberType, Combined); 2904 } 2905 2906 MarkDeclarationReferenced(MemberLoc, FD); 2907 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD)) 2908 return ExprError(); 2909 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2910 FD, FoundDecl, MemberNameInfo, 2911 MemberType)); 2912 } 2913 2914 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2915 MarkDeclarationReferenced(MemberLoc, Var); 2916 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2917 Var, FoundDecl, MemberNameInfo, 2918 Var->getType().getNonReferenceType())); 2919 } 2920 2921 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2922 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2923 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2924 MemberFn, FoundDecl, MemberNameInfo, 2925 MemberFn->getType())); 2926 } 2927 2928 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2929 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2930 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2931 Enum, FoundDecl, MemberNameInfo, 2932 Enum->getType())); 2933 } 2934 2935 Owned(BaseExpr); 2936 2937 // We found something that we didn't expect. Complain. 2938 if (isa<TypeDecl>(MemberDecl)) 2939 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 2940 << MemberName << BaseType << int(IsArrow); 2941 else 2942 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 2943 << MemberName << BaseType << int(IsArrow); 2944 2945 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 2946 << MemberName; 2947 R.suppressDiagnostics(); 2948 return ExprError(); 2949} 2950 2951/// Look up the given member of the given non-type-dependent 2952/// expression. This can return in one of two ways: 2953/// * If it returns a sentinel null-but-valid result, the caller will 2954/// assume that lookup was performed and the results written into 2955/// the provided structure. It will take over from there. 2956/// * Otherwise, the returned expression will be produced in place of 2957/// an ordinary member expression. 2958/// 2959/// The ObjCImpDecl bit is a gross hack that will need to be properly 2960/// fixed for ObjC++. 2961ExprResult 2962Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr, 2963 bool &IsArrow, SourceLocation OpLoc, 2964 CXXScopeSpec &SS, 2965 Decl *ObjCImpDecl, bool HasTemplateArgs) { 2966 assert(BaseExpr && "no base expression"); 2967 2968 // Perform default conversions. 2969 DefaultFunctionArrayConversion(BaseExpr); 2970 2971 QualType BaseType = BaseExpr->getType(); 2972 assert(!BaseType->isDependentType()); 2973 2974 DeclarationName MemberName = R.getLookupName(); 2975 SourceLocation MemberLoc = R.getNameLoc(); 2976 2977 // If the user is trying to apply -> or . to a function pointer 2978 // type, it's probably because they forgot parentheses to call that 2979 // function. Suggest the addition of those parentheses, build the 2980 // call, and continue on. 2981 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 2982 if (const FunctionProtoType *Fun 2983 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) { 2984 QualType ResultTy = Fun->getResultType(); 2985 if (Fun->getNumArgs() == 0 && 2986 ((!IsArrow && ResultTy->isRecordType()) || 2987 (IsArrow && ResultTy->isPointerType() && 2988 ResultTy->getAs<PointerType>()->getPointeeType() 2989 ->isRecordType()))) { 2990 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 2991 Diag(Loc, diag::err_member_reference_needs_call) 2992 << QualType(Fun, 0) 2993 << FixItHint::CreateInsertion(Loc, "()"); 2994 2995 ExprResult NewBase 2996 = ActOnCallExpr(0, BaseExpr, Loc, 2997 MultiExprArg(*this, 0, 0), 0, Loc); 2998 BaseExpr = 0; 2999 if (NewBase.isInvalid()) 3000 return ExprError(); 3001 3002 BaseExpr = NewBase.takeAs<Expr>(); 3003 DefaultFunctionArrayConversion(BaseExpr); 3004 BaseType = BaseExpr->getType(); 3005 } 3006 } 3007 } 3008 3009 // If this is an Objective-C pseudo-builtin and a definition is provided then 3010 // use that. 3011 if (BaseType->isObjCIdType()) { 3012 if (IsArrow) { 3013 // Handle the following exceptional case PObj->isa. 3014 if (const ObjCObjectPointerType *OPT = 3015 BaseType->getAs<ObjCObjectPointerType>()) { 3016 if (OPT->getObjectType()->isObjCId() && 3017 MemberName.getAsIdentifierInfo()->isStr("isa")) 3018 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc, 3019 Context.getObjCClassType())); 3020 } 3021 } 3022 // We have an 'id' type. Rather than fall through, we check if this 3023 // is a reference to 'isa'. 3024 if (BaseType != Context.ObjCIdRedefinitionType) { 3025 BaseType = Context.ObjCIdRedefinitionType; 3026 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 3027 } 3028 } 3029 3030 // If this is an Objective-C pseudo-builtin and a definition is provided then 3031 // use that. 3032 if (Context.isObjCSelType(BaseType)) { 3033 // We have an 'SEL' type. Rather than fall through, we check if this 3034 // is a reference to 'sel_id'. 3035 if (BaseType != Context.ObjCSelRedefinitionType) { 3036 BaseType = Context.ObjCSelRedefinitionType; 3037 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 3038 } 3039 } 3040 3041 assert(!BaseType.isNull() && "no type for member expression"); 3042 3043 // Handle properties on ObjC 'Class' types. 3044 if (!IsArrow && BaseType->isObjCClassType()) { 3045 // Also must look for a getter name which uses property syntax. 3046 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3047 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3048 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 3049 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 3050 ObjCMethodDecl *Getter; 3051 // FIXME: need to also look locally in the implementation. 3052 if ((Getter = IFace->lookupClassMethod(Sel))) { 3053 // Check the use of this method. 3054 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 3055 return ExprError(); 3056 } 3057 // If we found a getter then this may be a valid dot-reference, we 3058 // will look for the matching setter, in case it is needed. 3059 Selector SetterSel = 3060 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3061 PP.getSelectorTable(), Member); 3062 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 3063 if (!Setter) { 3064 // If this reference is in an @implementation, also check for 'private' 3065 // methods. 3066 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 3067 } 3068 // Look through local category implementations associated with the class. 3069 if (!Setter) 3070 Setter = IFace->getCategoryClassMethod(SetterSel); 3071 3072 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 3073 return ExprError(); 3074 3075 if (Getter || Setter) { 3076 QualType PType; 3077 3078 if (Getter) 3079 PType = Getter->getSendResultType(); 3080 else 3081 // Get the expression type from Setter's incoming parameter. 3082 PType = (*(Setter->param_end() -1))->getType(); 3083 // FIXME: we must check that the setter has property type. 3084 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, 3085 PType, 3086 Setter, MemberLoc, BaseExpr)); 3087 } 3088 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3089 << MemberName << BaseType); 3090 } 3091 } 3092 3093 if (BaseType->isObjCClassType() && 3094 BaseType != Context.ObjCClassRedefinitionType) { 3095 BaseType = Context.ObjCClassRedefinitionType; 3096 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 3097 } 3098 3099 if (IsArrow) { 3100 if (const PointerType *PT = BaseType->getAs<PointerType>()) 3101 BaseType = PT->getPointeeType(); 3102 else if (BaseType->isObjCObjectPointerType()) 3103 ; 3104 else if (BaseType->isRecordType()) { 3105 // Recover from arrow accesses to records, e.g.: 3106 // struct MyRecord foo; 3107 // foo->bar 3108 // This is actually well-formed in C++ if MyRecord has an 3109 // overloaded operator->, but that should have been dealt with 3110 // by now. 3111 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3112 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 3113 << FixItHint::CreateReplacement(OpLoc, "."); 3114 IsArrow = false; 3115 } else { 3116 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 3117 << BaseType << BaseExpr->getSourceRange(); 3118 return ExprError(); 3119 } 3120 } else { 3121 // Recover from dot accesses to pointers, e.g.: 3122 // type *foo; 3123 // foo.bar 3124 // This is actually well-formed in two cases: 3125 // - 'type' is an Objective C type 3126 // - 'bar' is a pseudo-destructor name which happens to refer to 3127 // the appropriate pointer type 3128 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 3129 const PointerType *PT = BaseType->getAs<PointerType>(); 3130 if (PT && PT->getPointeeType()->isRecordType()) { 3131 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3132 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 3133 << FixItHint::CreateReplacement(OpLoc, "->"); 3134 BaseType = PT->getPointeeType(); 3135 IsArrow = true; 3136 } 3137 } 3138 } 3139 3140 // Handle field access to simple records. 3141 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 3142 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(), 3143 RTy, OpLoc, SS, HasTemplateArgs)) 3144 return ExprError(); 3145 return Owned((Expr*) 0); 3146 } 3147 3148 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 3149 // (*Obj).ivar. 3150 if ((IsArrow && BaseType->isObjCObjectPointerType()) || 3151 (!IsArrow && BaseType->isObjCObjectType())) { 3152 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>(); 3153 ObjCInterfaceDecl *IDecl = 3154 OPT ? OPT->getInterfaceDecl() 3155 : BaseType->getAs<ObjCObjectType>()->getInterface(); 3156 if (IDecl) { 3157 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3158 3159 ObjCInterfaceDecl *ClassDeclared; 3160 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 3161 3162 if (!IV) { 3163 // Attempt to correct for typos in ivar names. 3164 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(), 3165 LookupMemberName); 3166 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) && 3167 (IV = Res.getAsSingle<ObjCIvarDecl>())) { 3168 Diag(R.getNameLoc(), 3169 diag::err_typecheck_member_reference_ivar_suggest) 3170 << IDecl->getDeclName() << MemberName << IV->getDeclName() 3171 << FixItHint::CreateReplacement(R.getNameLoc(), 3172 IV->getNameAsString()); 3173 Diag(IV->getLocation(), diag::note_previous_decl) 3174 << IV->getDeclName(); 3175 } else { 3176 Res.clear(); 3177 Res.setLookupName(Member); 3178 } 3179 } 3180 3181 if (IV) { 3182 // If the decl being referenced had an error, return an error for this 3183 // sub-expr without emitting another error, in order to avoid cascading 3184 // error cases. 3185 if (IV->isInvalidDecl()) 3186 return ExprError(); 3187 3188 // Check whether we can reference this field. 3189 if (DiagnoseUseOfDecl(IV, MemberLoc)) 3190 return ExprError(); 3191 if (IV->getAccessControl() != ObjCIvarDecl::Public && 3192 IV->getAccessControl() != ObjCIvarDecl::Package) { 3193 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 3194 if (ObjCMethodDecl *MD = getCurMethodDecl()) 3195 ClassOfMethodDecl = MD->getClassInterface(); 3196 else if (ObjCImpDecl && getCurFunctionDecl()) { 3197 // Case of a c-function declared inside an objc implementation. 3198 // FIXME: For a c-style function nested inside an objc implementation 3199 // class, there is no implementation context available, so we pass 3200 // down the context as argument to this routine. Ideally, this context 3201 // need be passed down in the AST node and somehow calculated from the 3202 // AST for a function decl. 3203 if (ObjCImplementationDecl *IMPD = 3204 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 3205 ClassOfMethodDecl = IMPD->getClassInterface(); 3206 else if (ObjCCategoryImplDecl* CatImplClass = 3207 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 3208 ClassOfMethodDecl = CatImplClass->getClassInterface(); 3209 } 3210 3211 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 3212 if (ClassDeclared != IDecl || 3213 ClassOfMethodDecl != ClassDeclared) 3214 Diag(MemberLoc, diag::error_private_ivar_access) 3215 << IV->getDeclName(); 3216 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 3217 // @protected 3218 Diag(MemberLoc, diag::error_protected_ivar_access) 3219 << IV->getDeclName(); 3220 } 3221 3222 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 3223 MemberLoc, BaseExpr, 3224 IsArrow)); 3225 } 3226 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 3227 << IDecl->getDeclName() << MemberName 3228 << BaseExpr->getSourceRange()); 3229 } 3230 } 3231 // Handle properties on 'id' and qualified "id". 3232 if (!IsArrow && (BaseType->isObjCIdType() || 3233 BaseType->isObjCQualifiedIdType())) { 3234 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>(); 3235 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3236 3237 // Check protocols on qualified interfaces. 3238 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3239 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { 3240 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 3241 // Check the use of this declaration 3242 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3243 return ExprError(); 3244 3245 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 3246 MemberLoc, BaseExpr)); 3247 } 3248 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 3249 // Check the use of this method. 3250 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 3251 return ExprError(); 3252 3253 return Owned(ObjCMessageExpr::Create(Context, 3254 OMD->getSendResultType(), 3255 OpLoc, BaseExpr, Sel, 3256 OMD, NULL, 0, MemberLoc)); 3257 } 3258 } 3259 3260 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3261 << MemberName << BaseType); 3262 } 3263 3264 // Handle Objective-C property access, which is "Obj.property" where Obj is a 3265 // pointer to a (potentially qualified) interface type. 3266 if (!IsArrow) 3267 if (const ObjCObjectPointerType *OPT = 3268 BaseType->getAsObjCInterfacePointerType()) 3269 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc); 3270 3271 // Handle the following exceptional case (*Obj).isa. 3272 if (!IsArrow && 3273 BaseType->isObjCObjectType() && 3274 BaseType->getAs<ObjCObjectType>()->isObjCId() && 3275 MemberName.getAsIdentifierInfo()->isStr("isa")) 3276 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc, 3277 Context.getObjCClassType())); 3278 3279 // Handle 'field access' to vectors, such as 'V.xx'. 3280 if (BaseType->isExtVectorType()) { 3281 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3282 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 3283 if (ret.isNull()) 3284 return ExprError(); 3285 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member, 3286 MemberLoc)); 3287 } 3288 3289 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 3290 << BaseType << BaseExpr->getSourceRange(); 3291 3292 return ExprError(); 3293} 3294 3295/// The main callback when the parser finds something like 3296/// expression . [nested-name-specifier] identifier 3297/// expression -> [nested-name-specifier] identifier 3298/// where 'identifier' encompasses a fairly broad spectrum of 3299/// possibilities, including destructor and operator references. 3300/// 3301/// \param OpKind either tok::arrow or tok::period 3302/// \param HasTrailingLParen whether the next token is '(', which 3303/// is used to diagnose mis-uses of special members that can 3304/// only be called 3305/// \param ObjCImpDecl the current ObjC @implementation decl; 3306/// this is an ugly hack around the fact that ObjC @implementations 3307/// aren't properly put in the context chain 3308ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 3309 SourceLocation OpLoc, 3310 tok::TokenKind OpKind, 3311 CXXScopeSpec &SS, 3312 UnqualifiedId &Id, 3313 Decl *ObjCImpDecl, 3314 bool HasTrailingLParen) { 3315 if (SS.isSet() && SS.isInvalid()) 3316 return ExprError(); 3317 3318 TemplateArgumentListInfo TemplateArgsBuffer; 3319 3320 // Decompose the name into its component parts. 3321 DeclarationNameInfo NameInfo; 3322 const TemplateArgumentListInfo *TemplateArgs; 3323 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, 3324 NameInfo, TemplateArgs); 3325 3326 DeclarationName Name = NameInfo.getName(); 3327 bool IsArrow = (OpKind == tok::arrow); 3328 3329 NamedDecl *FirstQualifierInScope 3330 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, 3331 static_cast<NestedNameSpecifier*>(SS.getScopeRep()))); 3332 3333 // This is a postfix expression, so get rid of ParenListExprs. 3334 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3335 if (Result.isInvalid()) return ExprError(); 3336 Base = Result.take(); 3337 3338 if (Base->getType()->isDependentType() || Name.isDependentName() || 3339 isDependentScopeSpecifier(SS)) { 3340 Result = ActOnDependentMemberExpr(Base, Base->getType(), 3341 IsArrow, OpLoc, 3342 SS, FirstQualifierInScope, 3343 NameInfo, TemplateArgs); 3344 } else { 3345 LookupResult R(*this, NameInfo, LookupMemberName); 3346 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc, 3347 SS, ObjCImpDecl, TemplateArgs != 0); 3348 3349 if (Result.isInvalid()) { 3350 Owned(Base); 3351 return ExprError(); 3352 } 3353 3354 if (Result.get()) { 3355 // The only way a reference to a destructor can be used is to 3356 // immediately call it, which falls into this case. If the 3357 // next token is not a '(', produce a diagnostic and build the 3358 // call now. 3359 if (!HasTrailingLParen && 3360 Id.getKind() == UnqualifiedId::IK_DestructorName) 3361 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get()); 3362 3363 return move(Result); 3364 } 3365 3366 Result = BuildMemberReferenceExpr(Base, Base->getType(), 3367 OpLoc, IsArrow, SS, FirstQualifierInScope, 3368 R, TemplateArgs); 3369 } 3370 3371 return move(Result); 3372} 3373 3374ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3375 FunctionDecl *FD, 3376 ParmVarDecl *Param) { 3377 if (Param->hasUnparsedDefaultArg()) { 3378 Diag (CallLoc, 3379 diag::err_use_of_default_argument_to_function_declared_later) << 3380 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3381 Diag(UnparsedDefaultArgLocs[Param], 3382 diag::note_default_argument_declared_here); 3383 } else { 3384 if (Param->hasUninstantiatedDefaultArg()) { 3385 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3386 3387 // Instantiate the expression. 3388 MultiLevelTemplateArgumentList ArgList 3389 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3390 3391 std::pair<const TemplateArgument *, unsigned> Innermost 3392 = ArgList.getInnermost(); 3393 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3394 Innermost.second); 3395 3396 ExprResult Result = SubstExpr(UninstExpr, ArgList); 3397 if (Result.isInvalid()) 3398 return ExprError(); 3399 3400 // Check the expression as an initializer for the parameter. 3401 InitializedEntity Entity 3402 = InitializedEntity::InitializeParameter(Param); 3403 InitializationKind Kind 3404 = InitializationKind::CreateCopy(Param->getLocation(), 3405 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3406 Expr *ResultE = Result.takeAs<Expr>(); 3407 3408 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3409 Result = InitSeq.Perform(*this, Entity, Kind, 3410 MultiExprArg(*this, &ResultE, 1)); 3411 if (Result.isInvalid()) 3412 return ExprError(); 3413 3414 // Build the default argument expression. 3415 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3416 Result.takeAs<Expr>())); 3417 } 3418 3419 // If the default expression creates temporaries, we need to 3420 // push them to the current stack of expression temporaries so they'll 3421 // be properly destroyed. 3422 // FIXME: We should really be rebuilding the default argument with new 3423 // bound temporaries; see the comment in PR5810. 3424 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) 3425 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i)); 3426 } 3427 3428 // We already type-checked the argument, so we know it works. 3429 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3430} 3431 3432/// ConvertArgumentsForCall - Converts the arguments specified in 3433/// Args/NumArgs to the parameter types of the function FDecl with 3434/// function prototype Proto. Call is the call expression itself, and 3435/// Fn is the function expression. For a C++ member function, this 3436/// routine does not attempt to convert the object argument. Returns 3437/// true if the call is ill-formed. 3438bool 3439Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3440 FunctionDecl *FDecl, 3441 const FunctionProtoType *Proto, 3442 Expr **Args, unsigned NumArgs, 3443 SourceLocation RParenLoc) { 3444 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3445 // assignment, to the types of the corresponding parameter, ... 3446 unsigned NumArgsInProto = Proto->getNumArgs(); 3447 bool Invalid = false; 3448 3449 // If too few arguments are available (and we don't have default 3450 // arguments for the remaining parameters), don't make the call. 3451 if (NumArgs < NumArgsInProto) { 3452 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 3453 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3454 << Fn->getType()->isBlockPointerType() 3455 << NumArgsInProto << NumArgs << Fn->getSourceRange(); 3456 Call->setNumArgs(Context, NumArgsInProto); 3457 } 3458 3459 // If too many are passed and not variadic, error on the extras and drop 3460 // them. 3461 if (NumArgs > NumArgsInProto) { 3462 if (!Proto->isVariadic()) { 3463 Diag(Args[NumArgsInProto]->getLocStart(), 3464 diag::err_typecheck_call_too_many_args) 3465 << Fn->getType()->isBlockPointerType() 3466 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3467 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3468 Args[NumArgs-1]->getLocEnd()); 3469 // This deletes the extra arguments. 3470 Call->setNumArgs(Context, NumArgsInProto); 3471 return true; 3472 } 3473 } 3474 llvm::SmallVector<Expr *, 8> AllArgs; 3475 VariadicCallType CallType = 3476 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3477 if (Fn->getType()->isBlockPointerType()) 3478 CallType = VariadicBlock; // Block 3479 else if (isa<MemberExpr>(Fn)) 3480 CallType = VariadicMethod; 3481 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3482 Proto, 0, Args, NumArgs, AllArgs, CallType); 3483 if (Invalid) 3484 return true; 3485 unsigned TotalNumArgs = AllArgs.size(); 3486 for (unsigned i = 0; i < TotalNumArgs; ++i) 3487 Call->setArg(i, AllArgs[i]); 3488 3489 return false; 3490} 3491 3492bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3493 FunctionDecl *FDecl, 3494 const FunctionProtoType *Proto, 3495 unsigned FirstProtoArg, 3496 Expr **Args, unsigned NumArgs, 3497 llvm::SmallVector<Expr *, 8> &AllArgs, 3498 VariadicCallType CallType) { 3499 unsigned NumArgsInProto = Proto->getNumArgs(); 3500 unsigned NumArgsToCheck = NumArgs; 3501 bool Invalid = false; 3502 if (NumArgs != NumArgsInProto) 3503 // Use default arguments for missing arguments 3504 NumArgsToCheck = NumArgsInProto; 3505 unsigned ArgIx = 0; 3506 // Continue to check argument types (even if we have too few/many args). 3507 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3508 QualType ProtoArgType = Proto->getArgType(i); 3509 3510 Expr *Arg; 3511 if (ArgIx < NumArgs) { 3512 Arg = Args[ArgIx++]; 3513 3514 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3515 ProtoArgType, 3516 PDiag(diag::err_call_incomplete_argument) 3517 << Arg->getSourceRange())) 3518 return true; 3519 3520 // Pass the argument 3521 ParmVarDecl *Param = 0; 3522 if (FDecl && i < FDecl->getNumParams()) 3523 Param = FDecl->getParamDecl(i); 3524 3525 3526 InitializedEntity Entity = 3527 Param? InitializedEntity::InitializeParameter(Param) 3528 : InitializedEntity::InitializeParameter(ProtoArgType); 3529 ExprResult ArgE = PerformCopyInitialization(Entity, 3530 SourceLocation(), 3531 Owned(Arg)); 3532 if (ArgE.isInvalid()) 3533 return true; 3534 3535 Arg = ArgE.takeAs<Expr>(); 3536 } else { 3537 ParmVarDecl *Param = FDecl->getParamDecl(i); 3538 3539 ExprResult ArgExpr = 3540 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3541 if (ArgExpr.isInvalid()) 3542 return true; 3543 3544 Arg = ArgExpr.takeAs<Expr>(); 3545 } 3546 AllArgs.push_back(Arg); 3547 } 3548 3549 // If this is a variadic call, handle args passed through "...". 3550 if (CallType != VariadicDoesNotApply) { 3551 // Promote the arguments (C99 6.5.2.2p7). 3552 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3553 Expr *Arg = Args[i]; 3554 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl); 3555 AllArgs.push_back(Arg); 3556 } 3557 } 3558 return Invalid; 3559} 3560 3561/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3562/// This provides the location of the left/right parens and a list of comma 3563/// locations. 3564ExprResult 3565Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3566 MultiExprArg args, 3567 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 3568 unsigned NumArgs = args.size(); 3569 3570 // Since this might be a postfix expression, get rid of ParenListExprs. 3571 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3572 if (Result.isInvalid()) return ExprError(); 3573 Fn = Result.take(); 3574 3575 Expr **Args = args.release(); 3576 3577 if (getLangOptions().CPlusPlus) { 3578 // If this is a pseudo-destructor expression, build the call immediately. 3579 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3580 if (NumArgs > 0) { 3581 // Pseudo-destructor calls should not have any arguments. 3582 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3583 << FixItHint::CreateRemoval( 3584 SourceRange(Args[0]->getLocStart(), 3585 Args[NumArgs-1]->getLocEnd())); 3586 3587 NumArgs = 0; 3588 } 3589 3590 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3591 RParenLoc)); 3592 } 3593 3594 // Determine whether this is a dependent call inside a C++ template, 3595 // in which case we won't do any semantic analysis now. 3596 // FIXME: Will need to cache the results of name lookup (including ADL) in 3597 // Fn. 3598 bool Dependent = false; 3599 if (Fn->isTypeDependent()) 3600 Dependent = true; 3601 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 3602 Dependent = true; 3603 3604 if (Dependent) 3605 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3606 Context.DependentTy, RParenLoc)); 3607 3608 // Determine whether this is a call to an object (C++ [over.call.object]). 3609 if (Fn->getType()->isRecordType()) 3610 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3611 CommaLocs, RParenLoc)); 3612 3613 Expr *NakedFn = Fn->IgnoreParens(); 3614 3615 // Determine whether this is a call to an unresolved member function. 3616 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 3617 // If lookup was unresolved but not dependent (i.e. didn't find 3618 // an unresolved using declaration), it has to be an overloaded 3619 // function set, which means it must contain either multiple 3620 // declarations (all methods or method templates) or a single 3621 // method template. 3622 assert((MemE->getNumDecls() > 1) || 3623 isa<FunctionTemplateDecl>( 3624 (*MemE->decls_begin())->getUnderlyingDecl())); 3625 (void)MemE; 3626 3627 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3628 CommaLocs, RParenLoc); 3629 } 3630 3631 // Determine whether this is a call to a member function. 3632 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) { 3633 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 3634 if (isa<CXXMethodDecl>(MemDecl)) 3635 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3636 CommaLocs, RParenLoc); 3637 } 3638 3639 // Determine whether this is a call to a pointer-to-member function. 3640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) { 3641 if (BO->getOpcode() == BinaryOperator::PtrMemD || 3642 BO->getOpcode() == BinaryOperator::PtrMemI) { 3643 if (const FunctionProtoType *FPT 3644 = BO->getType()->getAs<FunctionProtoType>()) { 3645 QualType ResultTy = FPT->getCallResultType(Context); 3646 3647 CXXMemberCallExpr *TheCall 3648 = new (Context) CXXMemberCallExpr(Context, BO, Args, 3649 NumArgs, ResultTy, 3650 RParenLoc); 3651 3652 if (CheckCallReturnType(FPT->getResultType(), 3653 BO->getRHS()->getSourceRange().getBegin(), 3654 TheCall, 0)) 3655 return ExprError(); 3656 3657 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs, 3658 RParenLoc)) 3659 return ExprError(); 3660 3661 return MaybeBindToTemporary(TheCall); 3662 } 3663 return ExprError(Diag(Fn->getLocStart(), 3664 diag::err_typecheck_call_not_function) 3665 << Fn->getType() << Fn->getSourceRange()); 3666 } 3667 } 3668 } 3669 3670 // If we're directly calling a function, get the appropriate declaration. 3671 // Also, in C++, keep track of whether we should perform argument-dependent 3672 // lookup and whether there were any explicitly-specified template arguments. 3673 3674 Expr *NakedFn = Fn->IgnoreParens(); 3675 if (isa<UnresolvedLookupExpr>(NakedFn)) { 3676 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn); 3677 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3678 CommaLocs, RParenLoc); 3679 } 3680 3681 NamedDecl *NDecl = 0; 3682 if (isa<DeclRefExpr>(NakedFn)) 3683 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3684 3685 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc); 3686} 3687 3688/// BuildResolvedCallExpr - Build a call to a resolved expression, 3689/// i.e. an expression not of \p OverloadTy. The expression should 3690/// unary-convert to an expression of function-pointer or 3691/// block-pointer type. 3692/// 3693/// \param NDecl the declaration being called, if available 3694ExprResult 3695Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3696 SourceLocation LParenLoc, 3697 Expr **Args, unsigned NumArgs, 3698 SourceLocation RParenLoc) { 3699 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3700 3701 // Promote the function operand. 3702 UsualUnaryConversions(Fn); 3703 3704 // Make the call expr early, before semantic checks. This guarantees cleanup 3705 // of arguments and function on error. 3706 CallExpr *TheCall = new (Context) CallExpr(Context, Fn, 3707 Args, NumArgs, 3708 Context.BoolTy, 3709 RParenLoc); 3710 3711 const FunctionType *FuncT; 3712 if (!Fn->getType()->isBlockPointerType()) { 3713 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3714 // have type pointer to function". 3715 const PointerType *PT = Fn->getType()->getAs<PointerType>(); 3716 if (PT == 0) 3717 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3718 << Fn->getType() << Fn->getSourceRange()); 3719 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3720 } else { // This is a block call. 3721 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()-> 3722 getAs<FunctionType>(); 3723 } 3724 if (FuncT == 0) 3725 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3726 << Fn->getType() << Fn->getSourceRange()); 3727 3728 // Check for a valid return type 3729 if (CheckCallReturnType(FuncT->getResultType(), 3730 Fn->getSourceRange().getBegin(), TheCall, 3731 FDecl)) 3732 return ExprError(); 3733 3734 // We know the result type of the call, set it. 3735 TheCall->setType(FuncT->getCallResultType(Context)); 3736 3737 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3738 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3739 RParenLoc)) 3740 return ExprError(); 3741 } else { 3742 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3743 3744 if (FDecl) { 3745 // Check if we have too few/too many template arguments, based 3746 // on our knowledge of the function definition. 3747 const FunctionDecl *Def = 0; 3748 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3749 const FunctionProtoType *Proto = 3750 Def->getType()->getAs<FunctionProtoType>(); 3751 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 3752 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3753 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3754 } 3755 } 3756 } 3757 3758 // Promote the arguments (C99 6.5.2.2p6). 3759 for (unsigned i = 0; i != NumArgs; i++) { 3760 Expr *Arg = Args[i]; 3761 DefaultArgumentPromotion(Arg); 3762 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3763 Arg->getType(), 3764 PDiag(diag::err_call_incomplete_argument) 3765 << Arg->getSourceRange())) 3766 return ExprError(); 3767 TheCall->setArg(i, Arg); 3768 } 3769 } 3770 3771 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3772 if (!Method->isStatic()) 3773 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3774 << Fn->getSourceRange()); 3775 3776 // Check for sentinels 3777 if (NDecl) 3778 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3779 3780 // Do special checking on direct calls to functions. 3781 if (FDecl) { 3782 if (CheckFunctionCall(FDecl, TheCall)) 3783 return ExprError(); 3784 3785 if (unsigned BuiltinID = FDecl->getBuiltinID()) 3786 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3787 } else if (NDecl) { 3788 if (CheckBlockCall(NDecl, TheCall)) 3789 return ExprError(); 3790 } 3791 3792 return MaybeBindToTemporary(TheCall); 3793} 3794 3795ExprResult 3796Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3797 SourceLocation RParenLoc, Expr *InitExpr) { 3798 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3799 // FIXME: put back this assert when initializers are worked out. 3800 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3801 3802 TypeSourceInfo *TInfo; 3803 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3804 if (!TInfo) 3805 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3806 3807 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3808} 3809 3810ExprResult 3811Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3812 SourceLocation RParenLoc, Expr *literalExpr) { 3813 QualType literalType = TInfo->getType(); 3814 3815 if (literalType->isArrayType()) { 3816 if (literalType->isVariableArrayType()) 3817 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3818 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3819 } else if (!literalType->isDependentType() && 3820 RequireCompleteType(LParenLoc, literalType, 3821 PDiag(diag::err_typecheck_decl_incomplete_type) 3822 << SourceRange(LParenLoc, 3823 literalExpr->getSourceRange().getEnd()))) 3824 return ExprError(); 3825 3826 InitializedEntity Entity 3827 = InitializedEntity::InitializeTemporary(literalType); 3828 InitializationKind Kind 3829 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc), 3830 /*IsCStyleCast=*/true); 3831 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1); 3832 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3833 MultiExprArg(*this, &literalExpr, 1), 3834 &literalType); 3835 if (Result.isInvalid()) 3836 return ExprError(); 3837 literalExpr = Result.get(); 3838 3839 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3840 if (isFileScope) { // 6.5.2.5p3 3841 if (CheckForConstantInitializer(literalExpr, literalType)) 3842 return ExprError(); 3843 } 3844 3845 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3846 literalExpr, isFileScope)); 3847} 3848 3849ExprResult 3850Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3851 SourceLocation RBraceLoc) { 3852 unsigned NumInit = initlist.size(); 3853 Expr **InitList = initlist.release(); 3854 3855 // Semantic analysis for initializers is done by ActOnDeclarator() and 3856 // CheckInitializer() - it requires knowledge of the object being intialized. 3857 3858 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 3859 NumInit, RBraceLoc); 3860 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3861 return Owned(E); 3862} 3863 3864static CastExpr::CastKind getScalarCastKind(ASTContext &Context, 3865 QualType SrcTy, QualType DestTy) { 3866 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3867 return CastExpr::CK_NoOp; 3868 3869 if (SrcTy->hasPointerRepresentation()) { 3870 if (DestTy->hasPointerRepresentation()) 3871 return DestTy->isObjCObjectPointerType() ? 3872 CastExpr::CK_AnyPointerToObjCPointerCast : 3873 CastExpr::CK_BitCast; 3874 if (DestTy->isIntegerType()) 3875 return CastExpr::CK_PointerToIntegral; 3876 } 3877 3878 if (SrcTy->isIntegerType()) { 3879 if (DestTy->isIntegerType()) 3880 return CastExpr::CK_IntegralCast; 3881 if (DestTy->hasPointerRepresentation()) 3882 return CastExpr::CK_IntegralToPointer; 3883 if (DestTy->isRealFloatingType()) 3884 return CastExpr::CK_IntegralToFloating; 3885 } 3886 3887 if (SrcTy->isRealFloatingType()) { 3888 if (DestTy->isRealFloatingType()) 3889 return CastExpr::CK_FloatingCast; 3890 if (DestTy->isIntegerType()) 3891 return CastExpr::CK_FloatingToIntegral; 3892 } 3893 3894 // FIXME: Assert here. 3895 // assert(false && "Unhandled cast combination!"); 3896 return CastExpr::CK_Unknown; 3897} 3898 3899/// CheckCastTypes - Check type constraints for casting between types. 3900bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr, 3901 CastExpr::CastKind& Kind, 3902 CXXCastPath &BasePath, 3903 bool FunctionalStyle) { 3904 if (getLangOptions().CPlusPlus) 3905 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath, 3906 FunctionalStyle); 3907 3908 DefaultFunctionArrayLvalueConversion(castExpr); 3909 3910 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3911 // type needs to be scalar. 3912 if (castType->isVoidType()) { 3913 // Cast to void allows any expr type. 3914 Kind = CastExpr::CK_ToVoid; 3915 return false; 3916 } 3917 3918 if (RequireCompleteType(TyR.getBegin(), castType, 3919 diag::err_typecheck_cast_to_incomplete)) 3920 return true; 3921 3922 if (!castType->isScalarType() && !castType->isVectorType()) { 3923 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 3924 (castType->isStructureType() || castType->isUnionType())) { 3925 // GCC struct/union extension: allow cast to self. 3926 // FIXME: Check that the cast destination type is complete. 3927 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3928 << castType << castExpr->getSourceRange(); 3929 Kind = CastExpr::CK_NoOp; 3930 return false; 3931 } 3932 3933 if (castType->isUnionType()) { 3934 // GCC cast to union extension 3935 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 3936 RecordDecl::field_iterator Field, FieldEnd; 3937 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 3938 Field != FieldEnd; ++Field) { 3939 if (Context.hasSameUnqualifiedType(Field->getType(), 3940 castExpr->getType())) { 3941 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 3942 << castExpr->getSourceRange(); 3943 break; 3944 } 3945 } 3946 if (Field == FieldEnd) 3947 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 3948 << castExpr->getType() << castExpr->getSourceRange(); 3949 Kind = CastExpr::CK_ToUnion; 3950 return false; 3951 } 3952 3953 // Reject any other conversions to non-scalar types. 3954 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 3955 << castType << castExpr->getSourceRange(); 3956 } 3957 3958 if (!castExpr->getType()->isScalarType() && 3959 !castExpr->getType()->isVectorType()) { 3960 return Diag(castExpr->getLocStart(), 3961 diag::err_typecheck_expect_scalar_operand) 3962 << castExpr->getType() << castExpr->getSourceRange(); 3963 } 3964 3965 if (castType->isExtVectorType()) 3966 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 3967 3968 if (castType->isVectorType()) 3969 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind); 3970 if (castExpr->getType()->isVectorType()) 3971 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind); 3972 3973 if (isa<ObjCSelectorExpr>(castExpr)) 3974 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 3975 3976 if (!castType->isArithmeticType()) { 3977 QualType castExprType = castExpr->getType(); 3978 if (!castExprType->isIntegralType(Context) && 3979 castExprType->isArithmeticType()) 3980 return Diag(castExpr->getLocStart(), 3981 diag::err_cast_pointer_from_non_pointer_int) 3982 << castExprType << castExpr->getSourceRange(); 3983 } else if (!castExpr->getType()->isArithmeticType()) { 3984 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) 3985 return Diag(castExpr->getLocStart(), 3986 diag::err_cast_pointer_to_non_pointer_int) 3987 << castType << castExpr->getSourceRange(); 3988 } 3989 3990 Kind = getScalarCastKind(Context, castExpr->getType(), castType); 3991 3992 if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast) 3993 CheckCastAlign(castExpr, castType, TyR); 3994 3995 return false; 3996} 3997 3998bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 3999 CastExpr::CastKind &Kind) { 4000 assert(VectorTy->isVectorType() && "Not a vector type!"); 4001 4002 if (Ty->isVectorType() || Ty->isIntegerType()) { 4003 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4004 return Diag(R.getBegin(), 4005 Ty->isVectorType() ? 4006 diag::err_invalid_conversion_between_vectors : 4007 diag::err_invalid_conversion_between_vector_and_integer) 4008 << VectorTy << Ty << R; 4009 } else 4010 return Diag(R.getBegin(), 4011 diag::err_invalid_conversion_between_vector_and_scalar) 4012 << VectorTy << Ty << R; 4013 4014 Kind = CastExpr::CK_BitCast; 4015 return false; 4016} 4017 4018bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 4019 CastExpr::CastKind &Kind) { 4020 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4021 4022 QualType SrcTy = CastExpr->getType(); 4023 4024 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4025 // an ExtVectorType. 4026 if (SrcTy->isVectorType()) { 4027 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 4028 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4029 << DestTy << SrcTy << R; 4030 Kind = CastExpr::CK_BitCast; 4031 return false; 4032 } 4033 4034 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4035 // conversion will take place first from scalar to elt type, and then 4036 // splat from elt type to vector. 4037 if (SrcTy->isPointerType()) 4038 return Diag(R.getBegin(), 4039 diag::err_invalid_conversion_between_vector_and_scalar) 4040 << DestTy << SrcTy << R; 4041 4042 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4043 ImpCastExprToType(CastExpr, DestElemTy, 4044 getScalarCastKind(Context, SrcTy, DestElemTy)); 4045 4046 Kind = CastExpr::CK_VectorSplat; 4047 return false; 4048} 4049 4050ExprResult 4051Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty, 4052 SourceLocation RParenLoc, Expr *castExpr) { 4053 assert((Ty != 0) && (castExpr != 0) && 4054 "ActOnCastExpr(): missing type or expr"); 4055 4056 TypeSourceInfo *castTInfo; 4057 QualType castType = GetTypeFromParser(Ty, &castTInfo); 4058 if (!castTInfo) 4059 castTInfo = Context.getTrivialTypeSourceInfo(castType); 4060 4061 // If the Expr being casted is a ParenListExpr, handle it specially. 4062 if (isa<ParenListExpr>(castExpr)) 4063 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr, 4064 castTInfo); 4065 4066 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr); 4067} 4068 4069ExprResult 4070Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 4071 SourceLocation RParenLoc, Expr *castExpr) { 4072 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 4073 CXXCastPath BasePath; 4074 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr, 4075 Kind, BasePath)) 4076 return ExprError(); 4077 4078 return Owned(CStyleCastExpr::Create(Context, 4079 Ty->getType().getNonLValueExprType(Context), 4080 Kind, castExpr, &BasePath, Ty, 4081 LParenLoc, RParenLoc)); 4082} 4083 4084/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 4085/// of comma binary operators. 4086ExprResult 4087Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) { 4088 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 4089 if (!E) 4090 return Owned(expr); 4091 4092 ExprResult Result(E->getExpr(0)); 4093 4094 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4095 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4096 E->getExpr(i)); 4097 4098 if (Result.isInvalid()) return ExprError(); 4099 4100 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4101} 4102 4103ExprResult 4104Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 4105 SourceLocation RParenLoc, Expr *Op, 4106 TypeSourceInfo *TInfo) { 4107 ParenListExpr *PE = cast<ParenListExpr>(Op); 4108 QualType Ty = TInfo->getType(); 4109 bool isAltiVecLiteral = false; 4110 4111 // Check for an altivec literal, 4112 // i.e. all the elements are integer constants. 4113 if (getLangOptions().AltiVec && Ty->isVectorType()) { 4114 if (PE->getNumExprs() == 0) { 4115 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 4116 return ExprError(); 4117 } 4118 if (PE->getNumExprs() == 1) { 4119 if (!PE->getExpr(0)->getType()->isVectorType()) 4120 isAltiVecLiteral = true; 4121 } 4122 else 4123 isAltiVecLiteral = true; 4124 } 4125 4126 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 4127 // then handle it as such. 4128 if (isAltiVecLiteral) { 4129 llvm::SmallVector<Expr *, 8> initExprs; 4130 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 4131 initExprs.push_back(PE->getExpr(i)); 4132 4133 // FIXME: This means that pretty-printing the final AST will produce curly 4134 // braces instead of the original commas. 4135 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc, 4136 &initExprs[0], 4137 initExprs.size(), RParenLoc); 4138 E->setType(Ty); 4139 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E); 4140 } else { 4141 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4142 // sequence of BinOp comma operators. 4143 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op); 4144 if (Result.isInvalid()) return ExprError(); 4145 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take()); 4146 } 4147} 4148 4149ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 4150 SourceLocation R, 4151 MultiExprArg Val, 4152 ParsedType TypeOfCast) { 4153 unsigned nexprs = Val.size(); 4154 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4155 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4156 Expr *expr; 4157 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast)) 4158 expr = new (Context) ParenExpr(L, R, exprs[0]); 4159 else 4160 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4161 return Owned(expr); 4162} 4163 4164/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 4165/// In that case, lhs = cond. 4166/// C99 6.5.15 4167QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 4168 SourceLocation QuestionLoc) { 4169 // C++ is sufficiently different to merit its own checker. 4170 if (getLangOptions().CPlusPlus) 4171 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc); 4172 4173 UsualUnaryConversions(Cond); 4174 UsualUnaryConversions(LHS); 4175 UsualUnaryConversions(RHS); 4176 QualType CondTy = Cond->getType(); 4177 QualType LHSTy = LHS->getType(); 4178 QualType RHSTy = RHS->getType(); 4179 4180 // first, check the condition. 4181 if (!CondTy->isScalarType()) { // C99 6.5.15p2 4182 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4183 << CondTy; 4184 return QualType(); 4185 } 4186 4187 // Now check the two expressions. 4188 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4189 return CheckVectorOperands(QuestionLoc, LHS, RHS); 4190 4191 // If both operands have arithmetic type, do the usual arithmetic conversions 4192 // to find a common type: C99 6.5.15p3,5. 4193 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4194 UsualArithmeticConversions(LHS, RHS); 4195 return LHS->getType(); 4196 } 4197 4198 // If both operands are the same structure or union type, the result is that 4199 // type. 4200 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4201 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4202 if (LHSRT->getDecl() == RHSRT->getDecl()) 4203 // "If both the operands have structure or union type, the result has 4204 // that type." This implies that CV qualifiers are dropped. 4205 return LHSTy.getUnqualifiedType(); 4206 // FIXME: Type of conditional expression must be complete in C mode. 4207 } 4208 4209 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4210 // The following || allows only one side to be void (a GCC-ism). 4211 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4212 if (!LHSTy->isVoidType()) 4213 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4214 << RHS->getSourceRange(); 4215 if (!RHSTy->isVoidType()) 4216 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4217 << LHS->getSourceRange(); 4218 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid); 4219 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid); 4220 return Context.VoidTy; 4221 } 4222 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4223 // the type of the other operand." 4224 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 4225 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4226 // promote the null to a pointer. 4227 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown); 4228 return LHSTy; 4229 } 4230 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 4231 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4232 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown); 4233 return RHSTy; 4234 } 4235 4236 // All objective-c pointer type analysis is done here. 4237 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4238 QuestionLoc); 4239 if (!compositeType.isNull()) 4240 return compositeType; 4241 4242 4243 // Handle block pointer types. 4244 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 4245 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4246 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4247 QualType destType = Context.getPointerType(Context.VoidTy); 4248 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4249 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4250 return destType; 4251 } 4252 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4253 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4254 return QualType(); 4255 } 4256 // We have 2 block pointer types. 4257 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4258 // Two identical block pointer types are always compatible. 4259 return LHSTy; 4260 } 4261 // The block pointer types aren't identical, continue checking. 4262 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 4263 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 4264 4265 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4266 rhptee.getUnqualifiedType())) { 4267 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4268 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4269 // In this situation, we assume void* type. No especially good 4270 // reason, but this is what gcc does, and we do have to pick 4271 // to get a consistent AST. 4272 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4273 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4274 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4275 return incompatTy; 4276 } 4277 // The block pointer types are compatible. 4278 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 4279 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4280 return LHSTy; 4281 } 4282 4283 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4284 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 4285 // get the "pointed to" types 4286 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4287 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4288 4289 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4290 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4291 // Figure out necessary qualifiers (C99 6.5.15p6) 4292 QualType destPointee 4293 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4294 QualType destType = Context.getPointerType(destPointee); 4295 // Add qualifiers if necessary. 4296 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 4297 // Promote to void*. 4298 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4299 return destType; 4300 } 4301 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4302 QualType destPointee 4303 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4304 QualType destType = Context.getPointerType(destPointee); 4305 // Add qualifiers if necessary. 4306 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 4307 // Promote to void*. 4308 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4309 return destType; 4310 } 4311 4312 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4313 // Two identical pointer types are always compatible. 4314 return LHSTy; 4315 } 4316 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4317 rhptee.getUnqualifiedType())) { 4318 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4319 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4320 // In this situation, we assume void* type. No especially good 4321 // reason, but this is what gcc does, and we do have to pick 4322 // to get a consistent AST. 4323 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4324 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4325 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4326 return incompatTy; 4327 } 4328 // The pointer types are compatible. 4329 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4330 // differently qualified versions of compatible types, the result type is 4331 // a pointer to an appropriately qualified version of the *composite* 4332 // type. 4333 // FIXME: Need to calculate the composite type. 4334 // FIXME: Need to add qualifiers 4335 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 4336 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4337 return LHSTy; 4338 } 4339 4340 // GCC compatibility: soften pointer/integer mismatch. 4341 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 4342 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4343 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4344 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer); 4345 return RHSTy; 4346 } 4347 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 4348 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4349 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4350 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer); 4351 return LHSTy; 4352 } 4353 4354 // Otherwise, the operands are not compatible. 4355 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4356 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4357 return QualType(); 4358} 4359 4360/// FindCompositeObjCPointerType - Helper method to find composite type of 4361/// two objective-c pointer types of the two input expressions. 4362QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS, 4363 SourceLocation QuestionLoc) { 4364 QualType LHSTy = LHS->getType(); 4365 QualType RHSTy = RHS->getType(); 4366 4367 // Handle things like Class and struct objc_class*. Here we case the result 4368 // to the pseudo-builtin, because that will be implicitly cast back to the 4369 // redefinition type if an attempt is made to access its fields. 4370 if (LHSTy->isObjCClassType() && 4371 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4372 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4373 return LHSTy; 4374 } 4375 if (RHSTy->isObjCClassType() && 4376 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4377 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4378 return RHSTy; 4379 } 4380 // And the same for struct objc_object* / id 4381 if (LHSTy->isObjCIdType() && 4382 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4383 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4384 return LHSTy; 4385 } 4386 if (RHSTy->isObjCIdType() && 4387 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4388 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4389 return RHSTy; 4390 } 4391 // And the same for struct objc_selector* / SEL 4392 if (Context.isObjCSelType(LHSTy) && 4393 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4394 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 4395 return LHSTy; 4396 } 4397 if (Context.isObjCSelType(RHSTy) && 4398 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4399 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 4400 return RHSTy; 4401 } 4402 // Check constraints for Objective-C object pointers types. 4403 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4404 4405 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4406 // Two identical object pointer types are always compatible. 4407 return LHSTy; 4408 } 4409 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 4410 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 4411 QualType compositeType = LHSTy; 4412 4413 // If both operands are interfaces and either operand can be 4414 // assigned to the other, use that type as the composite 4415 // type. This allows 4416 // xxx ? (A*) a : (B*) b 4417 // where B is a subclass of A. 4418 // 4419 // Additionally, as for assignment, if either type is 'id' 4420 // allow silent coercion. Finally, if the types are 4421 // incompatible then make sure to use 'id' as the composite 4422 // type so the result is acceptable for sending messages to. 4423 4424 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4425 // It could return the composite type. 4426 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4427 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4428 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4429 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4430 } else if ((LHSTy->isObjCQualifiedIdType() || 4431 RHSTy->isObjCQualifiedIdType()) && 4432 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4433 // Need to handle "id<xx>" explicitly. 4434 // GCC allows qualified id and any Objective-C type to devolve to 4435 // id. Currently localizing to here until clear this should be 4436 // part of ObjCQualifiedIdTypesAreCompatible. 4437 compositeType = Context.getObjCIdType(); 4438 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4439 compositeType = Context.getObjCIdType(); 4440 } else if (!(compositeType = 4441 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4442 ; 4443 else { 4444 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4445 << LHSTy << RHSTy 4446 << LHS->getSourceRange() << RHS->getSourceRange(); 4447 QualType incompatTy = Context.getObjCIdType(); 4448 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 4449 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 4450 return incompatTy; 4451 } 4452 // The object pointer types are compatible. 4453 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast); 4454 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast); 4455 return compositeType; 4456 } 4457 // Check Objective-C object pointer types and 'void *' 4458 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4459 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4460 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4461 QualType destPointee 4462 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4463 QualType destType = Context.getPointerType(destPointee); 4464 // Add qualifiers if necessary. 4465 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 4466 // Promote to void*. 4467 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 4468 return destType; 4469 } 4470 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4471 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4472 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4473 QualType destPointee 4474 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4475 QualType destType = Context.getPointerType(destPointee); 4476 // Add qualifiers if necessary. 4477 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 4478 // Promote to void*. 4479 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 4480 return destType; 4481 } 4482 return QualType(); 4483} 4484 4485/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 4486/// in the case of a the GNU conditional expr extension. 4487ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 4488 SourceLocation ColonLoc, 4489 Expr *CondExpr, Expr *LHSExpr, 4490 Expr *RHSExpr) { 4491 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 4492 // was the condition. 4493 bool isLHSNull = LHSExpr == 0; 4494 if (isLHSNull) 4495 LHSExpr = CondExpr; 4496 4497 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 4498 RHSExpr, QuestionLoc); 4499 if (result.isNull()) 4500 return ExprError(); 4501 4502 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 4503 isLHSNull ? 0 : LHSExpr, 4504 ColonLoc, RHSExpr, result)); 4505} 4506 4507// CheckPointerTypesForAssignment - This is a very tricky routine (despite 4508// being closely modeled after the C99 spec:-). The odd characteristic of this 4509// routine is it effectively iqnores the qualifiers on the top level pointee. 4510// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 4511// FIXME: add a couple examples in this comment. 4512Sema::AssignConvertType 4513Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4514 QualType lhptee, rhptee; 4515 4516 if ((lhsType->isObjCClassType() && 4517 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4518 (rhsType->isObjCClassType() && 4519 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4520 return Compatible; 4521 } 4522 4523 // get the "pointed to" type (ignoring qualifiers at the top level) 4524 lhptee = lhsType->getAs<PointerType>()->getPointeeType(); 4525 rhptee = rhsType->getAs<PointerType>()->getPointeeType(); 4526 4527 // make sure we operate on the canonical type 4528 lhptee = Context.getCanonicalType(lhptee); 4529 rhptee = Context.getCanonicalType(rhptee); 4530 4531 AssignConvertType ConvTy = Compatible; 4532 4533 // C99 6.5.16.1p1: This following citation is common to constraints 4534 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 4535 // qualifiers of the type *pointed to* by the right; 4536 // FIXME: Handle ExtQualType 4537 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4538 ConvTy = CompatiblePointerDiscardsQualifiers; 4539 4540 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 4541 // incomplete type and the other is a pointer to a qualified or unqualified 4542 // version of void... 4543 if (lhptee->isVoidType()) { 4544 if (rhptee->isIncompleteOrObjectType()) 4545 return ConvTy; 4546 4547 // As an extension, we allow cast to/from void* to function pointer. 4548 assert(rhptee->isFunctionType()); 4549 return FunctionVoidPointer; 4550 } 4551 4552 if (rhptee->isVoidType()) { 4553 if (lhptee->isIncompleteOrObjectType()) 4554 return ConvTy; 4555 4556 // As an extension, we allow cast to/from void* to function pointer. 4557 assert(lhptee->isFunctionType()); 4558 return FunctionVoidPointer; 4559 } 4560 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 4561 // unqualified versions of compatible types, ... 4562 lhptee = lhptee.getUnqualifiedType(); 4563 rhptee = rhptee.getUnqualifiedType(); 4564 if (!Context.typesAreCompatible(lhptee, rhptee)) { 4565 // Check if the pointee types are compatible ignoring the sign. 4566 // We explicitly check for char so that we catch "char" vs 4567 // "unsigned char" on systems where "char" is unsigned. 4568 if (lhptee->isCharType()) 4569 lhptee = Context.UnsignedCharTy; 4570 else if (lhptee->hasSignedIntegerRepresentation()) 4571 lhptee = Context.getCorrespondingUnsignedType(lhptee); 4572 4573 if (rhptee->isCharType()) 4574 rhptee = Context.UnsignedCharTy; 4575 else if (rhptee->hasSignedIntegerRepresentation()) 4576 rhptee = Context.getCorrespondingUnsignedType(rhptee); 4577 4578 if (lhptee == rhptee) { 4579 // Types are compatible ignoring the sign. Qualifier incompatibility 4580 // takes priority over sign incompatibility because the sign 4581 // warning can be disabled. 4582 if (ConvTy != Compatible) 4583 return ConvTy; 4584 return IncompatiblePointerSign; 4585 } 4586 4587 // If we are a multi-level pointer, it's possible that our issue is simply 4588 // one of qualification - e.g. char ** -> const char ** is not allowed. If 4589 // the eventual target type is the same and the pointers have the same 4590 // level of indirection, this must be the issue. 4591 if (lhptee->isPointerType() && rhptee->isPointerType()) { 4592 do { 4593 lhptee = lhptee->getAs<PointerType>()->getPointeeType(); 4594 rhptee = rhptee->getAs<PointerType>()->getPointeeType(); 4595 4596 lhptee = Context.getCanonicalType(lhptee); 4597 rhptee = Context.getCanonicalType(rhptee); 4598 } while (lhptee->isPointerType() && rhptee->isPointerType()); 4599 4600 if (Context.hasSameUnqualifiedType(lhptee, rhptee)) 4601 return IncompatibleNestedPointerQualifiers; 4602 } 4603 4604 // General pointer incompatibility takes priority over qualifiers. 4605 return IncompatiblePointer; 4606 } 4607 return ConvTy; 4608} 4609 4610/// CheckBlockPointerTypesForAssignment - This routine determines whether two 4611/// block pointer types are compatible or whether a block and normal pointer 4612/// are compatible. It is more restrict than comparing two function pointer 4613// types. 4614Sema::AssignConvertType 4615Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 4616 QualType rhsType) { 4617 QualType lhptee, rhptee; 4618 4619 // get the "pointed to" type (ignoring qualifiers at the top level) 4620 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType(); 4621 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType(); 4622 4623 // make sure we operate on the canonical type 4624 lhptee = Context.getCanonicalType(lhptee); 4625 rhptee = Context.getCanonicalType(rhptee); 4626 4627 AssignConvertType ConvTy = Compatible; 4628 4629 // For blocks we enforce that qualifiers are identical. 4630 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers()) 4631 ConvTy = CompatiblePointerDiscardsQualifiers; 4632 4633 if (!getLangOptions().CPlusPlus) { 4634 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType)) 4635 return IncompatibleBlockPointer; 4636 } 4637 else if (!Context.typesAreCompatible(lhptee, rhptee)) 4638 return IncompatibleBlockPointer; 4639 return ConvTy; 4640} 4641 4642/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types 4643/// for assignment compatibility. 4644Sema::AssignConvertType 4645Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4646 if (lhsType->isObjCBuiltinType()) { 4647 // Class is not compatible with ObjC object pointers. 4648 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() && 4649 !rhsType->isObjCQualifiedClassType()) 4650 return IncompatiblePointer; 4651 return Compatible; 4652 } 4653 if (rhsType->isObjCBuiltinType()) { 4654 // Class is not compatible with ObjC object pointers. 4655 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() && 4656 !lhsType->isObjCQualifiedClassType()) 4657 return IncompatiblePointer; 4658 return Compatible; 4659 } 4660 QualType lhptee = 4661 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4662 QualType rhptee = 4663 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4664 // make sure we operate on the canonical type 4665 lhptee = Context.getCanonicalType(lhptee); 4666 rhptee = Context.getCanonicalType(rhptee); 4667 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4668 return CompatiblePointerDiscardsQualifiers; 4669 4670 if (Context.typesAreCompatible(lhsType, rhsType)) 4671 return Compatible; 4672 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 4673 return IncompatibleObjCQualifiedId; 4674 return IncompatiblePointer; 4675} 4676 4677/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 4678/// has code to accommodate several GCC extensions when type checking 4679/// pointers. Here are some objectionable examples that GCC considers warnings: 4680/// 4681/// int a, *pint; 4682/// short *pshort; 4683/// struct foo *pfoo; 4684/// 4685/// pint = pshort; // warning: assignment from incompatible pointer type 4686/// a = pint; // warning: assignment makes integer from pointer without a cast 4687/// pint = a; // warning: assignment makes pointer from integer without a cast 4688/// pint = pfoo; // warning: assignment from incompatible pointer type 4689/// 4690/// As a result, the code for dealing with pointers is more complex than the 4691/// C99 spec dictates. 4692/// 4693Sema::AssignConvertType 4694Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 4695 // Get canonical types. We're not formatting these types, just comparing 4696 // them. 4697 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 4698 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 4699 4700 if (lhsType == rhsType) 4701 return Compatible; // Common case: fast path an exact match. 4702 4703 if ((lhsType->isObjCClassType() && 4704 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4705 (rhsType->isObjCClassType() && 4706 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4707 return Compatible; 4708 } 4709 4710 // If the left-hand side is a reference type, then we are in a 4711 // (rare!) case where we've allowed the use of references in C, 4712 // e.g., as a parameter type in a built-in function. In this case, 4713 // just make sure that the type referenced is compatible with the 4714 // right-hand side type. The caller is responsible for adjusting 4715 // lhsType so that the resulting expression does not have reference 4716 // type. 4717 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 4718 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 4719 return Compatible; 4720 return Incompatible; 4721 } 4722 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 4723 // to the same ExtVector type. 4724 if (lhsType->isExtVectorType()) { 4725 if (rhsType->isExtVectorType()) 4726 return lhsType == rhsType ? Compatible : Incompatible; 4727 if (rhsType->isArithmeticType()) 4728 return Compatible; 4729 } 4730 4731 if (lhsType->isVectorType() || rhsType->isVectorType()) { 4732 if (lhsType->isVectorType() && rhsType->isVectorType()) { 4733 // If we are allowing lax vector conversions, and LHS and RHS are both 4734 // vectors, the total size only needs to be the same. This is a bitcast; 4735 // no bits are changed but the result type is different. 4736 if (getLangOptions().LaxVectorConversions && 4737 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) 4738 return IncompatibleVectors; 4739 4740 // Allow assignments of an AltiVec vector type to an equivalent GCC 4741 // vector type and vice versa 4742 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) 4743 return Compatible; 4744 } 4745 return Incompatible; 4746 } 4747 4748 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() && 4749 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) 4750 return Compatible; 4751 4752 if (isa<PointerType>(lhsType)) { 4753 if (rhsType->isIntegerType()) 4754 return IntToPointer; 4755 4756 if (isa<PointerType>(rhsType)) 4757 return CheckPointerTypesForAssignment(lhsType, rhsType); 4758 4759 // In general, C pointers are not compatible with ObjC object pointers. 4760 if (isa<ObjCObjectPointerType>(rhsType)) { 4761 if (lhsType->isVoidPointerType()) // an exception to the rule. 4762 return Compatible; 4763 return IncompatiblePointer; 4764 } 4765 if (rhsType->getAs<BlockPointerType>()) { 4766 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4767 return Compatible; 4768 4769 // Treat block pointers as objects. 4770 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) 4771 return Compatible; 4772 } 4773 return Incompatible; 4774 } 4775 4776 if (isa<BlockPointerType>(lhsType)) { 4777 if (rhsType->isIntegerType()) 4778 return IntToBlockPointer; 4779 4780 // Treat block pointers as objects. 4781 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) 4782 return Compatible; 4783 4784 if (rhsType->isBlockPointerType()) 4785 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 4786 4787 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4788 if (RHSPT->getPointeeType()->isVoidType()) 4789 return Compatible; 4790 } 4791 return Incompatible; 4792 } 4793 4794 if (isa<ObjCObjectPointerType>(lhsType)) { 4795 if (rhsType->isIntegerType()) 4796 return IntToPointer; 4797 4798 // In general, C pointers are not compatible with ObjC object pointers. 4799 if (isa<PointerType>(rhsType)) { 4800 if (rhsType->isVoidPointerType()) // an exception to the rule. 4801 return Compatible; 4802 return IncompatiblePointer; 4803 } 4804 if (rhsType->isObjCObjectPointerType()) { 4805 return CheckObjCPointerTypesForAssignment(lhsType, rhsType); 4806 } 4807 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4808 if (RHSPT->getPointeeType()->isVoidType()) 4809 return Compatible; 4810 } 4811 // Treat block pointers as objects. 4812 if (rhsType->isBlockPointerType()) 4813 return Compatible; 4814 return Incompatible; 4815 } 4816 if (isa<PointerType>(rhsType)) { 4817 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4818 if (lhsType == Context.BoolTy) 4819 return Compatible; 4820 4821 if (lhsType->isIntegerType()) 4822 return PointerToInt; 4823 4824 if (isa<PointerType>(lhsType)) 4825 return CheckPointerTypesForAssignment(lhsType, rhsType); 4826 4827 if (isa<BlockPointerType>(lhsType) && 4828 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4829 return Compatible; 4830 return Incompatible; 4831 } 4832 if (isa<ObjCObjectPointerType>(rhsType)) { 4833 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4834 if (lhsType == Context.BoolTy) 4835 return Compatible; 4836 4837 if (lhsType->isIntegerType()) 4838 return PointerToInt; 4839 4840 // In general, C pointers are not compatible with ObjC object pointers. 4841 if (isa<PointerType>(lhsType)) { 4842 if (lhsType->isVoidPointerType()) // an exception to the rule. 4843 return Compatible; 4844 return IncompatiblePointer; 4845 } 4846 if (isa<BlockPointerType>(lhsType) && 4847 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4848 return Compatible; 4849 return Incompatible; 4850 } 4851 4852 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 4853 if (Context.typesAreCompatible(lhsType, rhsType)) 4854 return Compatible; 4855 } 4856 return Incompatible; 4857} 4858 4859/// \brief Constructs a transparent union from an expression that is 4860/// used to initialize the transparent union. 4861static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 4862 QualType UnionType, FieldDecl *Field) { 4863 // Build an initializer list that designates the appropriate member 4864 // of the transparent union. 4865 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 4866 &E, 1, 4867 SourceLocation()); 4868 Initializer->setType(UnionType); 4869 Initializer->setInitializedFieldInUnion(Field); 4870 4871 // Build a compound literal constructing a value of the transparent 4872 // union type from this initializer list. 4873 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 4874 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 4875 Initializer, false); 4876} 4877 4878Sema::AssignConvertType 4879Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 4880 QualType FromType = rExpr->getType(); 4881 4882 // If the ArgType is a Union type, we want to handle a potential 4883 // transparent_union GCC extension. 4884 const RecordType *UT = ArgType->getAsUnionType(); 4885 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4886 return Incompatible; 4887 4888 // The field to initialize within the transparent union. 4889 RecordDecl *UD = UT->getDecl(); 4890 FieldDecl *InitField = 0; 4891 // It's compatible if the expression matches any of the fields. 4892 for (RecordDecl::field_iterator it = UD->field_begin(), 4893 itend = UD->field_end(); 4894 it != itend; ++it) { 4895 if (it->getType()->isPointerType()) { 4896 // If the transparent union contains a pointer type, we allow: 4897 // 1) void pointer 4898 // 2) null pointer constant 4899 if (FromType->isPointerType()) 4900 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 4901 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast); 4902 InitField = *it; 4903 break; 4904 } 4905 4906 if (rExpr->isNullPointerConstant(Context, 4907 Expr::NPC_ValueDependentIsNull)) { 4908 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer); 4909 InitField = *it; 4910 break; 4911 } 4912 } 4913 4914 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 4915 == Compatible) { 4916 InitField = *it; 4917 break; 4918 } 4919 } 4920 4921 if (!InitField) 4922 return Incompatible; 4923 4924 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 4925 return Compatible; 4926} 4927 4928Sema::AssignConvertType 4929Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 4930 if (getLangOptions().CPlusPlus) { 4931 if (!lhsType->isRecordType()) { 4932 // C++ 5.17p3: If the left operand is not of class type, the 4933 // expression is implicitly converted (C++ 4) to the 4934 // cv-unqualified type of the left operand. 4935 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 4936 AA_Assigning)) 4937 return Incompatible; 4938 return Compatible; 4939 } 4940 4941 // FIXME: Currently, we fall through and treat C++ classes like C 4942 // structures. 4943 } 4944 4945 // C99 6.5.16.1p1: the left operand is a pointer and the right is 4946 // a null pointer constant. 4947 if ((lhsType->isPointerType() || 4948 lhsType->isObjCObjectPointerType() || 4949 lhsType->isBlockPointerType()) 4950 && rExpr->isNullPointerConstant(Context, 4951 Expr::NPC_ValueDependentIsNull)) { 4952 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown); 4953 return Compatible; 4954 } 4955 4956 // This check seems unnatural, however it is necessary to ensure the proper 4957 // conversion of functions/arrays. If the conversion were done for all 4958 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 4959 // expressions that suppress this implicit conversion (&, sizeof). 4960 // 4961 // Suppress this for references: C++ 8.5.3p5. 4962 if (!lhsType->isReferenceType()) 4963 DefaultFunctionArrayLvalueConversion(rExpr); 4964 4965 Sema::AssignConvertType result = 4966 CheckAssignmentConstraints(lhsType, rExpr->getType()); 4967 4968 // C99 6.5.16.1p2: The value of the right operand is converted to the 4969 // type of the assignment expression. 4970 // CheckAssignmentConstraints allows the left-hand side to be a reference, 4971 // so that we can use references in built-in functions even in C. 4972 // The getNonReferenceType() call makes sure that the resulting expression 4973 // does not have reference type. 4974 if (result != Incompatible && rExpr->getType() != lhsType) 4975 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), 4976 CastExpr::CK_Unknown); 4977 return result; 4978} 4979 4980QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 4981 Diag(Loc, diag::err_typecheck_invalid_operands) 4982 << lex->getType() << rex->getType() 4983 << lex->getSourceRange() << rex->getSourceRange(); 4984 return QualType(); 4985} 4986 4987QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 4988 // For conversion purposes, we ignore any qualifiers. 4989 // For example, "const float" and "float" are equivalent. 4990 QualType lhsType = 4991 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 4992 QualType rhsType = 4993 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 4994 4995 // If the vector types are identical, return. 4996 if (lhsType == rhsType) 4997 return lhsType; 4998 4999 // Handle the case of a vector & extvector type of the same size and element 5000 // type. It would be nice if we only had one vector type someday. 5001 if (getLangOptions().LaxVectorConversions) { 5002 // FIXME: Should we warn here? 5003 if (const VectorType *LV = lhsType->getAs<VectorType>()) { 5004 if (const VectorType *RV = rhsType->getAs<VectorType>()) 5005 if (LV->getElementType() == RV->getElementType() && 5006 LV->getNumElements() == RV->getNumElements()) { 5007 if (lhsType->isExtVectorType()) { 5008 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast); 5009 return lhsType; 5010 } 5011 5012 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast); 5013 return rhsType; 5014 } 5015 } 5016 } 5017 5018 // Handle the case of equivalent AltiVec and GCC vector types 5019 if (lhsType->isVectorType() && rhsType->isVectorType() && 5020 Context.areCompatibleVectorTypes(lhsType, rhsType)) { 5021 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast); 5022 return rhsType; 5023 } 5024 5025 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5026 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5027 bool swapped = false; 5028 if (rhsType->isExtVectorType()) { 5029 swapped = true; 5030 std::swap(rex, lex); 5031 std::swap(rhsType, lhsType); 5032 } 5033 5034 // Handle the case of an ext vector and scalar. 5035 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) { 5036 QualType EltTy = LV->getElementType(); 5037 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) { 5038 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 5039 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast); 5040 if (swapped) std::swap(rex, lex); 5041 return lhsType; 5042 } 5043 } 5044 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 5045 rhsType->isRealFloatingType()) { 5046 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 5047 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast); 5048 if (swapped) std::swap(rex, lex); 5049 return lhsType; 5050 } 5051 } 5052 } 5053 5054 // Vectors of different size or scalar and non-ext-vector are errors. 5055 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5056 << lex->getType() << rex->getType() 5057 << lex->getSourceRange() << rex->getSourceRange(); 5058 return QualType(); 5059} 5060 5061QualType Sema::CheckMultiplyDivideOperands( 5062 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) { 5063 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5064 return CheckVectorOperands(Loc, lex, rex); 5065 5066 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5067 5068 if (!lex->getType()->isArithmeticType() || 5069 !rex->getType()->isArithmeticType()) 5070 return InvalidOperands(Loc, lex, rex); 5071 5072 // Check for division by zero. 5073 if (isDiv && 5074 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 5075 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero) 5076 << rex->getSourceRange()); 5077 5078 return compType; 5079} 5080 5081QualType Sema::CheckRemainderOperands( 5082 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 5083 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5084 if (lex->getType()->hasIntegerRepresentation() && 5085 rex->getType()->hasIntegerRepresentation()) 5086 return CheckVectorOperands(Loc, lex, rex); 5087 return InvalidOperands(Loc, lex, rex); 5088 } 5089 5090 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5091 5092 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 5093 return InvalidOperands(Loc, lex, rex); 5094 5095 // Check for remainder by zero. 5096 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 5097 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero) 5098 << rex->getSourceRange()); 5099 5100 return compType; 5101} 5102 5103QualType Sema::CheckAdditionOperands( // C99 6.5.6 5104 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { 5105 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5106 QualType compType = CheckVectorOperands(Loc, lex, rex); 5107 if (CompLHSTy) *CompLHSTy = compType; 5108 return compType; 5109 } 5110 5111 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 5112 5113 // handle the common case first (both operands are arithmetic). 5114 if (lex->getType()->isArithmeticType() && 5115 rex->getType()->isArithmeticType()) { 5116 if (CompLHSTy) *CompLHSTy = compType; 5117 return compType; 5118 } 5119 5120 // Put any potential pointer into PExp 5121 Expr* PExp = lex, *IExp = rex; 5122 if (IExp->getType()->isAnyPointerType()) 5123 std::swap(PExp, IExp); 5124 5125 if (PExp->getType()->isAnyPointerType()) { 5126 5127 if (IExp->getType()->isIntegerType()) { 5128 QualType PointeeTy = PExp->getType()->getPointeeType(); 5129 5130 // Check for arithmetic on pointers to incomplete types. 5131 if (PointeeTy->isVoidType()) { 5132 if (getLangOptions().CPlusPlus) { 5133 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5134 << lex->getSourceRange() << rex->getSourceRange(); 5135 return QualType(); 5136 } 5137 5138 // GNU extension: arithmetic on pointer to void 5139 Diag(Loc, diag::ext_gnu_void_ptr) 5140 << lex->getSourceRange() << rex->getSourceRange(); 5141 } else if (PointeeTy->isFunctionType()) { 5142 if (getLangOptions().CPlusPlus) { 5143 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5144 << lex->getType() << lex->getSourceRange(); 5145 return QualType(); 5146 } 5147 5148 // GNU extension: arithmetic on pointer to function 5149 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5150 << lex->getType() << lex->getSourceRange(); 5151 } else { 5152 // Check if we require a complete type. 5153 if (((PExp->getType()->isPointerType() && 5154 !PExp->getType()->isDependentType()) || 5155 PExp->getType()->isObjCObjectPointerType()) && 5156 RequireCompleteType(Loc, PointeeTy, 5157 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5158 << PExp->getSourceRange() 5159 << PExp->getType())) 5160 return QualType(); 5161 } 5162 // Diagnose bad cases where we step over interface counts. 5163 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 5164 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5165 << PointeeTy << PExp->getSourceRange(); 5166 return QualType(); 5167 } 5168 5169 if (CompLHSTy) { 5170 QualType LHSTy = Context.isPromotableBitField(lex); 5171 if (LHSTy.isNull()) { 5172 LHSTy = lex->getType(); 5173 if (LHSTy->isPromotableIntegerType()) 5174 LHSTy = Context.getPromotedIntegerType(LHSTy); 5175 } 5176 *CompLHSTy = LHSTy; 5177 } 5178 return PExp->getType(); 5179 } 5180 } 5181 5182 return InvalidOperands(Loc, lex, rex); 5183} 5184 5185// C99 6.5.6 5186QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 5187 SourceLocation Loc, QualType* CompLHSTy) { 5188 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5189 QualType compType = CheckVectorOperands(Loc, lex, rex); 5190 if (CompLHSTy) *CompLHSTy = compType; 5191 return compType; 5192 } 5193 5194 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 5195 5196 // Enforce type constraints: C99 6.5.6p3. 5197 5198 // Handle the common case first (both operands are arithmetic). 5199 if (lex->getType()->isArithmeticType() 5200 && rex->getType()->isArithmeticType()) { 5201 if (CompLHSTy) *CompLHSTy = compType; 5202 return compType; 5203 } 5204 5205 // Either ptr - int or ptr - ptr. 5206 if (lex->getType()->isAnyPointerType()) { 5207 QualType lpointee = lex->getType()->getPointeeType(); 5208 5209 // The LHS must be an completely-defined object type. 5210 5211 bool ComplainAboutVoid = false; 5212 Expr *ComplainAboutFunc = 0; 5213 if (lpointee->isVoidType()) { 5214 if (getLangOptions().CPlusPlus) { 5215 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5216 << lex->getSourceRange() << rex->getSourceRange(); 5217 return QualType(); 5218 } 5219 5220 // GNU C extension: arithmetic on pointer to void 5221 ComplainAboutVoid = true; 5222 } else if (lpointee->isFunctionType()) { 5223 if (getLangOptions().CPlusPlus) { 5224 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5225 << lex->getType() << lex->getSourceRange(); 5226 return QualType(); 5227 } 5228 5229 // GNU C extension: arithmetic on pointer to function 5230 ComplainAboutFunc = lex; 5231 } else if (!lpointee->isDependentType() && 5232 RequireCompleteType(Loc, lpointee, 5233 PDiag(diag::err_typecheck_sub_ptr_object) 5234 << lex->getSourceRange() 5235 << lex->getType())) 5236 return QualType(); 5237 5238 // Diagnose bad cases where we step over interface counts. 5239 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 5240 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5241 << lpointee << lex->getSourceRange(); 5242 return QualType(); 5243 } 5244 5245 // The result type of a pointer-int computation is the pointer type. 5246 if (rex->getType()->isIntegerType()) { 5247 if (ComplainAboutVoid) 5248 Diag(Loc, diag::ext_gnu_void_ptr) 5249 << lex->getSourceRange() << rex->getSourceRange(); 5250 if (ComplainAboutFunc) 5251 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5252 << ComplainAboutFunc->getType() 5253 << ComplainAboutFunc->getSourceRange(); 5254 5255 if (CompLHSTy) *CompLHSTy = lex->getType(); 5256 return lex->getType(); 5257 } 5258 5259 // Handle pointer-pointer subtractions. 5260 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 5261 QualType rpointee = RHSPTy->getPointeeType(); 5262 5263 // RHS must be a completely-type object type. 5264 // Handle the GNU void* extension. 5265 if (rpointee->isVoidType()) { 5266 if (getLangOptions().CPlusPlus) { 5267 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5268 << lex->getSourceRange() << rex->getSourceRange(); 5269 return QualType(); 5270 } 5271 5272 ComplainAboutVoid = true; 5273 } else if (rpointee->isFunctionType()) { 5274 if (getLangOptions().CPlusPlus) { 5275 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5276 << rex->getType() << rex->getSourceRange(); 5277 return QualType(); 5278 } 5279 5280 // GNU extension: arithmetic on pointer to function 5281 if (!ComplainAboutFunc) 5282 ComplainAboutFunc = rex; 5283 } else if (!rpointee->isDependentType() && 5284 RequireCompleteType(Loc, rpointee, 5285 PDiag(diag::err_typecheck_sub_ptr_object) 5286 << rex->getSourceRange() 5287 << rex->getType())) 5288 return QualType(); 5289 5290 if (getLangOptions().CPlusPlus) { 5291 // Pointee types must be the same: C++ [expr.add] 5292 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 5293 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5294 << lex->getType() << rex->getType() 5295 << lex->getSourceRange() << rex->getSourceRange(); 5296 return QualType(); 5297 } 5298 } else { 5299 // Pointee types must be compatible C99 6.5.6p3 5300 if (!Context.typesAreCompatible( 5301 Context.getCanonicalType(lpointee).getUnqualifiedType(), 5302 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 5303 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5304 << lex->getType() << rex->getType() 5305 << lex->getSourceRange() << rex->getSourceRange(); 5306 return QualType(); 5307 } 5308 } 5309 5310 if (ComplainAboutVoid) 5311 Diag(Loc, diag::ext_gnu_void_ptr) 5312 << lex->getSourceRange() << rex->getSourceRange(); 5313 if (ComplainAboutFunc) 5314 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5315 << ComplainAboutFunc->getType() 5316 << ComplainAboutFunc->getSourceRange(); 5317 5318 if (CompLHSTy) *CompLHSTy = lex->getType(); 5319 return Context.getPointerDiffType(); 5320 } 5321 } 5322 5323 return InvalidOperands(Loc, lex, rex); 5324} 5325 5326// C99 6.5.7 5327QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5328 bool isCompAssign) { 5329 // C99 6.5.7p2: Each of the operands shall have integer type. 5330 if (!lex->getType()->hasIntegerRepresentation() || 5331 !rex->getType()->hasIntegerRepresentation()) 5332 return InvalidOperands(Loc, lex, rex); 5333 5334 // Vector shifts promote their scalar inputs to vector type. 5335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5336 return CheckVectorOperands(Loc, lex, rex); 5337 5338 // Shifts don't perform usual arithmetic conversions, they just do integer 5339 // promotions on each operand. C99 6.5.7p3 5340 QualType LHSTy = Context.isPromotableBitField(lex); 5341 if (LHSTy.isNull()) { 5342 LHSTy = lex->getType(); 5343 if (LHSTy->isPromotableIntegerType()) 5344 LHSTy = Context.getPromotedIntegerType(LHSTy); 5345 } 5346 if (!isCompAssign) 5347 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast); 5348 5349 UsualUnaryConversions(rex); 5350 5351 // Sanity-check shift operands 5352 llvm::APSInt Right; 5353 // Check right/shifter operand 5354 if (!rex->isValueDependent() && 5355 rex->isIntegerConstantExpr(Right, Context)) { 5356 if (Right.isNegative()) 5357 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange(); 5358 else { 5359 llvm::APInt LeftBits(Right.getBitWidth(), 5360 Context.getTypeSize(lex->getType())); 5361 if (Right.uge(LeftBits)) 5362 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange(); 5363 } 5364 } 5365 5366 // "The type of the result is that of the promoted left operand." 5367 return LHSTy; 5368} 5369 5370static bool IsWithinTemplateSpecialization(Decl *D) { 5371 if (DeclContext *DC = D->getDeclContext()) { 5372 if (isa<ClassTemplateSpecializationDecl>(DC)) 5373 return true; 5374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 5375 return FD->isFunctionTemplateSpecialization(); 5376 } 5377 return false; 5378} 5379 5380// C99 6.5.8, C++ [expr.rel] 5381QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5382 unsigned OpaqueOpc, bool isRelational) { 5383 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; 5384 5385 // Handle vector comparisons separately. 5386 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5387 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 5388 5389 QualType lType = lex->getType(); 5390 QualType rType = rex->getType(); 5391 5392 if (!lType->hasFloatingRepresentation() && 5393 !(lType->isBlockPointerType() && isRelational)) { 5394 // For non-floating point types, check for self-comparisons of the form 5395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5396 // often indicate logic errors in the program. 5397 // 5398 // NOTE: Don't warn about comparison expressions resulting from macro 5399 // expansion. Also don't warn about comparisons which are only self 5400 // comparisons within a template specialization. The warnings should catch 5401 // obvious cases in the definition of the template anyways. The idea is to 5402 // warn when the typed comparison operator will always evaluate to the same 5403 // result. 5404 Expr *LHSStripped = lex->IgnoreParens(); 5405 Expr *RHSStripped = rex->IgnoreParens(); 5406 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 5407 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 5408 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() && 5409 !IsWithinTemplateSpecialization(DRL->getDecl())) { 5410 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always) 5411 << 0 // self- 5412 << (Opc == BinaryOperator::EQ 5413 || Opc == BinaryOperator::LE 5414 || Opc == BinaryOperator::GE)); 5415 } else if (lType->isArrayType() && rType->isArrayType() && 5416 !DRL->getDecl()->getType()->isReferenceType() && 5417 !DRR->getDecl()->getType()->isReferenceType()) { 5418 // what is it always going to eval to? 5419 char always_evals_to; 5420 switch(Opc) { 5421 case BinaryOperator::EQ: // e.g. array1 == array2 5422 always_evals_to = 0; // false 5423 break; 5424 case BinaryOperator::NE: // e.g. array1 != array2 5425 always_evals_to = 1; // true 5426 break; 5427 default: 5428 // best we can say is 'a constant' 5429 always_evals_to = 2; // e.g. array1 <= array2 5430 break; 5431 } 5432 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always) 5433 << 1 // array 5434 << always_evals_to); 5435 } 5436 } 5437 } 5438 5439 if (isa<CastExpr>(LHSStripped)) 5440 LHSStripped = LHSStripped->IgnoreParenCasts(); 5441 if (isa<CastExpr>(RHSStripped)) 5442 RHSStripped = RHSStripped->IgnoreParenCasts(); 5443 5444 // Warn about comparisons against a string constant (unless the other 5445 // operand is null), the user probably wants strcmp. 5446 Expr *literalString = 0; 5447 Expr *literalStringStripped = 0; 5448 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 5449 !RHSStripped->isNullPointerConstant(Context, 5450 Expr::NPC_ValueDependentIsNull)) { 5451 literalString = lex; 5452 literalStringStripped = LHSStripped; 5453 } else if ((isa<StringLiteral>(RHSStripped) || 5454 isa<ObjCEncodeExpr>(RHSStripped)) && 5455 !LHSStripped->isNullPointerConstant(Context, 5456 Expr::NPC_ValueDependentIsNull)) { 5457 literalString = rex; 5458 literalStringStripped = RHSStripped; 5459 } 5460 5461 if (literalString) { 5462 std::string resultComparison; 5463 switch (Opc) { 5464 case BinaryOperator::LT: resultComparison = ") < 0"; break; 5465 case BinaryOperator::GT: resultComparison = ") > 0"; break; 5466 case BinaryOperator::LE: resultComparison = ") <= 0"; break; 5467 case BinaryOperator::GE: resultComparison = ") >= 0"; break; 5468 case BinaryOperator::EQ: resultComparison = ") == 0"; break; 5469 case BinaryOperator::NE: resultComparison = ") != 0"; break; 5470 default: assert(false && "Invalid comparison operator"); 5471 } 5472 5473 DiagRuntimeBehavior(Loc, 5474 PDiag(diag::warn_stringcompare) 5475 << isa<ObjCEncodeExpr>(literalStringStripped) 5476 << literalString->getSourceRange()); 5477 } 5478 } 5479 5480 // C99 6.5.8p3 / C99 6.5.9p4 5481 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 5482 UsualArithmeticConversions(lex, rex); 5483 else { 5484 UsualUnaryConversions(lex); 5485 UsualUnaryConversions(rex); 5486 } 5487 5488 lType = lex->getType(); 5489 rType = rex->getType(); 5490 5491 // The result of comparisons is 'bool' in C++, 'int' in C. 5492 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy; 5493 5494 if (isRelational) { 5495 if (lType->isRealType() && rType->isRealType()) 5496 return ResultTy; 5497 } else { 5498 // Check for comparisons of floating point operands using != and ==. 5499 if (lType->hasFloatingRepresentation()) 5500 CheckFloatComparison(Loc,lex,rex); 5501 5502 if (lType->isArithmeticType() && rType->isArithmeticType()) 5503 return ResultTy; 5504 } 5505 5506 bool LHSIsNull = lex->isNullPointerConstant(Context, 5507 Expr::NPC_ValueDependentIsNull); 5508 bool RHSIsNull = rex->isNullPointerConstant(Context, 5509 Expr::NPC_ValueDependentIsNull); 5510 5511 // All of the following pointer-related warnings are GCC extensions, except 5512 // when handling null pointer constants. 5513 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 5514 QualType LCanPointeeTy = 5515 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 5516 QualType RCanPointeeTy = 5517 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 5518 5519 if (getLangOptions().CPlusPlus) { 5520 if (LCanPointeeTy == RCanPointeeTy) 5521 return ResultTy; 5522 if (!isRelational && 5523 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5524 // Valid unless comparison between non-null pointer and function pointer 5525 // This is a gcc extension compatibility comparison. 5526 // In a SFINAE context, we treat this as a hard error to maintain 5527 // conformance with the C++ standard. 5528 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5529 && !LHSIsNull && !RHSIsNull) { 5530 Diag(Loc, 5531 isSFINAEContext()? 5532 diag::err_typecheck_comparison_of_fptr_to_void 5533 : diag::ext_typecheck_comparison_of_fptr_to_void) 5534 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5535 5536 if (isSFINAEContext()) 5537 return QualType(); 5538 5539 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5540 return ResultTy; 5541 } 5542 } 5543 // C++ [expr.rel]p2: 5544 // [...] Pointer conversions (4.10) and qualification 5545 // conversions (4.4) are performed on pointer operands (or on 5546 // a pointer operand and a null pointer constant) to bring 5547 // them to their composite pointer type. [...] 5548 // 5549 // C++ [expr.eq]p1 uses the same notion for (in)equality 5550 // comparisons of pointers. 5551 bool NonStandardCompositeType = false; 5552 QualType T = FindCompositePointerType(Loc, lex, rex, 5553 isSFINAEContext()? 0 : &NonStandardCompositeType); 5554 if (T.isNull()) { 5555 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5556 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5557 return QualType(); 5558 } else if (NonStandardCompositeType) { 5559 Diag(Loc, 5560 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 5561 << lType << rType << T 5562 << lex->getSourceRange() << rex->getSourceRange(); 5563 } 5564 5565 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 5566 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 5567 return ResultTy; 5568 } 5569 // C99 6.5.9p2 and C99 6.5.8p2 5570 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 5571 RCanPointeeTy.getUnqualifiedType())) { 5572 // Valid unless a relational comparison of function pointers 5573 if (isRelational && LCanPointeeTy->isFunctionType()) { 5574 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 5575 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5576 } 5577 } else if (!isRelational && 5578 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5579 // Valid unless comparison between non-null pointer and function pointer 5580 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5581 && !LHSIsNull && !RHSIsNull) { 5582 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 5583 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5584 } 5585 } else { 5586 // Invalid 5587 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5588 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5589 } 5590 if (LCanPointeeTy != RCanPointeeTy) 5591 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5592 return ResultTy; 5593 } 5594 5595 if (getLangOptions().CPlusPlus) { 5596 // Comparison of pointers with null pointer constants and equality 5597 // comparisons of member pointers to null pointer constants. 5598 if (RHSIsNull && 5599 (lType->isPointerType() || 5600 (!isRelational && lType->isMemberPointerType()))) { 5601 ImpCastExprToType(rex, lType, 5602 lType->isMemberPointerType() 5603 ? CastExpr::CK_NullToMemberPointer 5604 : CastExpr::CK_IntegralToPointer); 5605 return ResultTy; 5606 } 5607 if (LHSIsNull && 5608 (rType->isPointerType() || 5609 (!isRelational && rType->isMemberPointerType()))) { 5610 ImpCastExprToType(lex, rType, 5611 rType->isMemberPointerType() 5612 ? CastExpr::CK_NullToMemberPointer 5613 : CastExpr::CK_IntegralToPointer); 5614 return ResultTy; 5615 } 5616 5617 // Comparison of member pointers. 5618 if (!isRelational && 5619 lType->isMemberPointerType() && rType->isMemberPointerType()) { 5620 // C++ [expr.eq]p2: 5621 // In addition, pointers to members can be compared, or a pointer to 5622 // member and a null pointer constant. Pointer to member conversions 5623 // (4.11) and qualification conversions (4.4) are performed to bring 5624 // them to a common type. If one operand is a null pointer constant, 5625 // the common type is the type of the other operand. Otherwise, the 5626 // common type is a pointer to member type similar (4.4) to the type 5627 // of one of the operands, with a cv-qualification signature (4.4) 5628 // that is the union of the cv-qualification signatures of the operand 5629 // types. 5630 bool NonStandardCompositeType = false; 5631 QualType T = FindCompositePointerType(Loc, lex, rex, 5632 isSFINAEContext()? 0 : &NonStandardCompositeType); 5633 if (T.isNull()) { 5634 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5635 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5636 return QualType(); 5637 } else if (NonStandardCompositeType) { 5638 Diag(Loc, 5639 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 5640 << lType << rType << T 5641 << lex->getSourceRange() << rex->getSourceRange(); 5642 } 5643 5644 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 5645 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 5646 return ResultTy; 5647 } 5648 5649 // Comparison of nullptr_t with itself. 5650 if (lType->isNullPtrType() && rType->isNullPtrType()) 5651 return ResultTy; 5652 } 5653 5654 // Handle block pointer types. 5655 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 5656 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 5657 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 5658 5659 if (!LHSIsNull && !RHSIsNull && 5660 !Context.typesAreCompatible(lpointee, rpointee)) { 5661 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5662 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5663 } 5664 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5665 return ResultTy; 5666 } 5667 // Allow block pointers to be compared with null pointer constants. 5668 if (!isRelational 5669 && ((lType->isBlockPointerType() && rType->isPointerType()) 5670 || (lType->isPointerType() && rType->isBlockPointerType()))) { 5671 if (!LHSIsNull && !RHSIsNull) { 5672 if (!((rType->isPointerType() && rType->getAs<PointerType>() 5673 ->getPointeeType()->isVoidType()) 5674 || (lType->isPointerType() && lType->getAs<PointerType>() 5675 ->getPointeeType()->isVoidType()))) 5676 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5677 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5678 } 5679 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5680 return ResultTy; 5681 } 5682 5683 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) { 5684 if (lType->isPointerType() || rType->isPointerType()) { 5685 const PointerType *LPT = lType->getAs<PointerType>(); 5686 const PointerType *RPT = rType->getAs<PointerType>(); 5687 bool LPtrToVoid = LPT ? 5688 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 5689 bool RPtrToVoid = RPT ? 5690 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 5691 5692 if (!LPtrToVoid && !RPtrToVoid && 5693 !Context.typesAreCompatible(lType, rType)) { 5694 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5695 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5696 } 5697 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5698 return ResultTy; 5699 } 5700 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 5701 if (!Context.areComparableObjCPointerTypes(lType, rType)) 5702 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5703 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5704 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 5705 return ResultTy; 5706 } 5707 } 5708 if ((lType->isAnyPointerType() && rType->isIntegerType()) || 5709 (lType->isIntegerType() && rType->isAnyPointerType())) { 5710 unsigned DiagID = 0; 5711 bool isError = false; 5712 if ((LHSIsNull && lType->isIntegerType()) || 5713 (RHSIsNull && rType->isIntegerType())) { 5714 if (isRelational && !getLangOptions().CPlusPlus) 5715 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 5716 } else if (isRelational && !getLangOptions().CPlusPlus) 5717 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 5718 else if (getLangOptions().CPlusPlus) { 5719 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 5720 isError = true; 5721 } else 5722 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 5723 5724 if (DiagID) { 5725 Diag(Loc, DiagID) 5726 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5727 if (isError) 5728 return QualType(); 5729 } 5730 5731 if (lType->isIntegerType()) 5732 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 5733 else 5734 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 5735 return ResultTy; 5736 } 5737 5738 // Handle block pointers. 5739 if (!isRelational && RHSIsNull 5740 && lType->isBlockPointerType() && rType->isIntegerType()) { 5741 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 5742 return ResultTy; 5743 } 5744 if (!isRelational && LHSIsNull 5745 && lType->isIntegerType() && rType->isBlockPointerType()) { 5746 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 5747 return ResultTy; 5748 } 5749 return InvalidOperands(Loc, lex, rex); 5750} 5751 5752/// CheckVectorCompareOperands - vector comparisons are a clang extension that 5753/// operates on extended vector types. Instead of producing an IntTy result, 5754/// like a scalar comparison, a vector comparison produces a vector of integer 5755/// types. 5756QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 5757 SourceLocation Loc, 5758 bool isRelational) { 5759 // Check to make sure we're operating on vectors of the same type and width, 5760 // Allowing one side to be a scalar of element type. 5761 QualType vType = CheckVectorOperands(Loc, lex, rex); 5762 if (vType.isNull()) 5763 return vType; 5764 5765 QualType lType = lex->getType(); 5766 QualType rType = rex->getType(); 5767 5768 // For non-floating point types, check for self-comparisons of the form 5769 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5770 // often indicate logic errors in the program. 5771 if (!lType->hasFloatingRepresentation()) { 5772 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 5773 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 5774 if (DRL->getDecl() == DRR->getDecl()) 5775 DiagRuntimeBehavior(Loc, 5776 PDiag(diag::warn_comparison_always) 5777 << 0 // self- 5778 << 2 // "a constant" 5779 ); 5780 } 5781 5782 // Check for comparisons of floating point operands using != and ==. 5783 if (!isRelational && lType->hasFloatingRepresentation()) { 5784 assert (rType->hasFloatingRepresentation()); 5785 CheckFloatComparison(Loc,lex,rex); 5786 } 5787 5788 // Return the type for the comparison, which is the same as vector type for 5789 // integer vectors, or an integer type of identical size and number of 5790 // elements for floating point vectors. 5791 if (lType->hasIntegerRepresentation()) 5792 return lType; 5793 5794 const VectorType *VTy = lType->getAs<VectorType>(); 5795 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 5796 if (TypeSize == Context.getTypeSize(Context.IntTy)) 5797 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 5798 if (TypeSize == Context.getTypeSize(Context.LongTy)) 5799 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 5800 5801 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 5802 "Unhandled vector element size in vector compare"); 5803 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 5804} 5805 5806inline QualType Sema::CheckBitwiseOperands( 5807 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 5808 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5809 if (lex->getType()->hasIntegerRepresentation() && 5810 rex->getType()->hasIntegerRepresentation()) 5811 return CheckVectorOperands(Loc, lex, rex); 5812 5813 return InvalidOperands(Loc, lex, rex); 5814 } 5815 5816 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5817 5818 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 5819 return compType; 5820 return InvalidOperands(Loc, lex, rex); 5821} 5822 5823inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 5824 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) { 5825 5826 // Diagnose cases where the user write a logical and/or but probably meant a 5827 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 5828 // is a constant. 5829 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() && 5830 rex->getType()->isIntegerType() && !rex->isValueDependent() && 5831 // Don't warn in macros. 5832 !Loc.isMacroID()) { 5833 // If the RHS can be constant folded, and if it constant folds to something 5834 // that isn't 0 or 1 (which indicate a potential logical operation that 5835 // happened to fold to true/false) then warn. 5836 Expr::EvalResult Result; 5837 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects && 5838 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) { 5839 Diag(Loc, diag::warn_logical_instead_of_bitwise) 5840 << rex->getSourceRange() 5841 << (Opc == BinaryOperator::LAnd ? "&&" : "||") 5842 << (Opc == BinaryOperator::LAnd ? "&" : "|"); 5843 } 5844 } 5845 5846 if (!Context.getLangOptions().CPlusPlus) { 5847 UsualUnaryConversions(lex); 5848 UsualUnaryConversions(rex); 5849 5850 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType()) 5851 return InvalidOperands(Loc, lex, rex); 5852 5853 return Context.IntTy; 5854 } 5855 5856 // The following is safe because we only use this method for 5857 // non-overloadable operands. 5858 5859 // C++ [expr.log.and]p1 5860 // C++ [expr.log.or]p1 5861 // The operands are both contextually converted to type bool. 5862 if (PerformContextuallyConvertToBool(lex) || 5863 PerformContextuallyConvertToBool(rex)) 5864 return InvalidOperands(Loc, lex, rex); 5865 5866 // C++ [expr.log.and]p2 5867 // C++ [expr.log.or]p2 5868 // The result is a bool. 5869 return Context.BoolTy; 5870} 5871 5872/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 5873/// is a read-only property; return true if so. A readonly property expression 5874/// depends on various declarations and thus must be treated specially. 5875/// 5876static bool IsReadonlyProperty(Expr *E, Sema &S) { 5877 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 5878 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 5879 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 5880 QualType BaseType = PropExpr->getBase()->getType(); 5881 if (const ObjCObjectPointerType *OPT = 5882 BaseType->getAsObjCInterfacePointerType()) 5883 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 5884 if (S.isPropertyReadonly(PDecl, IFace)) 5885 return true; 5886 } 5887 } 5888 return false; 5889} 5890 5891/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 5892/// emit an error and return true. If so, return false. 5893static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 5894 SourceLocation OrigLoc = Loc; 5895 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 5896 &Loc); 5897 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 5898 IsLV = Expr::MLV_ReadonlyProperty; 5899 if (IsLV == Expr::MLV_Valid) 5900 return false; 5901 5902 unsigned Diag = 0; 5903 bool NeedType = false; 5904 switch (IsLV) { // C99 6.5.16p2 5905 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 5906 case Expr::MLV_ArrayType: 5907 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 5908 NeedType = true; 5909 break; 5910 case Expr::MLV_NotObjectType: 5911 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 5912 NeedType = true; 5913 break; 5914 case Expr::MLV_LValueCast: 5915 Diag = diag::err_typecheck_lvalue_casts_not_supported; 5916 break; 5917 case Expr::MLV_Valid: 5918 llvm_unreachable("did not take early return for MLV_Valid"); 5919 case Expr::MLV_InvalidExpression: 5920 case Expr::MLV_MemberFunction: 5921 case Expr::MLV_ClassTemporary: 5922 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 5923 break; 5924 case Expr::MLV_IncompleteType: 5925 case Expr::MLV_IncompleteVoidType: 5926 return S.RequireCompleteType(Loc, E->getType(), 5927 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 5928 << E->getSourceRange()); 5929 case Expr::MLV_DuplicateVectorComponents: 5930 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 5931 break; 5932 case Expr::MLV_NotBlockQualified: 5933 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 5934 break; 5935 case Expr::MLV_ReadonlyProperty: 5936 Diag = diag::error_readonly_property_assignment; 5937 break; 5938 case Expr::MLV_NoSetterProperty: 5939 Diag = diag::error_nosetter_property_assignment; 5940 break; 5941 case Expr::MLV_SubObjCPropertySetting: 5942 Diag = diag::error_no_subobject_property_setting; 5943 break; 5944 } 5945 5946 SourceRange Assign; 5947 if (Loc != OrigLoc) 5948 Assign = SourceRange(OrigLoc, OrigLoc); 5949 if (NeedType) 5950 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 5951 else 5952 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 5953 return true; 5954} 5955 5956 5957 5958// C99 6.5.16.1 5959QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 5960 SourceLocation Loc, 5961 QualType CompoundType) { 5962 // Verify that LHS is a modifiable lvalue, and emit error if not. 5963 if (CheckForModifiableLvalue(LHS, Loc, *this)) 5964 return QualType(); 5965 5966 QualType LHSType = LHS->getType(); 5967 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 5968 AssignConvertType ConvTy; 5969 if (CompoundType.isNull()) { 5970 QualType LHSTy(LHSType); 5971 // Simple assignment "x = y". 5972 if (const ObjCImplicitSetterGetterRefExpr *OISGE = 5973 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) { 5974 // If using property-dot syntax notation for assignment, and there is a 5975 // setter, RHS expression is being passed to the setter argument. So, 5976 // type conversion (and comparison) is RHS to setter's argument type. 5977 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) { 5978 ObjCMethodDecl::param_iterator P = SetterMD->param_begin(); 5979 LHSTy = (*P)->getType(); 5980 } 5981 } 5982 5983 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 5984 // Special case of NSObject attributes on c-style pointer types. 5985 if (ConvTy == IncompatiblePointer && 5986 ((Context.isObjCNSObjectType(LHSType) && 5987 RHSType->isObjCObjectPointerType()) || 5988 (Context.isObjCNSObjectType(RHSType) && 5989 LHSType->isObjCObjectPointerType()))) 5990 ConvTy = Compatible; 5991 5992 // If the RHS is a unary plus or minus, check to see if they = and + are 5993 // right next to each other. If so, the user may have typo'd "x =+ 4" 5994 // instead of "x += 4". 5995 Expr *RHSCheck = RHS; 5996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 5997 RHSCheck = ICE->getSubExpr(); 5998 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 5999 if ((UO->getOpcode() == UnaryOperator::Plus || 6000 UO->getOpcode() == UnaryOperator::Minus) && 6001 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 6002 // Only if the two operators are exactly adjacent. 6003 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 6004 // And there is a space or other character before the subexpr of the 6005 // unary +/-. We don't want to warn on "x=-1". 6006 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 6007 UO->getSubExpr()->getLocStart().isFileID()) { 6008 Diag(Loc, diag::warn_not_compound_assign) 6009 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 6010 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 6011 } 6012 } 6013 } else { 6014 // Compound assignment "x += y" 6015 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 6016 } 6017 6018 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 6019 RHS, AA_Assigning)) 6020 return QualType(); 6021 6022 6023 // Check to see if the destination operand is a dereferenced null pointer. If 6024 // so, and if not volatile-qualified, this is undefined behavior that the 6025 // optimizer will delete, so warn about it. People sometimes try to use this 6026 // to get a deterministic trap and are surprised by clang's behavior. This 6027 // only handles the pattern "*null = whatever", which is a very syntactic 6028 // check. 6029 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts())) 6030 if (UO->getOpcode() == UnaryOperator::Deref && 6031 UO->getSubExpr()->IgnoreParenCasts()-> 6032 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) && 6033 !UO->getType().isVolatileQualified()) { 6034 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null) 6035 << UO->getSubExpr()->getSourceRange(); 6036 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null); 6037 } 6038 6039 // C99 6.5.16p3: The type of an assignment expression is the type of the 6040 // left operand unless the left operand has qualified type, in which case 6041 // it is the unqualified version of the type of the left operand. 6042 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 6043 // is converted to the type of the assignment expression (above). 6044 // C++ 5.17p1: the type of the assignment expression is that of its left 6045 // operand. 6046 return LHSType.getUnqualifiedType(); 6047} 6048 6049// C99 6.5.17 6050QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 6051 DiagnoseUnusedExprResult(LHS); 6052 6053 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 6054 // C++ does not perform this conversion (C++ [expr.comma]p1). 6055 if (!getLangOptions().CPlusPlus) 6056 DefaultFunctionArrayLvalueConversion(RHS); 6057 6058 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be 6059 // incomplete in C++). 6060 6061 return RHS->getType(); 6062} 6063 6064/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 6065/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 6066QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 6067 bool isInc, bool isPrefix) { 6068 if (Op->isTypeDependent()) 6069 return Context.DependentTy; 6070 6071 QualType ResType = Op->getType(); 6072 assert(!ResType.isNull() && "no type for increment/decrement expression"); 6073 6074 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 6075 // Decrement of bool is not allowed. 6076 if (!isInc) { 6077 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 6078 return QualType(); 6079 } 6080 // Increment of bool sets it to true, but is deprecated. 6081 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 6082 } else if (ResType->isRealType()) { 6083 // OK! 6084 } else if (ResType->isAnyPointerType()) { 6085 QualType PointeeTy = ResType->getPointeeType(); 6086 6087 // C99 6.5.2.4p2, 6.5.6p2 6088 if (PointeeTy->isVoidType()) { 6089 if (getLangOptions().CPlusPlus) { 6090 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 6091 << Op->getSourceRange(); 6092 return QualType(); 6093 } 6094 6095 // Pointer to void is a GNU extension in C. 6096 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 6097 } else if (PointeeTy->isFunctionType()) { 6098 if (getLangOptions().CPlusPlus) { 6099 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 6100 << Op->getType() << Op->getSourceRange(); 6101 return QualType(); 6102 } 6103 6104 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 6105 << ResType << Op->getSourceRange(); 6106 } else if (RequireCompleteType(OpLoc, PointeeTy, 6107 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 6108 << Op->getSourceRange() 6109 << ResType)) 6110 return QualType(); 6111 // Diagnose bad cases where we step over interface counts. 6112 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6113 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 6114 << PointeeTy << Op->getSourceRange(); 6115 return QualType(); 6116 } 6117 } else if (ResType->isAnyComplexType()) { 6118 // C99 does not support ++/-- on complex types, we allow as an extension. 6119 Diag(OpLoc, diag::ext_integer_increment_complex) 6120 << ResType << Op->getSourceRange(); 6121 } else { 6122 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 6123 << ResType << int(isInc) << Op->getSourceRange(); 6124 return QualType(); 6125 } 6126 // At this point, we know we have a real, complex or pointer type. 6127 // Now make sure the operand is a modifiable lvalue. 6128 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 6129 return QualType(); 6130 // In C++, a prefix increment is the same type as the operand. Otherwise 6131 // (in C or with postfix), the increment is the unqualified type of the 6132 // operand. 6133 return isPrefix && getLangOptions().CPlusPlus 6134 ? ResType : ResType.getUnqualifiedType(); 6135} 6136 6137/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 6138/// This routine allows us to typecheck complex/recursive expressions 6139/// where the declaration is needed for type checking. We only need to 6140/// handle cases when the expression references a function designator 6141/// or is an lvalue. Here are some examples: 6142/// - &(x) => x 6143/// - &*****f => f for f a function designator. 6144/// - &s.xx => s 6145/// - &s.zz[1].yy -> s, if zz is an array 6146/// - *(x + 1) -> x, if x is an array 6147/// - &"123"[2] -> 0 6148/// - & __real__ x -> x 6149static NamedDecl *getPrimaryDecl(Expr *E) { 6150 switch (E->getStmtClass()) { 6151 case Stmt::DeclRefExprClass: 6152 return cast<DeclRefExpr>(E)->getDecl(); 6153 case Stmt::MemberExprClass: 6154 // If this is an arrow operator, the address is an offset from 6155 // the base's value, so the object the base refers to is 6156 // irrelevant. 6157 if (cast<MemberExpr>(E)->isArrow()) 6158 return 0; 6159 // Otherwise, the expression refers to a part of the base 6160 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 6161 case Stmt::ArraySubscriptExprClass: { 6162 // FIXME: This code shouldn't be necessary! We should catch the implicit 6163 // promotion of register arrays earlier. 6164 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 6165 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 6166 if (ICE->getSubExpr()->getType()->isArrayType()) 6167 return getPrimaryDecl(ICE->getSubExpr()); 6168 } 6169 return 0; 6170 } 6171 case Stmt::UnaryOperatorClass: { 6172 UnaryOperator *UO = cast<UnaryOperator>(E); 6173 6174 switch(UO->getOpcode()) { 6175 case UnaryOperator::Real: 6176 case UnaryOperator::Imag: 6177 case UnaryOperator::Extension: 6178 return getPrimaryDecl(UO->getSubExpr()); 6179 default: 6180 return 0; 6181 } 6182 } 6183 case Stmt::ParenExprClass: 6184 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 6185 case Stmt::ImplicitCastExprClass: 6186 // If the result of an implicit cast is an l-value, we care about 6187 // the sub-expression; otherwise, the result here doesn't matter. 6188 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 6189 default: 6190 return 0; 6191 } 6192} 6193 6194/// CheckAddressOfOperand - The operand of & must be either a function 6195/// designator or an lvalue designating an object. If it is an lvalue, the 6196/// object cannot be declared with storage class register or be a bit field. 6197/// Note: The usual conversions are *not* applied to the operand of the & 6198/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 6199/// In C++, the operand might be an overloaded function name, in which case 6200/// we allow the '&' but retain the overloaded-function type. 6201QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 6202 // Make sure to ignore parentheses in subsequent checks 6203 op = op->IgnoreParens(); 6204 6205 if (op->isTypeDependent()) 6206 return Context.DependentTy; 6207 6208 if (getLangOptions().C99) { 6209 // Implement C99-only parts of addressof rules. 6210 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 6211 if (uOp->getOpcode() == UnaryOperator::Deref) 6212 // Per C99 6.5.3.2, the address of a deref always returns a valid result 6213 // (assuming the deref expression is valid). 6214 return uOp->getSubExpr()->getType(); 6215 } 6216 // Technically, there should be a check for array subscript 6217 // expressions here, but the result of one is always an lvalue anyway. 6218 } 6219 NamedDecl *dcl = getPrimaryDecl(op); 6220 Expr::isLvalueResult lval = op->isLvalue(Context); 6221 6222 MemberExpr *ME = dyn_cast<MemberExpr>(op); 6223 if (lval == Expr::LV_MemberFunction && ME && 6224 isa<CXXMethodDecl>(ME->getMemberDecl())) { 6225 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl(); 6226 // &f where f is a member of the current object, or &o.f, or &p->f 6227 // All these are not allowed, and we need to catch them before the dcl 6228 // branch of the if, below. 6229 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 6230 << dcl; 6231 // FIXME: Improve this diagnostic and provide a fixit. 6232 6233 // Now recover by acting as if the function had been accessed qualified. 6234 return Context.getMemberPointerType(op->getType(), 6235 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext())) 6236 .getTypePtr()); 6237 } 6238 6239 if (lval == Expr::LV_ClassTemporary) { 6240 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary 6241 : diag::ext_typecheck_addrof_class_temporary) 6242 << op->getType() << op->getSourceRange(); 6243 if (isSFINAEContext()) 6244 return QualType(); 6245 } else if (isa<ObjCSelectorExpr>(op)) 6246 return Context.getPointerType(op->getType()); 6247 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 6248 // C99 6.5.3.2p1 6249 // The operand must be either an l-value or a function designator 6250 if (!op->getType()->isFunctionType()) { 6251 // FIXME: emit more specific diag... 6252 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 6253 << op->getSourceRange(); 6254 return QualType(); 6255 } 6256 } else if (op->getBitField()) { // C99 6.5.3.2p1 6257 // The operand cannot be a bit-field 6258 Diag(OpLoc, diag::err_typecheck_address_of) 6259 << "bit-field" << op->getSourceRange(); 6260 return QualType(); 6261 } else if (op->refersToVectorElement()) { 6262 // The operand cannot be an element of a vector 6263 Diag(OpLoc, diag::err_typecheck_address_of) 6264 << "vector element" << op->getSourceRange(); 6265 return QualType(); 6266 } else if (isa<ObjCPropertyRefExpr>(op)) { 6267 // cannot take address of a property expression. 6268 Diag(OpLoc, diag::err_typecheck_address_of) 6269 << "property expression" << op->getSourceRange(); 6270 return QualType(); 6271 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) { 6272 // FIXME: Can LHS ever be null here? 6273 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull()) 6274 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc); 6275 } else if (isa<OverloadExpr>(op)) { 6276 return Context.OverloadTy; 6277 } else if (dcl) { // C99 6.5.3.2p1 6278 // We have an lvalue with a decl. Make sure the decl is not declared 6279 // with the register storage-class specifier. 6280 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 6281 if (vd->getStorageClass() == VarDecl::Register) { 6282 Diag(OpLoc, diag::err_typecheck_address_of) 6283 << "register variable" << op->getSourceRange(); 6284 return QualType(); 6285 } 6286 } else if (isa<FunctionTemplateDecl>(dcl)) { 6287 return Context.OverloadTy; 6288 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 6289 // Okay: we can take the address of a field. 6290 // Could be a pointer to member, though, if there is an explicit 6291 // scope qualifier for the class. 6292 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 6293 DeclContext *Ctx = dcl->getDeclContext(); 6294 if (Ctx && Ctx->isRecord()) { 6295 if (FD->getType()->isReferenceType()) { 6296 Diag(OpLoc, 6297 diag::err_cannot_form_pointer_to_member_of_reference_type) 6298 << FD->getDeclName() << FD->getType(); 6299 return QualType(); 6300 } 6301 6302 return Context.getMemberPointerType(op->getType(), 6303 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 6304 } 6305 } 6306 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) { 6307 // Okay: we can take the address of a function. 6308 // As above. 6309 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() && 6310 MD->isInstance()) 6311 return Context.getMemberPointerType(op->getType(), 6312 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 6313 } else if (!isa<FunctionDecl>(dcl)) 6314 assert(0 && "Unknown/unexpected decl type"); 6315 } 6316 6317 if (lval == Expr::LV_IncompleteVoidType) { 6318 // Taking the address of a void variable is technically illegal, but we 6319 // allow it in cases which are otherwise valid. 6320 // Example: "extern void x; void* y = &x;". 6321 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 6322 } 6323 6324 // If the operand has type "type", the result has type "pointer to type". 6325 if (op->getType()->isObjCObjectType()) 6326 return Context.getObjCObjectPointerType(op->getType()); 6327 return Context.getPointerType(op->getType()); 6328} 6329 6330/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 6331QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 6332 if (Op->isTypeDependent()) 6333 return Context.DependentTy; 6334 6335 UsualUnaryConversions(Op); 6336 QualType OpTy = Op->getType(); 6337 QualType Result; 6338 6339 // Note that per both C89 and C99, indirection is always legal, even if OpTy 6340 // is an incomplete type or void. It would be possible to warn about 6341 // dereferencing a void pointer, but it's completely well-defined, and such a 6342 // warning is unlikely to catch any mistakes. 6343 if (const PointerType *PT = OpTy->getAs<PointerType>()) 6344 Result = PT->getPointeeType(); 6345 else if (const ObjCObjectPointerType *OPT = 6346 OpTy->getAs<ObjCObjectPointerType>()) 6347 Result = OPT->getPointeeType(); 6348 6349 if (Result.isNull()) { 6350 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 6351 << OpTy << Op->getSourceRange(); 6352 return QualType(); 6353 } 6354 6355 return Result; 6356} 6357 6358static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 6359 tok::TokenKind Kind) { 6360 BinaryOperator::Opcode Opc; 6361 switch (Kind) { 6362 default: assert(0 && "Unknown binop!"); 6363 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 6364 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 6365 case tok::star: Opc = BinaryOperator::Mul; break; 6366 case tok::slash: Opc = BinaryOperator::Div; break; 6367 case tok::percent: Opc = BinaryOperator::Rem; break; 6368 case tok::plus: Opc = BinaryOperator::Add; break; 6369 case tok::minus: Opc = BinaryOperator::Sub; break; 6370 case tok::lessless: Opc = BinaryOperator::Shl; break; 6371 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 6372 case tok::lessequal: Opc = BinaryOperator::LE; break; 6373 case tok::less: Opc = BinaryOperator::LT; break; 6374 case tok::greaterequal: Opc = BinaryOperator::GE; break; 6375 case tok::greater: Opc = BinaryOperator::GT; break; 6376 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 6377 case tok::equalequal: Opc = BinaryOperator::EQ; break; 6378 case tok::amp: Opc = BinaryOperator::And; break; 6379 case tok::caret: Opc = BinaryOperator::Xor; break; 6380 case tok::pipe: Opc = BinaryOperator::Or; break; 6381 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 6382 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 6383 case tok::equal: Opc = BinaryOperator::Assign; break; 6384 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 6385 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 6386 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 6387 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 6388 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 6389 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 6390 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 6391 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 6392 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 6393 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 6394 case tok::comma: Opc = BinaryOperator::Comma; break; 6395 } 6396 return Opc; 6397} 6398 6399static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 6400 tok::TokenKind Kind) { 6401 UnaryOperator::Opcode Opc; 6402 switch (Kind) { 6403 default: assert(0 && "Unknown unary op!"); 6404 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 6405 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 6406 case tok::amp: Opc = UnaryOperator::AddrOf; break; 6407 case tok::star: Opc = UnaryOperator::Deref; break; 6408 case tok::plus: Opc = UnaryOperator::Plus; break; 6409 case tok::minus: Opc = UnaryOperator::Minus; break; 6410 case tok::tilde: Opc = UnaryOperator::Not; break; 6411 case tok::exclaim: Opc = UnaryOperator::LNot; break; 6412 case tok::kw___real: Opc = UnaryOperator::Real; break; 6413 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 6414 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 6415 } 6416 return Opc; 6417} 6418 6419/// CreateBuiltinBinOp - Creates a new built-in binary operation with 6420/// operator @p Opc at location @c TokLoc. This routine only supports 6421/// built-in operations; ActOnBinOp handles overloaded operators. 6422ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 6423 unsigned Op, 6424 Expr *lhs, Expr *rhs) { 6425 QualType ResultTy; // Result type of the binary operator. 6426 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 6427 // The following two variables are used for compound assignment operators 6428 QualType CompLHSTy; // Type of LHS after promotions for computation 6429 QualType CompResultTy; // Type of computation result 6430 6431 switch (Opc) { 6432 case BinaryOperator::Assign: 6433 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 6434 break; 6435 case BinaryOperator::PtrMemD: 6436 case BinaryOperator::PtrMemI: 6437 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 6438 Opc == BinaryOperator::PtrMemI); 6439 break; 6440 case BinaryOperator::Mul: 6441 case BinaryOperator::Div: 6442 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false, 6443 Opc == BinaryOperator::Div); 6444 break; 6445 case BinaryOperator::Rem: 6446 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 6447 break; 6448 case BinaryOperator::Add: 6449 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 6450 break; 6451 case BinaryOperator::Sub: 6452 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 6453 break; 6454 case BinaryOperator::Shl: 6455 case BinaryOperator::Shr: 6456 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 6457 break; 6458 case BinaryOperator::LE: 6459 case BinaryOperator::LT: 6460 case BinaryOperator::GE: 6461 case BinaryOperator::GT: 6462 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 6463 break; 6464 case BinaryOperator::EQ: 6465 case BinaryOperator::NE: 6466 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 6467 break; 6468 case BinaryOperator::And: 6469 case BinaryOperator::Xor: 6470 case BinaryOperator::Or: 6471 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 6472 break; 6473 case BinaryOperator::LAnd: 6474 case BinaryOperator::LOr: 6475 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc); 6476 break; 6477 case BinaryOperator::MulAssign: 6478 case BinaryOperator::DivAssign: 6479 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true, 6480 Opc == BinaryOperator::DivAssign); 6481 CompLHSTy = CompResultTy; 6482 if (!CompResultTy.isNull()) 6483 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6484 break; 6485 case BinaryOperator::RemAssign: 6486 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 6487 CompLHSTy = CompResultTy; 6488 if (!CompResultTy.isNull()) 6489 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6490 break; 6491 case BinaryOperator::AddAssign: 6492 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6493 if (!CompResultTy.isNull()) 6494 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6495 break; 6496 case BinaryOperator::SubAssign: 6497 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6498 if (!CompResultTy.isNull()) 6499 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6500 break; 6501 case BinaryOperator::ShlAssign: 6502 case BinaryOperator::ShrAssign: 6503 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 6504 CompLHSTy = CompResultTy; 6505 if (!CompResultTy.isNull()) 6506 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6507 break; 6508 case BinaryOperator::AndAssign: 6509 case BinaryOperator::XorAssign: 6510 case BinaryOperator::OrAssign: 6511 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 6512 CompLHSTy = CompResultTy; 6513 if (!CompResultTy.isNull()) 6514 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6515 break; 6516 case BinaryOperator::Comma: 6517 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 6518 break; 6519 } 6520 if (ResultTy.isNull()) 6521 return ExprError(); 6522 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6523 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) 6524 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object) 6525 << ResultTy; 6526 } 6527 if (CompResultTy.isNull()) 6528 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 6529 else 6530 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 6531 CompLHSTy, CompResultTy, 6532 OpLoc)); 6533} 6534 6535/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps 6536/// ParenRange in parentheses. 6537static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6538 const PartialDiagnostic &PD, 6539 const PartialDiagnostic &FirstNote, 6540 SourceRange FirstParenRange, 6541 const PartialDiagnostic &SecondNote, 6542 SourceRange SecondParenRange) { 6543 Self.Diag(Loc, PD); 6544 6545 if (!FirstNote.getDiagID()) 6546 return; 6547 6548 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd()); 6549 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6550 // We can't display the parentheses, so just return. 6551 return; 6552 } 6553 6554 Self.Diag(Loc, FirstNote) 6555 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(") 6556 << FixItHint::CreateInsertion(EndLoc, ")"); 6557 6558 if (!SecondNote.getDiagID()) 6559 return; 6560 6561 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd()); 6562 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6563 // We can't display the parentheses, so just dig the 6564 // warning/error and return. 6565 Self.Diag(Loc, SecondNote); 6566 return; 6567 } 6568 6569 Self.Diag(Loc, SecondNote) 6570 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(") 6571 << FixItHint::CreateInsertion(EndLoc, ")"); 6572} 6573 6574/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 6575/// operators are mixed in a way that suggests that the programmer forgot that 6576/// comparison operators have higher precedence. The most typical example of 6577/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 6578static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc, 6579 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 6580 typedef BinaryOperator BinOp; 6581 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 6582 rhsopc = static_cast<BinOp::Opcode>(-1); 6583 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 6584 lhsopc = BO->getOpcode(); 6585 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 6586 rhsopc = BO->getOpcode(); 6587 6588 // Subs are not binary operators. 6589 if (lhsopc == -1 && rhsopc == -1) 6590 return; 6591 6592 // Bitwise operations are sometimes used as eager logical ops. 6593 // Don't diagnose this. 6594 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 6595 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 6596 return; 6597 6598 if (BinOp::isComparisonOp(lhsopc)) 6599 SuggestParentheses(Self, OpLoc, 6600 Self.PDiag(diag::warn_precedence_bitwise_rel) 6601 << SourceRange(lhs->getLocStart(), OpLoc) 6602 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc), 6603 Self.PDiag(diag::note_precedence_bitwise_first) 6604 << BinOp::getOpcodeStr(Opc), 6605 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()), 6606 Self.PDiag(diag::note_precedence_bitwise_silence) 6607 << BinOp::getOpcodeStr(lhsopc), 6608 lhs->getSourceRange()); 6609 else if (BinOp::isComparisonOp(rhsopc)) 6610 SuggestParentheses(Self, OpLoc, 6611 Self.PDiag(diag::warn_precedence_bitwise_rel) 6612 << SourceRange(OpLoc, rhs->getLocEnd()) 6613 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc), 6614 Self.PDiag(diag::note_precedence_bitwise_first) 6615 << BinOp::getOpcodeStr(Opc), 6616 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()), 6617 Self.PDiag(diag::note_precedence_bitwise_silence) 6618 << BinOp::getOpcodeStr(rhsopc), 6619 rhs->getSourceRange()); 6620} 6621 6622/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 6623/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3". 6624/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does. 6625static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc, 6626 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 6627 if (BinaryOperator::isBitwiseOp(Opc)) 6628 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 6629} 6630 6631// Binary Operators. 'Tok' is the token for the operator. 6632ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 6633 tok::TokenKind Kind, 6634 Expr *lhs, Expr *rhs) { 6635 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 6636 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 6637 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 6638 6639 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 6640 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 6641 6642 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 6643} 6644 6645ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 6646 BinaryOperator::Opcode Opc, 6647 Expr *lhs, Expr *rhs) { 6648 if (getLangOptions().CPlusPlus && 6649 (lhs->getType()->isOverloadableType() || 6650 rhs->getType()->isOverloadableType())) { 6651 // Find all of the overloaded operators visible from this 6652 // point. We perform both an operator-name lookup from the local 6653 // scope and an argument-dependent lookup based on the types of 6654 // the arguments. 6655 UnresolvedSet<16> Functions; 6656 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 6657 if (S && OverOp != OO_None) 6658 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 6659 Functions); 6660 6661 // Build the (potentially-overloaded, potentially-dependent) 6662 // binary operation. 6663 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 6664 } 6665 6666 // Build a built-in binary operation. 6667 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 6668} 6669 6670ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 6671 unsigned OpcIn, 6672 Expr *Input) { 6673 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 6674 6675 QualType resultType; 6676 switch (Opc) { 6677 case UnaryOperator::PreInc: 6678 case UnaryOperator::PreDec: 6679 case UnaryOperator::PostInc: 6680 case UnaryOperator::PostDec: 6681 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 6682 Opc == UnaryOperator::PreInc || 6683 Opc == UnaryOperator::PostInc, 6684 Opc == UnaryOperator::PreInc || 6685 Opc == UnaryOperator::PreDec); 6686 break; 6687 case UnaryOperator::AddrOf: 6688 resultType = CheckAddressOfOperand(Input, OpLoc); 6689 break; 6690 case UnaryOperator::Deref: 6691 DefaultFunctionArrayLvalueConversion(Input); 6692 resultType = CheckIndirectionOperand(Input, OpLoc); 6693 break; 6694 case UnaryOperator::Plus: 6695 case UnaryOperator::Minus: 6696 UsualUnaryConversions(Input); 6697 resultType = Input->getType(); 6698 if (resultType->isDependentType()) 6699 break; 6700 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 6701 resultType->isVectorType()) 6702 break; 6703 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 6704 resultType->isEnumeralType()) 6705 break; 6706 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 6707 Opc == UnaryOperator::Plus && 6708 resultType->isPointerType()) 6709 break; 6710 6711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6712 << resultType << Input->getSourceRange()); 6713 case UnaryOperator::Not: // bitwise complement 6714 UsualUnaryConversions(Input); 6715 resultType = Input->getType(); 6716 if (resultType->isDependentType()) 6717 break; 6718 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 6719 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 6720 // C99 does not support '~' for complex conjugation. 6721 Diag(OpLoc, diag::ext_integer_complement_complex) 6722 << resultType << Input->getSourceRange(); 6723 else if (!resultType->hasIntegerRepresentation()) 6724 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6725 << resultType << Input->getSourceRange()); 6726 break; 6727 case UnaryOperator::LNot: // logical negation 6728 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 6729 DefaultFunctionArrayLvalueConversion(Input); 6730 resultType = Input->getType(); 6731 if (resultType->isDependentType()) 6732 break; 6733 if (!resultType->isScalarType()) // C99 6.5.3.3p1 6734 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6735 << resultType << Input->getSourceRange()); 6736 // LNot always has type int. C99 6.5.3.3p5. 6737 // In C++, it's bool. C++ 5.3.1p8 6738 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 6739 break; 6740 case UnaryOperator::Real: 6741 case UnaryOperator::Imag: 6742 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 6743 break; 6744 case UnaryOperator::Extension: 6745 resultType = Input->getType(); 6746 break; 6747 } 6748 if (resultType.isNull()) 6749 return ExprError(); 6750 6751 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 6752} 6753 6754ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 6755 UnaryOperator::Opcode Opc, 6756 Expr *Input) { 6757 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 6758 Opc != UnaryOperator::Extension) { 6759 // Find all of the overloaded operators visible from this 6760 // point. We perform both an operator-name lookup from the local 6761 // scope and an argument-dependent lookup based on the types of 6762 // the arguments. 6763 UnresolvedSet<16> Functions; 6764 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 6765 if (S && OverOp != OO_None) 6766 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 6767 Functions); 6768 6769 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 6770 } 6771 6772 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 6773} 6774 6775// Unary Operators. 'Tok' is the token for the operator. 6776ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 6777 tok::TokenKind Op, Expr *Input) { 6778 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 6779} 6780 6781/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 6782ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 6783 SourceLocation LabLoc, 6784 IdentifierInfo *LabelII) { 6785 // Look up the record for this label identifier. 6786 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 6787 6788 // If we haven't seen this label yet, create a forward reference. It 6789 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 6790 if (LabelDecl == 0) 6791 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 6792 6793 // Create the AST node. The address of a label always has type 'void*'. 6794 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 6795 Context.getPointerType(Context.VoidTy))); 6796} 6797 6798ExprResult 6799Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 6800 SourceLocation RPLoc) { // "({..})" 6801 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 6802 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 6803 6804 bool isFileScope 6805 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 6806 if (isFileScope) 6807 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 6808 6809 // FIXME: there are a variety of strange constraints to enforce here, for 6810 // example, it is not possible to goto into a stmt expression apparently. 6811 // More semantic analysis is needed. 6812 6813 // If there are sub stmts in the compound stmt, take the type of the last one 6814 // as the type of the stmtexpr. 6815 QualType Ty = Context.VoidTy; 6816 6817 if (!Compound->body_empty()) { 6818 Stmt *LastStmt = Compound->body_back(); 6819 // If LastStmt is a label, skip down through into the body. 6820 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 6821 LastStmt = Label->getSubStmt(); 6822 6823 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 6824 Ty = LastExpr->getType(); 6825 } 6826 6827 // FIXME: Check that expression type is complete/non-abstract; statement 6828 // expressions are not lvalues. 6829 6830 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 6831} 6832 6833ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 6834 TypeSourceInfo *TInfo, 6835 OffsetOfComponent *CompPtr, 6836 unsigned NumComponents, 6837 SourceLocation RParenLoc) { 6838 QualType ArgTy = TInfo->getType(); 6839 bool Dependent = ArgTy->isDependentType(); 6840 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 6841 6842 // We must have at least one component that refers to the type, and the first 6843 // one is known to be a field designator. Verify that the ArgTy represents 6844 // a struct/union/class. 6845 if (!Dependent && !ArgTy->isRecordType()) 6846 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 6847 << ArgTy << TypeRange); 6848 6849 // Type must be complete per C99 7.17p3 because a declaring a variable 6850 // with an incomplete type would be ill-formed. 6851 if (!Dependent 6852 && RequireCompleteType(BuiltinLoc, ArgTy, 6853 PDiag(diag::err_offsetof_incomplete_type) 6854 << TypeRange)) 6855 return ExprError(); 6856 6857 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 6858 // GCC extension, diagnose them. 6859 // FIXME: This diagnostic isn't actually visible because the location is in 6860 // a system header! 6861 if (NumComponents != 1) 6862 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 6863 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 6864 6865 bool DidWarnAboutNonPOD = false; 6866 QualType CurrentType = ArgTy; 6867 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 6868 llvm::SmallVector<OffsetOfNode, 4> Comps; 6869 llvm::SmallVector<Expr*, 4> Exprs; 6870 for (unsigned i = 0; i != NumComponents; ++i) { 6871 const OffsetOfComponent &OC = CompPtr[i]; 6872 if (OC.isBrackets) { 6873 // Offset of an array sub-field. TODO: Should we allow vector elements? 6874 if (!CurrentType->isDependentType()) { 6875 const ArrayType *AT = Context.getAsArrayType(CurrentType); 6876 if(!AT) 6877 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 6878 << CurrentType); 6879 CurrentType = AT->getElementType(); 6880 } else 6881 CurrentType = Context.DependentTy; 6882 6883 // The expression must be an integral expression. 6884 // FIXME: An integral constant expression? 6885 Expr *Idx = static_cast<Expr*>(OC.U.E); 6886 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 6887 !Idx->getType()->isIntegerType()) 6888 return ExprError(Diag(Idx->getLocStart(), 6889 diag::err_typecheck_subscript_not_integer) 6890 << Idx->getSourceRange()); 6891 6892 // Record this array index. 6893 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 6894 Exprs.push_back(Idx); 6895 continue; 6896 } 6897 6898 // Offset of a field. 6899 if (CurrentType->isDependentType()) { 6900 // We have the offset of a field, but we can't look into the dependent 6901 // type. Just record the identifier of the field. 6902 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 6903 CurrentType = Context.DependentTy; 6904 continue; 6905 } 6906 6907 // We need to have a complete type to look into. 6908 if (RequireCompleteType(OC.LocStart, CurrentType, 6909 diag::err_offsetof_incomplete_type)) 6910 return ExprError(); 6911 6912 // Look for the designated field. 6913 const RecordType *RC = CurrentType->getAs<RecordType>(); 6914 if (!RC) 6915 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 6916 << CurrentType); 6917 RecordDecl *RD = RC->getDecl(); 6918 6919 // C++ [lib.support.types]p5: 6920 // The macro offsetof accepts a restricted set of type arguments in this 6921 // International Standard. type shall be a POD structure or a POD union 6922 // (clause 9). 6923 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 6924 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 6925 DiagRuntimeBehavior(BuiltinLoc, 6926 PDiag(diag::warn_offsetof_non_pod_type) 6927 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 6928 << CurrentType)) 6929 DidWarnAboutNonPOD = true; 6930 } 6931 6932 // Look for the field. 6933 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 6934 LookupQualifiedName(R, RD); 6935 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 6936 if (!MemberDecl) 6937 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 6938 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 6939 OC.LocEnd)); 6940 6941 // C99 7.17p3: 6942 // (If the specified member is a bit-field, the behavior is undefined.) 6943 // 6944 // We diagnose this as an error. 6945 if (MemberDecl->getBitWidth()) { 6946 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 6947 << MemberDecl->getDeclName() 6948 << SourceRange(BuiltinLoc, RParenLoc); 6949 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 6950 return ExprError(); 6951 } 6952 6953 RecordDecl *Parent = MemberDecl->getParent(); 6954 bool AnonStructUnion = Parent->isAnonymousStructOrUnion(); 6955 if (AnonStructUnion) { 6956 do { 6957 Parent = cast<RecordDecl>(Parent->getParent()); 6958 } while (Parent->isAnonymousStructOrUnion()); 6959 } 6960 6961 // If the member was found in a base class, introduce OffsetOfNodes for 6962 // the base class indirections. 6963 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 6964 /*DetectVirtual=*/false); 6965 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 6966 CXXBasePath &Path = Paths.front(); 6967 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 6968 B != BEnd; ++B) 6969 Comps.push_back(OffsetOfNode(B->Base)); 6970 } 6971 6972 if (AnonStructUnion) { 6973 llvm::SmallVector<FieldDecl*, 4> Path; 6974 BuildAnonymousStructUnionMemberPath(MemberDecl, Path); 6975 unsigned n = Path.size(); 6976 for (int j = n - 1; j > -1; --j) 6977 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd)); 6978 } else { 6979 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 6980 } 6981 CurrentType = MemberDecl->getType().getNonReferenceType(); 6982 } 6983 6984 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 6985 TInfo, Comps.data(), Comps.size(), 6986 Exprs.data(), Exprs.size(), RParenLoc)); 6987} 6988 6989ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 6990 SourceLocation BuiltinLoc, 6991 SourceLocation TypeLoc, 6992 ParsedType argty, 6993 OffsetOfComponent *CompPtr, 6994 unsigned NumComponents, 6995 SourceLocation RPLoc) { 6996 6997 TypeSourceInfo *ArgTInfo; 6998 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo); 6999 if (ArgTy.isNull()) 7000 return ExprError(); 7001 7002 if (!ArgTInfo) 7003 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 7004 7005 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 7006 RPLoc); 7007} 7008 7009 7010ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 7011 ParsedType arg1,ParsedType arg2, 7012 SourceLocation RPLoc) { 7013 TypeSourceInfo *argTInfo1; 7014 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1); 7015 TypeSourceInfo *argTInfo2; 7016 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2); 7017 7018 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 7019 7020 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc); 7021} 7022 7023ExprResult 7024Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc, 7025 TypeSourceInfo *argTInfo1, 7026 TypeSourceInfo *argTInfo2, 7027 SourceLocation RPLoc) { 7028 if (getLangOptions().CPlusPlus) { 7029 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 7030 << SourceRange(BuiltinLoc, RPLoc); 7031 return ExprError(); 7032 } 7033 7034 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 7035 argTInfo1, argTInfo2, RPLoc)); 7036} 7037 7038 7039ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 7040 Expr *CondExpr, 7041 Expr *LHSExpr, Expr *RHSExpr, 7042 SourceLocation RPLoc) { 7043 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 7044 7045 QualType resType; 7046 bool ValueDependent = false; 7047 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 7048 resType = Context.DependentTy; 7049 ValueDependent = true; 7050 } else { 7051 // The conditional expression is required to be a constant expression. 7052 llvm::APSInt condEval(32); 7053 SourceLocation ExpLoc; 7054 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 7055 return ExprError(Diag(ExpLoc, 7056 diag::err_typecheck_choose_expr_requires_constant) 7057 << CondExpr->getSourceRange()); 7058 7059 // If the condition is > zero, then the AST type is the same as the LSHExpr. 7060 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 7061 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent() 7062 : RHSExpr->isValueDependent(); 7063 } 7064 7065 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 7066 resType, RPLoc, 7067 resType->isDependentType(), 7068 ValueDependent)); 7069} 7070 7071//===----------------------------------------------------------------------===// 7072// Clang Extensions. 7073//===----------------------------------------------------------------------===// 7074 7075/// ActOnBlockStart - This callback is invoked when a block literal is started. 7076void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 7077 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 7078 PushBlockScope(BlockScope, Block); 7079 CurContext->addDecl(Block); 7080 if (BlockScope) 7081 PushDeclContext(BlockScope, Block); 7082 else 7083 CurContext = Block; 7084} 7085 7086void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 7087 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 7088 BlockScopeInfo *CurBlock = getCurBlock(); 7089 7090 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 7091 CurBlock->TheDecl->setSignatureAsWritten(Sig); 7092 QualType T = Sig->getType(); 7093 7094 bool isVariadic; 7095 QualType RetTy; 7096 if (const FunctionType *Fn = T->getAs<FunctionType>()) { 7097 CurBlock->FunctionType = T; 7098 RetTy = Fn->getResultType(); 7099 isVariadic = 7100 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic(); 7101 } else { 7102 RetTy = T; 7103 isVariadic = false; 7104 } 7105 7106 CurBlock->TheDecl->setIsVariadic(isVariadic); 7107 7108 // Don't allow returning an array by value. 7109 if (RetTy->isArrayType()) { 7110 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array); 7111 return; 7112 } 7113 7114 // Don't allow returning a objc interface by value. 7115 if (RetTy->isObjCObjectType()) { 7116 Diag(ParamInfo.getSourceRange().getBegin(), 7117 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 7118 return; 7119 } 7120 7121 // Context.DependentTy is used as a placeholder for a missing block 7122 // return type. TODO: what should we do with declarators like: 7123 // ^ * { ... } 7124 // If the answer is "apply template argument deduction".... 7125 if (RetTy != Context.DependentTy) 7126 CurBlock->ReturnType = RetTy; 7127 7128 // Push block parameters from the declarator if we had them. 7129 llvm::SmallVector<ParmVarDecl*, 8> Params; 7130 if (isa<FunctionProtoType>(T)) { 7131 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc()); 7132 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 7133 ParmVarDecl *Param = TL.getArg(I); 7134 if (Param->getIdentifier() == 0 && 7135 !Param->isImplicit() && 7136 !Param->isInvalidDecl() && 7137 !getLangOptions().CPlusPlus) 7138 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 7139 Params.push_back(Param); 7140 } 7141 7142 // Fake up parameter variables if we have a typedef, like 7143 // ^ fntype { ... } 7144 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 7145 for (FunctionProtoType::arg_type_iterator 7146 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 7147 ParmVarDecl *Param = 7148 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 7149 ParamInfo.getSourceRange().getBegin(), 7150 *I); 7151 Params.push_back(Param); 7152 } 7153 } 7154 7155 // Set the parameters on the block decl. 7156 if (!Params.empty()) 7157 CurBlock->TheDecl->setParams(Params.data(), Params.size()); 7158 7159 // Finally we can process decl attributes. 7160 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 7161 7162 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) { 7163 Diag(ParamInfo.getAttributes()->getLoc(), 7164 diag::warn_attribute_sentinel_not_variadic) << 1; 7165 // FIXME: remove the attribute. 7166 } 7167 7168 // Put the parameter variables in scope. We can bail out immediately 7169 // if we don't have any. 7170 if (Params.empty()) 7171 return; 7172 7173 bool ShouldCheckShadow = 7174 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored; 7175 7176 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 7177 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 7178 (*AI)->setOwningFunction(CurBlock->TheDecl); 7179 7180 // If this has an identifier, add it to the scope stack. 7181 if ((*AI)->getIdentifier()) { 7182 if (ShouldCheckShadow) 7183 CheckShadow(CurBlock->TheScope, *AI); 7184 7185 PushOnScopeChains(*AI, CurBlock->TheScope); 7186 } 7187 } 7188} 7189 7190/// ActOnBlockError - If there is an error parsing a block, this callback 7191/// is invoked to pop the information about the block from the action impl. 7192void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 7193 // Pop off CurBlock, handle nested blocks. 7194 PopDeclContext(); 7195 PopFunctionOrBlockScope(); 7196 // FIXME: Delete the ParmVarDecl objects as well??? 7197} 7198 7199/// ActOnBlockStmtExpr - This is called when the body of a block statement 7200/// literal was successfully completed. ^(int x){...} 7201ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 7202 Stmt *Body, Scope *CurScope) { 7203 // If blocks are disabled, emit an error. 7204 if (!LangOpts.Blocks) 7205 Diag(CaretLoc, diag::err_blocks_disable); 7206 7207 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 7208 7209 PopDeclContext(); 7210 7211 QualType RetTy = Context.VoidTy; 7212 if (!BSI->ReturnType.isNull()) 7213 RetTy = BSI->ReturnType; 7214 7215 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 7216 QualType BlockTy; 7217 7218 // If the user wrote a function type in some form, try to use that. 7219 if (!BSI->FunctionType.isNull()) { 7220 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 7221 7222 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 7223 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 7224 7225 // Turn protoless block types into nullary block types. 7226 if (isa<FunctionNoProtoType>(FTy)) { 7227 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, 7228 false, false, 0, 0, Ext); 7229 7230 // Otherwise, if we don't need to change anything about the function type, 7231 // preserve its sugar structure. 7232 } else if (FTy->getResultType() == RetTy && 7233 (!NoReturn || FTy->getNoReturnAttr())) { 7234 BlockTy = BSI->FunctionType; 7235 7236 // Otherwise, make the minimal modifications to the function type. 7237 } else { 7238 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 7239 BlockTy = Context.getFunctionType(RetTy, 7240 FPT->arg_type_begin(), 7241 FPT->getNumArgs(), 7242 FPT->isVariadic(), 7243 /*quals*/ 0, 7244 FPT->hasExceptionSpec(), 7245 FPT->hasAnyExceptionSpec(), 7246 FPT->getNumExceptions(), 7247 FPT->exception_begin(), 7248 Ext); 7249 } 7250 7251 // If we don't have a function type, just build one from nothing. 7252 } else { 7253 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, 7254 false, false, 0, 0, 7255 FunctionType::ExtInfo(NoReturn, 0, CC_Default)); 7256 } 7257 7258 // FIXME: Check that return/parameter types are complete/non-abstract 7259 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 7260 BSI->TheDecl->param_end()); 7261 BlockTy = Context.getBlockPointerType(BlockTy); 7262 7263 // If needed, diagnose invalid gotos and switches in the block. 7264 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction()) 7265 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 7266 7267 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 7268 7269 bool Good = true; 7270 // Check goto/label use. 7271 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 7272 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) { 7273 LabelStmt *L = I->second; 7274 7275 // Verify that we have no forward references left. If so, there was a goto 7276 // or address of a label taken, but no definition of it. 7277 if (L->getSubStmt() != 0) 7278 continue; 7279 7280 // Emit error. 7281 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 7282 Good = false; 7283 } 7284 if (!Good) { 7285 PopFunctionOrBlockScope(); 7286 return ExprError(); 7287 } 7288 7289 // Issue any analysis-based warnings. 7290 const sema::AnalysisBasedWarnings::Policy &WP = 7291 AnalysisWarnings.getDefaultPolicy(); 7292 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy); 7293 7294 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy, 7295 BSI->hasBlockDeclRefExprs); 7296 PopFunctionOrBlockScope(); 7297 return Owned(Result); 7298} 7299 7300ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 7301 Expr *expr, ParsedType type, 7302 SourceLocation RPLoc) { 7303 TypeSourceInfo *TInfo; 7304 QualType T = GetTypeFromParser(type, &TInfo); 7305 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc); 7306} 7307 7308ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 7309 Expr *E, TypeSourceInfo *TInfo, 7310 SourceLocation RPLoc) { 7311 Expr *OrigExpr = E; 7312 7313 InitBuiltinVaListType(); 7314 7315 // Get the va_list type 7316 QualType VaListType = Context.getBuiltinVaListType(); 7317 if (VaListType->isArrayType()) { 7318 // Deal with implicit array decay; for example, on x86-64, 7319 // va_list is an array, but it's supposed to decay to 7320 // a pointer for va_arg. 7321 VaListType = Context.getArrayDecayedType(VaListType); 7322 // Make sure the input expression also decays appropriately. 7323 UsualUnaryConversions(E); 7324 } else { 7325 // Otherwise, the va_list argument must be an l-value because 7326 // it is modified by va_arg. 7327 if (!E->isTypeDependent() && 7328 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 7329 return ExprError(); 7330 } 7331 7332 if (!E->isTypeDependent() && 7333 !Context.hasSameType(VaListType, E->getType())) { 7334 return ExprError(Diag(E->getLocStart(), 7335 diag::err_first_argument_to_va_arg_not_of_type_va_list) 7336 << OrigExpr->getType() << E->getSourceRange()); 7337 } 7338 7339 // FIXME: Check that type is complete/non-abstract 7340 // FIXME: Warn if a non-POD type is passed in. 7341 7342 QualType T = TInfo->getType().getNonLValueExprType(Context); 7343 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 7344} 7345 7346ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 7347 // The type of __null will be int or long, depending on the size of 7348 // pointers on the target. 7349 QualType Ty; 7350 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 7351 Ty = Context.IntTy; 7352 else 7353 Ty = Context.LongTy; 7354 7355 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 7356} 7357 7358static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 7359 Expr *SrcExpr, FixItHint &Hint) { 7360 if (!SemaRef.getLangOptions().ObjC1) 7361 return; 7362 7363 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 7364 if (!PT) 7365 return; 7366 7367 // Check if the destination is of type 'id'. 7368 if (!PT->isObjCIdType()) { 7369 // Check if the destination is the 'NSString' interface. 7370 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 7371 if (!ID || !ID->getIdentifier()->isStr("NSString")) 7372 return; 7373 } 7374 7375 // Strip off any parens and casts. 7376 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 7377 if (!SL || SL->isWide()) 7378 return; 7379 7380 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 7381} 7382 7383bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 7384 SourceLocation Loc, 7385 QualType DstType, QualType SrcType, 7386 Expr *SrcExpr, AssignmentAction Action, 7387 bool *Complained) { 7388 if (Complained) 7389 *Complained = false; 7390 7391 // Decode the result (notice that AST's are still created for extensions). 7392 bool isInvalid = false; 7393 unsigned DiagKind; 7394 FixItHint Hint; 7395 7396 switch (ConvTy) { 7397 default: assert(0 && "Unknown conversion type"); 7398 case Compatible: return false; 7399 case PointerToInt: 7400 DiagKind = diag::ext_typecheck_convert_pointer_int; 7401 break; 7402 case IntToPointer: 7403 DiagKind = diag::ext_typecheck_convert_int_pointer; 7404 break; 7405 case IncompatiblePointer: 7406 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 7407 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 7408 break; 7409 case IncompatiblePointerSign: 7410 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 7411 break; 7412 case FunctionVoidPointer: 7413 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 7414 break; 7415 case CompatiblePointerDiscardsQualifiers: 7416 // If the qualifiers lost were because we were applying the 7417 // (deprecated) C++ conversion from a string literal to a char* 7418 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 7419 // Ideally, this check would be performed in 7420 // CheckPointerTypesForAssignment. However, that would require a 7421 // bit of refactoring (so that the second argument is an 7422 // expression, rather than a type), which should be done as part 7423 // of a larger effort to fix CheckPointerTypesForAssignment for 7424 // C++ semantics. 7425 if (getLangOptions().CPlusPlus && 7426 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 7427 return false; 7428 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 7429 break; 7430 case IncompatibleNestedPointerQualifiers: 7431 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 7432 break; 7433 case IntToBlockPointer: 7434 DiagKind = diag::err_int_to_block_pointer; 7435 break; 7436 case IncompatibleBlockPointer: 7437 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 7438 break; 7439 case IncompatibleObjCQualifiedId: 7440 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 7441 // it can give a more specific diagnostic. 7442 DiagKind = diag::warn_incompatible_qualified_id; 7443 break; 7444 case IncompatibleVectors: 7445 DiagKind = diag::warn_incompatible_vectors; 7446 break; 7447 case Incompatible: 7448 DiagKind = diag::err_typecheck_convert_incompatible; 7449 isInvalid = true; 7450 break; 7451 } 7452 7453 QualType FirstType, SecondType; 7454 switch (Action) { 7455 case AA_Assigning: 7456 case AA_Initializing: 7457 // The destination type comes first. 7458 FirstType = DstType; 7459 SecondType = SrcType; 7460 break; 7461 7462 case AA_Returning: 7463 case AA_Passing: 7464 case AA_Converting: 7465 case AA_Sending: 7466 case AA_Casting: 7467 // The source type comes first. 7468 FirstType = SrcType; 7469 SecondType = DstType; 7470 break; 7471 } 7472 7473 Diag(Loc, DiagKind) << FirstType << SecondType << Action 7474 << SrcExpr->getSourceRange() << Hint; 7475 if (Complained) 7476 *Complained = true; 7477 return isInvalid; 7478} 7479 7480bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 7481 llvm::APSInt ICEResult; 7482 if (E->isIntegerConstantExpr(ICEResult, Context)) { 7483 if (Result) 7484 *Result = ICEResult; 7485 return false; 7486 } 7487 7488 Expr::EvalResult EvalResult; 7489 7490 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 7491 EvalResult.HasSideEffects) { 7492 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 7493 7494 if (EvalResult.Diag) { 7495 // We only show the note if it's not the usual "invalid subexpression" 7496 // or if it's actually in a subexpression. 7497 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 7498 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 7499 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7500 } 7501 7502 return true; 7503 } 7504 7505 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 7506 E->getSourceRange(); 7507 7508 if (EvalResult.Diag && 7509 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 7510 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7511 7512 if (Result) 7513 *Result = EvalResult.Val.getInt(); 7514 return false; 7515} 7516 7517void 7518Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 7519 ExprEvalContexts.push_back( 7520 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size())); 7521} 7522 7523void 7524Sema::PopExpressionEvaluationContext() { 7525 // Pop the current expression evaluation context off the stack. 7526 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 7527 ExprEvalContexts.pop_back(); 7528 7529 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 7530 if (Rec.PotentiallyReferenced) { 7531 // Mark any remaining declarations in the current position of the stack 7532 // as "referenced". If they were not meant to be referenced, semantic 7533 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 7534 for (PotentiallyReferencedDecls::iterator 7535 I = Rec.PotentiallyReferenced->begin(), 7536 IEnd = Rec.PotentiallyReferenced->end(); 7537 I != IEnd; ++I) 7538 MarkDeclarationReferenced(I->first, I->second); 7539 } 7540 7541 if (Rec.PotentiallyDiagnosed) { 7542 // Emit any pending diagnostics. 7543 for (PotentiallyEmittedDiagnostics::iterator 7544 I = Rec.PotentiallyDiagnosed->begin(), 7545 IEnd = Rec.PotentiallyDiagnosed->end(); 7546 I != IEnd; ++I) 7547 Diag(I->first, I->second); 7548 } 7549 } 7550 7551 // When are coming out of an unevaluated context, clear out any 7552 // temporaries that we may have created as part of the evaluation of 7553 // the expression in that context: they aren't relevant because they 7554 // will never be constructed. 7555 if (Rec.Context == Unevaluated && 7556 ExprTemporaries.size() > Rec.NumTemporaries) 7557 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 7558 ExprTemporaries.end()); 7559 7560 // Destroy the popped expression evaluation record. 7561 Rec.Destroy(); 7562} 7563 7564/// \brief Note that the given declaration was referenced in the source code. 7565/// 7566/// This routine should be invoke whenever a given declaration is referenced 7567/// in the source code, and where that reference occurred. If this declaration 7568/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 7569/// C99 6.9p3), then the declaration will be marked as used. 7570/// 7571/// \param Loc the location where the declaration was referenced. 7572/// 7573/// \param D the declaration that has been referenced by the source code. 7574void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 7575 assert(D && "No declaration?"); 7576 7577 if (D->isUsed(false)) 7578 return; 7579 7580 // Mark a parameter or variable declaration "used", regardless of whether we're in a 7581 // template or not. The reason for this is that unevaluated expressions 7582 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and 7583 // -Wunused-parameters) 7584 if (isa<ParmVarDecl>(D) || 7585 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) { 7586 D->setUsed(true); 7587 return; 7588 } 7589 7590 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) 7591 return; 7592 7593 // Do not mark anything as "used" within a dependent context; wait for 7594 // an instantiation. 7595 if (CurContext->isDependentContext()) 7596 return; 7597 7598 switch (ExprEvalContexts.back().Context) { 7599 case Unevaluated: 7600 // We are in an expression that is not potentially evaluated; do nothing. 7601 return; 7602 7603 case PotentiallyEvaluated: 7604 // We are in a potentially-evaluated expression, so this declaration is 7605 // "used"; handle this below. 7606 break; 7607 7608 case PotentiallyPotentiallyEvaluated: 7609 // We are in an expression that may be potentially evaluated; queue this 7610 // declaration reference until we know whether the expression is 7611 // potentially evaluated. 7612 ExprEvalContexts.back().addReferencedDecl(Loc, D); 7613 return; 7614 } 7615 7616 // Note that this declaration has been used. 7617 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 7618 unsigned TypeQuals; 7619 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 7620 if (Constructor->getParent()->hasTrivialConstructor()) 7621 return; 7622 if (!Constructor->isUsed(false)) 7623 DefineImplicitDefaultConstructor(Loc, Constructor); 7624 } else if (Constructor->isImplicit() && 7625 Constructor->isCopyConstructor(TypeQuals)) { 7626 if (!Constructor->isUsed(false)) 7627 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 7628 } 7629 7630 MarkVTableUsed(Loc, Constructor->getParent()); 7631 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 7632 if (Destructor->isImplicit() && !Destructor->isUsed(false)) 7633 DefineImplicitDestructor(Loc, Destructor); 7634 if (Destructor->isVirtual()) 7635 MarkVTableUsed(Loc, Destructor->getParent()); 7636 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 7637 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 7638 MethodDecl->getOverloadedOperator() == OO_Equal) { 7639 if (!MethodDecl->isUsed(false)) 7640 DefineImplicitCopyAssignment(Loc, MethodDecl); 7641 } else if (MethodDecl->isVirtual()) 7642 MarkVTableUsed(Loc, MethodDecl->getParent()); 7643 } 7644 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 7645 // Implicit instantiation of function templates and member functions of 7646 // class templates. 7647 if (Function->isImplicitlyInstantiable()) { 7648 bool AlreadyInstantiated = false; 7649 if (FunctionTemplateSpecializationInfo *SpecInfo 7650 = Function->getTemplateSpecializationInfo()) { 7651 if (SpecInfo->getPointOfInstantiation().isInvalid()) 7652 SpecInfo->setPointOfInstantiation(Loc); 7653 else if (SpecInfo->getTemplateSpecializationKind() 7654 == TSK_ImplicitInstantiation) 7655 AlreadyInstantiated = true; 7656 } else if (MemberSpecializationInfo *MSInfo 7657 = Function->getMemberSpecializationInfo()) { 7658 if (MSInfo->getPointOfInstantiation().isInvalid()) 7659 MSInfo->setPointOfInstantiation(Loc); 7660 else if (MSInfo->getTemplateSpecializationKind() 7661 == TSK_ImplicitInstantiation) 7662 AlreadyInstantiated = true; 7663 } 7664 7665 if (!AlreadyInstantiated) { 7666 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 7667 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 7668 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 7669 Loc)); 7670 else 7671 PendingImplicitInstantiations.push_back(std::make_pair(Function, 7672 Loc)); 7673 } 7674 } 7675 7676 // FIXME: keep track of references to static functions 7677 Function->setUsed(true); 7678 7679 return; 7680 } 7681 7682 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 7683 // Implicit instantiation of static data members of class templates. 7684 if (Var->isStaticDataMember() && 7685 Var->getInstantiatedFromStaticDataMember()) { 7686 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 7687 assert(MSInfo && "Missing member specialization information?"); 7688 if (MSInfo->getPointOfInstantiation().isInvalid() && 7689 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 7690 MSInfo->setPointOfInstantiation(Loc); 7691 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc)); 7692 } 7693 } 7694 7695 // FIXME: keep track of references to static data? 7696 7697 D->setUsed(true); 7698 return; 7699 } 7700} 7701 7702namespace { 7703 // Mark all of the declarations referenced 7704 // FIXME: Not fully implemented yet! We need to have a better understanding 7705 // of when we're entering 7706 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 7707 Sema &S; 7708 SourceLocation Loc; 7709 7710 public: 7711 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 7712 7713 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 7714 7715 bool TraverseTemplateArgument(const TemplateArgument &Arg); 7716 bool TraverseRecordType(RecordType *T); 7717 }; 7718} 7719 7720bool MarkReferencedDecls::TraverseTemplateArgument( 7721 const TemplateArgument &Arg) { 7722 if (Arg.getKind() == TemplateArgument::Declaration) { 7723 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl()); 7724 } 7725 7726 return Inherited::TraverseTemplateArgument(Arg); 7727} 7728 7729bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 7730 if (ClassTemplateSpecializationDecl *Spec 7731 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 7732 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 7733 return TraverseTemplateArguments(Args.getFlatArgumentList(), 7734 Args.flat_size()); 7735 } 7736 7737 return true; 7738} 7739 7740void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 7741 MarkReferencedDecls Marker(*this, Loc); 7742 Marker.TraverseType(Context.getCanonicalType(T)); 7743} 7744 7745/// \brief Emit a diagnostic that describes an effect on the run-time behavior 7746/// of the program being compiled. 7747/// 7748/// This routine emits the given diagnostic when the code currently being 7749/// type-checked is "potentially evaluated", meaning that there is a 7750/// possibility that the code will actually be executable. Code in sizeof() 7751/// expressions, code used only during overload resolution, etc., are not 7752/// potentially evaluated. This routine will suppress such diagnostics or, 7753/// in the absolutely nutty case of potentially potentially evaluated 7754/// expressions (C++ typeid), queue the diagnostic to potentially emit it 7755/// later. 7756/// 7757/// This routine should be used for all diagnostics that describe the run-time 7758/// behavior of a program, such as passing a non-POD value through an ellipsis. 7759/// Failure to do so will likely result in spurious diagnostics or failures 7760/// during overload resolution or within sizeof/alignof/typeof/typeid. 7761bool Sema::DiagRuntimeBehavior(SourceLocation Loc, 7762 const PartialDiagnostic &PD) { 7763 switch (ExprEvalContexts.back().Context ) { 7764 case Unevaluated: 7765 // The argument will never be evaluated, so don't complain. 7766 break; 7767 7768 case PotentiallyEvaluated: 7769 Diag(Loc, PD); 7770 return true; 7771 7772 case PotentiallyPotentiallyEvaluated: 7773 ExprEvalContexts.back().addDiagnostic(Loc, PD); 7774 break; 7775 } 7776 7777 return false; 7778} 7779 7780bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 7781 CallExpr *CE, FunctionDecl *FD) { 7782 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 7783 return false; 7784 7785 PartialDiagnostic Note = 7786 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 7787 << FD->getDeclName() : PDiag(); 7788 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 7789 7790 if (RequireCompleteType(Loc, ReturnType, 7791 FD ? 7792 PDiag(diag::err_call_function_incomplete_return) 7793 << CE->getSourceRange() << FD->getDeclName() : 7794 PDiag(diag::err_call_incomplete_return) 7795 << CE->getSourceRange(), 7796 std::make_pair(NoteLoc, Note))) 7797 return true; 7798 7799 return false; 7800} 7801 7802// Diagnose the common s/=/==/ typo. Note that adding parentheses 7803// will prevent this condition from triggering, which is what we want. 7804void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 7805 SourceLocation Loc; 7806 7807 unsigned diagnostic = diag::warn_condition_is_assignment; 7808 7809 if (isa<BinaryOperator>(E)) { 7810 BinaryOperator *Op = cast<BinaryOperator>(E); 7811 if (Op->getOpcode() != BinaryOperator::Assign) 7812 return; 7813 7814 // Greylist some idioms by putting them into a warning subcategory. 7815 if (ObjCMessageExpr *ME 7816 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 7817 Selector Sel = ME->getSelector(); 7818 7819 // self = [<foo> init...] 7820 if (isSelfExpr(Op->getLHS()) 7821 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init")) 7822 diagnostic = diag::warn_condition_is_idiomatic_assignment; 7823 7824 // <foo> = [<bar> nextObject] 7825 else if (Sel.isUnarySelector() && 7826 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject") 7827 diagnostic = diag::warn_condition_is_idiomatic_assignment; 7828 } 7829 7830 Loc = Op->getOperatorLoc(); 7831 } else if (isa<CXXOperatorCallExpr>(E)) { 7832 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E); 7833 if (Op->getOperator() != OO_Equal) 7834 return; 7835 7836 Loc = Op->getOperatorLoc(); 7837 } else { 7838 // Not an assignment. 7839 return; 7840 } 7841 7842 SourceLocation Open = E->getSourceRange().getBegin(); 7843 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 7844 7845 Diag(Loc, diagnostic) << E->getSourceRange(); 7846 Diag(Loc, diag::note_condition_assign_to_comparison) 7847 << FixItHint::CreateReplacement(Loc, "=="); 7848 Diag(Loc, diag::note_condition_assign_silence) 7849 << FixItHint::CreateInsertion(Open, "(") 7850 << FixItHint::CreateInsertion(Close, ")"); 7851} 7852 7853bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) { 7854 DiagnoseAssignmentAsCondition(E); 7855 7856 if (!E->isTypeDependent()) { 7857 DefaultFunctionArrayLvalueConversion(E); 7858 7859 QualType T = E->getType(); 7860 7861 if (getLangOptions().CPlusPlus) { 7862 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4 7863 return true; 7864 } else if (!T->isScalarType()) { // C99 6.8.4.1p1 7865 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 7866 << T << E->getSourceRange(); 7867 return true; 7868 } 7869 } 7870 7871 return false; 7872} 7873 7874ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 7875 Expr *Sub) { 7876 if (!Sub) 7877 return ExprError(); 7878 7879 if (CheckBooleanCondition(Sub, Loc)) 7880 return ExprError(); 7881 7882 return Owned(Sub); 7883} 7884