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