SemaExpr.cpp revision cc00fc02fb26921c2f1f99632ea1d96aa5d4d183
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 "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/Basic/PartialDiagnostic.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Lex/LiteralSupport.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Parse/DeclSpec.h" 26#include "clang/Parse/Designator.h" 27#include "clang/Parse/Scope.h" 28using namespace clang; 29 30 31/// \brief Determine whether the use of this declaration is valid, and 32/// emit any corresponding diagnostics. 33/// 34/// This routine diagnoses various problems with referencing 35/// declarations that can occur when using a declaration. For example, 36/// it might warn if a deprecated or unavailable declaration is being 37/// used, or produce an error (and return true) if a C++0x deleted 38/// function is being used. 39/// 40/// \returns true if there was an error (this declaration cannot be 41/// referenced), false otherwise. 42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 43 // See if the decl is deprecated. 44 if (D->getAttr<DeprecatedAttr>()) { 45 // Implementing deprecated stuff requires referencing deprecated 46 // stuff. Don't warn if we are implementing a deprecated 47 // construct. 48 bool isSilenced = false; 49 50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) { 51 // If this reference happens *in* a deprecated function or method, don't 52 // warn. 53 isSilenced = ND->getAttr<DeprecatedAttr>(); 54 55 // If this is an Objective-C method implementation, check to see if the 56 // method was deprecated on the declaration, not the definition. 57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) { 58 // The semantic decl context of a ObjCMethodDecl is the 59 // ObjCImplementationDecl. 60 if (ObjCImplementationDecl *Impl 61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) { 62 63 MD = Impl->getClassInterface()->getMethod(MD->getSelector(), 64 MD->isInstanceMethod()); 65 isSilenced |= MD && MD->getAttr<DeprecatedAttr>(); 66 } 67 } 68 } 69 70 if (!isSilenced) 71 Diag(Loc, diag::warn_deprecated) << D->getDeclName(); 72 } 73 74 // See if this is a deleted function. 75 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 76 if (FD->isDeleted()) { 77 Diag(Loc, diag::err_deleted_function_use); 78 Diag(D->getLocation(), diag::note_unavailable_here) << true; 79 return true; 80 } 81 } 82 83 // See if the decl is unavailable 84 if (D->getAttr<UnavailableAttr>()) { 85 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 86 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 87 } 88 89 return false; 90} 91 92/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 93/// (and other functions in future), which have been declared with sentinel 94/// attribute. It warns if call does not have the sentinel argument. 95/// 96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 97 Expr **Args, unsigned NumArgs) 98{ 99 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 100 if (!attr) 101 return; 102 int sentinelPos = attr->getSentinel(); 103 int nullPos = attr->getNullPos(); 104 105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 106 // base class. Then we won't be needing two versions of the same code. 107 unsigned int i = 0; 108 bool warnNotEnoughArgs = false; 109 int isMethod = 0; 110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 111 // skip over named parameters. 112 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 114 if (nullPos) 115 --nullPos; 116 else 117 ++i; 118 } 119 warnNotEnoughArgs = (P != E || i >= NumArgs); 120 isMethod = 1; 121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 122 // skip over named parameters. 123 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 125 if (nullPos) 126 --nullPos; 127 else 128 ++i; 129 } 130 warnNotEnoughArgs = (P != E || i >= NumArgs); 131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 132 // block or function pointer call. 133 QualType Ty = V->getType(); 134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 135 const FunctionType *FT = Ty->isFunctionPointerType() 136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType() 137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType(); 138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 139 unsigned NumArgsInProto = Proto->getNumArgs(); 140 unsigned k; 141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 142 if (nullPos) 143 --nullPos; 144 else 145 ++i; 146 } 147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 148 } 149 if (Ty->isBlockPointerType()) 150 isMethod = 2; 151 } else 152 return; 153 } else 154 return; 155 156 if (warnNotEnoughArgs) { 157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 159 return; 160 } 161 int sentinel = i; 162 while (sentinelPos > 0 && i < NumArgs-1) { 163 --sentinelPos; 164 ++i; 165 } 166 if (sentinelPos > 0) { 167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 169 return; 170 } 171 while (i < NumArgs-1) { 172 ++i; 173 ++sentinel; 174 } 175 Expr *sentinelExpr = Args[sentinel]; 176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() || 177 !sentinelExpr->isNullPointerConstant(Context))) { 178 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 180 } 181 return; 182} 183 184SourceRange Sema::getExprRange(ExprTy *E) const { 185 Expr *Ex = (Expr *)E; 186 return Ex? Ex->getSourceRange() : SourceRange(); 187} 188 189//===----------------------------------------------------------------------===// 190// Standard Promotions and Conversions 191//===----------------------------------------------------------------------===// 192 193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 194void Sema::DefaultFunctionArrayConversion(Expr *&E) { 195 QualType Ty = E->getType(); 196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 197 198 if (Ty->isFunctionType()) 199 ImpCastExprToType(E, Context.getPointerType(Ty), 200 CastExpr::CK_FunctionToPointerDecay); 201 else if (Ty->isArrayType()) { 202 // In C90 mode, arrays only promote to pointers if the array expression is 203 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 204 // type 'array of type' is converted to an expression that has type 'pointer 205 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 206 // that has type 'array of type' ...". The relevant change is "an lvalue" 207 // (C90) to "an expression" (C99). 208 // 209 // C++ 4.2p1: 210 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 211 // T" can be converted to an rvalue of type "pointer to T". 212 // 213 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 214 E->isLvalue(Context) == Expr::LV_Valid) 215 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 216 CastExpr::CK_ArrayToPointerDecay); 217 } 218} 219 220/// UsualUnaryConversions - Performs various conversions that are common to most 221/// operators (C99 6.3). The conversions of array and function types are 222/// sometimes surpressed. For example, the array->pointer conversion doesn't 223/// apply if the array is an argument to the sizeof or address (&) operators. 224/// In these instances, this routine should *not* be called. 225Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 226 QualType Ty = Expr->getType(); 227 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 228 229 // C99 6.3.1.1p2: 230 // 231 // The following may be used in an expression wherever an int or 232 // unsigned int may be used: 233 // - an object or expression with an integer type whose integer 234 // conversion rank is less than or equal to the rank of int 235 // and unsigned int. 236 // - A bit-field of type _Bool, int, signed int, or unsigned int. 237 // 238 // If an int can represent all values of the original type, the 239 // value is converted to an int; otherwise, it is converted to an 240 // unsigned int. These are called the integer promotions. All 241 // other types are unchanged by the integer promotions. 242 QualType PTy = Context.isPromotableBitField(Expr); 243 if (!PTy.isNull()) { 244 ImpCastExprToType(Expr, PTy); 245 return Expr; 246 } 247 if (Ty->isPromotableIntegerType()) { 248 QualType PT = Context.getPromotedIntegerType(Ty); 249 ImpCastExprToType(Expr, PT); 250 return Expr; 251 } 252 253 DefaultFunctionArrayConversion(Expr); 254 return Expr; 255} 256 257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 258/// do not have a prototype. Arguments that have type float are promoted to 259/// double. All other argument types are converted by UsualUnaryConversions(). 260void Sema::DefaultArgumentPromotion(Expr *&Expr) { 261 QualType Ty = Expr->getType(); 262 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 263 264 // If this is a 'float' (CVR qualified or typedef) promote to double. 265 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 266 if (BT->getKind() == BuiltinType::Float) 267 return ImpCastExprToType(Expr, Context.DoubleTy); 268 269 UsualUnaryConversions(Expr); 270} 271 272/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 273/// will warn if the resulting type is not a POD type, and rejects ObjC 274/// interfaces passed by value. This returns true if the argument type is 275/// completely illegal. 276bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 277 DefaultArgumentPromotion(Expr); 278 279 if (Expr->getType()->isObjCInterfaceType()) { 280 Diag(Expr->getLocStart(), 281 diag::err_cannot_pass_objc_interface_to_vararg) 282 << Expr->getType() << CT; 283 return true; 284 } 285 286 if (!Expr->getType()->isPODType()) 287 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg) 288 << Expr->getType() << CT; 289 290 return false; 291} 292 293 294/// UsualArithmeticConversions - Performs various conversions that are common to 295/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 296/// routine returns the first non-arithmetic type found. The client is 297/// responsible for emitting appropriate error diagnostics. 298/// FIXME: verify the conversion rules for "complex int" are consistent with 299/// GCC. 300QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 301 bool isCompAssign) { 302 if (!isCompAssign) 303 UsualUnaryConversions(lhsExpr); 304 305 UsualUnaryConversions(rhsExpr); 306 307 // For conversion purposes, we ignore any qualifiers. 308 // For example, "const float" and "float" are equivalent. 309 QualType lhs = 310 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 311 QualType rhs = 312 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 313 314 // If both types are identical, no conversion is needed. 315 if (lhs == rhs) 316 return lhs; 317 318 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 319 // The caller can deal with this (e.g. pointer + int). 320 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 321 return lhs; 322 323 // Perform bitfield promotions. 324 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 325 if (!LHSBitfieldPromoteTy.isNull()) 326 lhs = LHSBitfieldPromoteTy; 327 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr); 328 if (!RHSBitfieldPromoteTy.isNull()) 329 rhs = RHSBitfieldPromoteTy; 330 331 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs); 332 if (!isCompAssign) 333 ImpCastExprToType(lhsExpr, destType); 334 ImpCastExprToType(rhsExpr, destType); 335 return destType; 336} 337 338//===----------------------------------------------------------------------===// 339// Semantic Analysis for various Expression Types 340//===----------------------------------------------------------------------===// 341 342 343/// ActOnStringLiteral - The specified tokens were lexed as pasted string 344/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 345/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 346/// multiple tokens. However, the common case is that StringToks points to one 347/// string. 348/// 349Action::OwningExprResult 350Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 351 assert(NumStringToks && "Must have at least one string!"); 352 353 StringLiteralParser Literal(StringToks, NumStringToks, PP); 354 if (Literal.hadError) 355 return ExprError(); 356 357 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 358 for (unsigned i = 0; i != NumStringToks; ++i) 359 StringTokLocs.push_back(StringToks[i].getLocation()); 360 361 QualType StrTy = Context.CharTy; 362 if (Literal.AnyWide) StrTy = Context.getWCharType(); 363 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 364 365 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 366 if (getLangOptions().CPlusPlus) 367 StrTy.addConst(); 368 369 // Get an array type for the string, according to C99 6.4.5. This includes 370 // the nul terminator character as well as the string length for pascal 371 // strings. 372 StrTy = Context.getConstantArrayType(StrTy, 373 llvm::APInt(32, Literal.GetNumStringChars()+1), 374 ArrayType::Normal, 0); 375 376 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 377 return Owned(StringLiteral::Create(Context, Literal.GetString(), 378 Literal.GetStringLength(), 379 Literal.AnyWide, StrTy, 380 &StringTokLocs[0], 381 StringTokLocs.size())); 382} 383 384/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 385/// CurBlock to VD should cause it to be snapshotted (as we do for auto 386/// variables defined outside the block) or false if this is not needed (e.g. 387/// for values inside the block or for globals). 388/// 389/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records 390/// up-to-date. 391/// 392static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 393 ValueDecl *VD) { 394 // If the value is defined inside the block, we couldn't snapshot it even if 395 // we wanted to. 396 if (CurBlock->TheDecl == VD->getDeclContext()) 397 return false; 398 399 // If this is an enum constant or function, it is constant, don't snapshot. 400 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 401 return false; 402 403 // If this is a reference to an extern, static, or global variable, no need to 404 // snapshot it. 405 // FIXME: What about 'const' variables in C++? 406 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 407 if (!Var->hasLocalStorage()) 408 return false; 409 410 // Blocks that have these can't be constant. 411 CurBlock->hasBlockDeclRefExprs = true; 412 413 // If we have nested blocks, the decl may be declared in an outer block (in 414 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 415 // be defined outside all of the current blocks (in which case the blocks do 416 // all get the bit). Walk the nesting chain. 417 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock; 418 NextBlock = NextBlock->PrevBlockInfo) { 419 // If we found the defining block for the variable, don't mark the block as 420 // having a reference outside it. 421 if (NextBlock->TheDecl == VD->getDeclContext()) 422 break; 423 424 // Otherwise, the DeclRef from the inner block causes the outer one to need 425 // a snapshot as well. 426 NextBlock->hasBlockDeclRefExprs = true; 427 } 428 429 return true; 430} 431 432 433 434/// ActOnIdentifierExpr - The parser read an identifier in expression context, 435/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 436/// identifier is used in a function call context. 437/// SS is only used for a C++ qualified-id (foo::bar) to indicate the 438/// class or namespace that the identifier must be a member of. 439Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 440 IdentifierInfo &II, 441 bool HasTrailingLParen, 442 const CXXScopeSpec *SS, 443 bool isAddressOfOperand) { 444 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS, 445 isAddressOfOperand); 446} 447 448/// BuildDeclRefExpr - Build either a DeclRefExpr or a 449/// QualifiedDeclRefExpr based on whether or not SS is a 450/// nested-name-specifier. 451Sema::OwningExprResult 452Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, 453 bool TypeDependent, bool ValueDependent, 454 const CXXScopeSpec *SS) { 455 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 456 Diag(Loc, 457 diag::err_auto_variable_cannot_appear_in_own_initializer) 458 << D->getDeclName(); 459 return ExprError(); 460 } 461 462 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 464 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 465 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 466 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function) 467 << D->getIdentifier() << FD->getDeclName(); 468 Diag(D->getLocation(), diag::note_local_variable_declared_here) 469 << D->getIdentifier(); 470 return ExprError(); 471 } 472 } 473 } 474 } 475 476 MarkDeclarationReferenced(Loc, D); 477 478 Expr *E; 479 if (SS && !SS->isEmpty()) { 480 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, 481 ValueDependent, SS->getRange(), 482 static_cast<NestedNameSpecifier *>(SS->getScopeRep())); 483 } else 484 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent); 485 486 return Owned(E); 487} 488 489/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 490/// variable corresponding to the anonymous union or struct whose type 491/// is Record. 492static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context, 493 RecordDecl *Record) { 494 assert(Record->isAnonymousStructOrUnion() && 495 "Record must be an anonymous struct or union!"); 496 497 // FIXME: Once Decls are directly linked together, this will be an O(1) 498 // operation rather than a slow walk through DeclContext's vector (which 499 // itself will be eliminated). DeclGroups might make this even better. 500 DeclContext *Ctx = Record->getDeclContext(); 501 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 502 DEnd = Ctx->decls_end(); 503 D != DEnd; ++D) { 504 if (*D == Record) { 505 // The object for the anonymous struct/union directly 506 // follows its type in the list of declarations. 507 ++D; 508 assert(D != DEnd && "Missing object for anonymous record"); 509 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 510 return *D; 511 } 512 } 513 514 assert(false && "Missing object for anonymous record"); 515 return 0; 516} 517 518/// \brief Given a field that represents a member of an anonymous 519/// struct/union, build the path from that field's context to the 520/// actual member. 521/// 522/// Construct the sequence of field member references we'll have to 523/// perform to get to the field in the anonymous union/struct. The 524/// list of members is built from the field outward, so traverse it 525/// backwards to go from an object in the current context to the field 526/// we found. 527/// 528/// \returns The variable from which the field access should begin, 529/// for an anonymous struct/union that is not a member of another 530/// class. Otherwise, returns NULL. 531VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 532 llvm::SmallVectorImpl<FieldDecl *> &Path) { 533 assert(Field->getDeclContext()->isRecord() && 534 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 535 && "Field must be stored inside an anonymous struct or union"); 536 537 Path.push_back(Field); 538 VarDecl *BaseObject = 0; 539 DeclContext *Ctx = Field->getDeclContext(); 540 do { 541 RecordDecl *Record = cast<RecordDecl>(Ctx); 542 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record); 543 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 544 Path.push_back(AnonField); 545 else { 546 BaseObject = cast<VarDecl>(AnonObject); 547 break; 548 } 549 Ctx = Ctx->getParent(); 550 } while (Ctx->isRecord() && 551 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 552 553 return BaseObject; 554} 555 556Sema::OwningExprResult 557Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 558 FieldDecl *Field, 559 Expr *BaseObjectExpr, 560 SourceLocation OpLoc) { 561 llvm::SmallVector<FieldDecl *, 4> AnonFields; 562 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 563 AnonFields); 564 565 // Build the expression that refers to the base object, from 566 // which we will build a sequence of member references to each 567 // of the anonymous union objects and, eventually, the field we 568 // found via name lookup. 569 bool BaseObjectIsPointer = false; 570 unsigned ExtraQuals = 0; 571 if (BaseObject) { 572 // BaseObject is an anonymous struct/union variable (and is, 573 // therefore, not part of another non-anonymous record). 574 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 575 MarkDeclarationReferenced(Loc, BaseObject); 576 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 577 SourceLocation()); 578 ExtraQuals 579 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers(); 580 } else if (BaseObjectExpr) { 581 // The caller provided the base object expression. Determine 582 // whether its a pointer and whether it adds any qualifiers to the 583 // anonymous struct/union fields we're looking into. 584 QualType ObjectType = BaseObjectExpr->getType(); 585 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) { 586 BaseObjectIsPointer = true; 587 ObjectType = ObjectPtr->getPointeeType(); 588 } 589 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers(); 590 } else { 591 // We've found a member of an anonymous struct/union that is 592 // inside a non-anonymous struct/union, so in a well-formed 593 // program our base object expression is "this". 594 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 595 if (!MD->isStatic()) { 596 QualType AnonFieldType 597 = Context.getTagDeclType( 598 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 599 QualType ThisType = Context.getTagDeclType(MD->getParent()); 600 if ((Context.getCanonicalType(AnonFieldType) 601 == Context.getCanonicalType(ThisType)) || 602 IsDerivedFrom(ThisType, AnonFieldType)) { 603 // Our base object expression is "this". 604 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), 605 MD->getThisType(Context)); 606 BaseObjectIsPointer = true; 607 } 608 } else { 609 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 610 << Field->getDeclName()); 611 } 612 ExtraQuals = MD->getTypeQualifiers(); 613 } 614 615 if (!BaseObjectExpr) 616 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 617 << Field->getDeclName()); 618 } 619 620 // Build the implicit member references to the field of the 621 // anonymous struct/union. 622 Expr *Result = BaseObjectExpr; 623 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace(); 624 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 625 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 626 FI != FIEnd; ++FI) { 627 QualType MemberType = (*FI)->getType(); 628 if (!(*FI)->isMutable()) { 629 unsigned combinedQualifiers 630 = MemberType.getCVRQualifiers() | ExtraQuals; 631 MemberType = MemberType.getQualifiedType(combinedQualifiers); 632 } 633 if (BaseAddrSpace != MemberType.getAddressSpace()) 634 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace); 635 MarkDeclarationReferenced(Loc, *FI); 636 // FIXME: Might this end up being a qualified name? 637 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 638 OpLoc, MemberType); 639 BaseObjectIsPointer = false; 640 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers(); 641 } 642 643 return Owned(Result); 644} 645 646/// ActOnDeclarationNameExpr - The parser has read some kind of name 647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine 648/// performs lookup on that name and returns an expression that refers 649/// to that name. This routine isn't directly called from the parser, 650/// because the parser doesn't know about DeclarationName. Rather, 651/// this routine is called by ActOnIdentifierExpr, 652/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, 653/// which form the DeclarationName from the corresponding syntactic 654/// forms. 655/// 656/// HasTrailingLParen indicates whether this identifier is used in a 657/// function call context. LookupCtx is only used for a C++ 658/// qualified-id (foo::bar) to indicate the class or namespace that 659/// the identifier must be a member of. 660/// 661/// isAddressOfOperand means that this expression is the direct operand 662/// of an address-of operator. This matters because this is the only 663/// situation where a qualified name referencing a non-static member may 664/// appear outside a member function of this class. 665Sema::OwningExprResult 666Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, 667 DeclarationName Name, bool HasTrailingLParen, 668 const CXXScopeSpec *SS, 669 bool isAddressOfOperand) { 670 // Could be enum-constant, value decl, instance variable, etc. 671 if (SS && SS->isInvalid()) 672 return ExprError(); 673 674 // C++ [temp.dep.expr]p3: 675 // An id-expression is type-dependent if it contains: 676 // -- a nested-name-specifier that contains a class-name that 677 // names a dependent type. 678 // FIXME: Member of the current instantiation. 679 if (SS && isDependentScopeSpecifier(*SS)) { 680 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy, 681 Loc, SS->getRange(), 682 static_cast<NestedNameSpecifier *>(SS->getScopeRep()), 683 isAddressOfOperand)); 684 } 685 686 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName, 687 false, true, Loc); 688 689 if (Lookup.isAmbiguous()) { 690 DiagnoseAmbiguousLookup(Lookup, Name, Loc, 691 SS && SS->isSet() ? SS->getRange() 692 : SourceRange()); 693 return ExprError(); 694 } 695 696 NamedDecl *D = Lookup.getAsDecl(); 697 698 // If this reference is in an Objective-C method, then ivar lookup happens as 699 // well. 700 IdentifierInfo *II = Name.getAsIdentifierInfo(); 701 if (II && getCurMethodDecl()) { 702 // There are two cases to handle here. 1) scoped lookup could have failed, 703 // in which case we should look for an ivar. 2) scoped lookup could have 704 // found a decl, but that decl is outside the current instance method (i.e. 705 // a global variable). In these two cases, we do a lookup for an ivar with 706 // this name, if the lookup sucedes, we replace it our current decl. 707 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) { 708 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 709 ObjCInterfaceDecl *ClassDeclared; 710 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 711 // Check if referencing a field with __attribute__((deprecated)). 712 if (DiagnoseUseOfDecl(IV, Loc)) 713 return ExprError(); 714 715 // If we're referencing an invalid decl, just return this as a silent 716 // error node. The error diagnostic was already emitted on the decl. 717 if (IV->isInvalidDecl()) 718 return ExprError(); 719 720 bool IsClsMethod = getCurMethodDecl()->isClassMethod(); 721 // If a class method attemps to use a free standing ivar, this is 722 // an error. 723 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod()) 724 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 725 << IV->getDeclName()); 726 // If a class method uses a global variable, even if an ivar with 727 // same name exists, use the global. 728 if (!IsClsMethod) { 729 if (IV->getAccessControl() == ObjCIvarDecl::Private && 730 ClassDeclared != IFace) 731 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 732 // FIXME: This should use a new expr for a direct reference, don't 733 // turn this into Self->ivar, just return a BareIVarExpr or something. 734 IdentifierInfo &II = Context.Idents.get("self"); 735 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(), 736 II, false); 737 MarkDeclarationReferenced(Loc, IV); 738 return Owned(new (Context) 739 ObjCIvarRefExpr(IV, IV->getType(), Loc, 740 SelfExpr.takeAs<Expr>(), true, true)); 741 } 742 } 743 } else if (getCurMethodDecl()->isInstanceMethod()) { 744 // We should warn if a local variable hides an ivar. 745 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 746 ObjCInterfaceDecl *ClassDeclared; 747 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 748 if (IV->getAccessControl() != ObjCIvarDecl::Private || 749 IFace == ClassDeclared) 750 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 751 } 752 } 753 // Needed to implement property "super.method" notation. 754 if (D == 0 && II->isStr("super")) { 755 QualType T; 756 757 if (getCurMethodDecl()->isInstanceMethod()) 758 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType( 759 getCurMethodDecl()->getClassInterface())); 760 else 761 T = Context.getObjCClassType(); 762 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 763 } 764 } 765 766 // Determine whether this name might be a candidate for 767 // argument-dependent lookup. 768 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 769 HasTrailingLParen; 770 771 if (ADL && D == 0) { 772 // We've seen something of the form 773 // 774 // identifier( 775 // 776 // and we did not find any entity by the name 777 // "identifier". However, this identifier is still subject to 778 // argument-dependent lookup, so keep track of the name. 779 return Owned(new (Context) UnresolvedFunctionNameExpr(Name, 780 Context.OverloadTy, 781 Loc)); 782 } 783 784 if (D == 0) { 785 // Otherwise, this could be an implicitly declared function reference (legal 786 // in C90, extension in C99). 787 if (HasTrailingLParen && II && 788 !getLangOptions().CPlusPlus) // Not in C++. 789 D = ImplicitlyDefineFunction(Loc, *II, S); 790 else { 791 // If this name wasn't predeclared and if this is not a function call, 792 // diagnose the problem. 793 if (SS && !SS->isEmpty()) { 794 DiagnoseMissingMember(Loc, Name, 795 (NestedNameSpecifier *)SS->getScopeRep(), 796 SS->getRange()); 797 return ExprError(); 798 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 799 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 800 return ExprError(Diag(Loc, diag::err_undeclared_use) 801 << Name.getAsString()); 802 else 803 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name); 804 } 805 } 806 807 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 808 // Warn about constructs like: 809 // if (void *X = foo()) { ... } else { X }. 810 // In the else block, the pointer is always false. 811 812 // FIXME: In a template instantiation, we don't have scope 813 // information to check this property. 814 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 815 Scope *CheckS = S; 816 while (CheckS) { 817 if (CheckS->isWithinElse() && 818 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) { 819 if (Var->getType()->isBooleanType()) 820 ExprError(Diag(Loc, diag::warn_value_always_false) 821 << Var->getDeclName()); 822 else 823 ExprError(Diag(Loc, diag::warn_value_always_zero) 824 << Var->getDeclName()); 825 break; 826 } 827 828 // Move up one more control parent to check again. 829 CheckS = CheckS->getControlParent(); 830 if (CheckS) 831 CheckS = CheckS->getParent(); 832 } 833 } 834 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) { 835 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 836 // C99 DR 316 says that, if a function type comes from a 837 // function definition (without a prototype), that type is only 838 // used for checking compatibility. Therefore, when referencing 839 // the function, we pretend that we don't have the full function 840 // type. 841 if (DiagnoseUseOfDecl(Func, Loc)) 842 return ExprError(); 843 844 QualType T = Func->getType(); 845 QualType NoProtoType = T; 846 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType()) 847 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 848 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS); 849 } 850 } 851 852 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand); 853} 854/// \brief Cast member's object to its own class if necessary. 855bool 856Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) { 857 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member)) 858 if (CXXRecordDecl *RD = 859 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) { 860 QualType DestType = 861 Context.getCanonicalType(Context.getTypeDeclType(RD)); 862 if (DestType->isDependentType() || From->getType()->isDependentType()) 863 return false; 864 QualType FromRecordType = From->getType(); 865 QualType DestRecordType = DestType; 866 if (FromRecordType->getAs<PointerType>()) { 867 DestType = Context.getPointerType(DestType); 868 FromRecordType = FromRecordType->getPointeeType(); 869 } 870 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) && 871 CheckDerivedToBaseConversion(FromRecordType, 872 DestRecordType, 873 From->getSourceRange().getBegin(), 874 From->getSourceRange())) 875 return true; 876 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase, 877 /*isLvalue=*/true); 878 } 879 return false; 880} 881 882/// \brief Build a MemberExpr AST node. 883static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 884 const CXXScopeSpec *SS, NamedDecl *Member, 885 SourceLocation Loc, QualType Ty) { 886 if (SS && SS->isSet()) 887 return MemberExpr::Create(C, Base, isArrow, 888 (NestedNameSpecifier *)SS->getScopeRep(), 889 SS->getRange(), Member, Loc, 890 // FIXME: Explicit template argument lists 891 false, SourceLocation(), 0, 0, SourceLocation(), 892 Ty); 893 894 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty); 895} 896 897/// \brief Complete semantic analysis for a reference to the given declaration. 898Sema::OwningExprResult 899Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D, 900 bool HasTrailingLParen, 901 const CXXScopeSpec *SS, 902 bool isAddressOfOperand) { 903 assert(D && "Cannot refer to a NULL declaration"); 904 DeclarationName Name = D->getDeclName(); 905 906 // If this is an expression of the form &Class::member, don't build an 907 // implicit member ref, because we want a pointer to the member in general, 908 // not any specific instance's member. 909 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) { 910 DeclContext *DC = computeDeclContext(*SS); 911 if (D && isa<CXXRecordDecl>(DC)) { 912 QualType DType; 913 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 914 DType = FD->getType().getNonReferenceType(); 915 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 916 DType = Method->getType(); 917 } else if (isa<OverloadedFunctionDecl>(D)) { 918 DType = Context.OverloadTy; 919 } 920 // Could be an inner type. That's diagnosed below, so ignore it here. 921 if (!DType.isNull()) { 922 // The pointer is type- and value-dependent if it points into something 923 // dependent. 924 bool Dependent = DC->isDependentContext(); 925 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS); 926 } 927 } 928 } 929 930 // We may have found a field within an anonymous union or struct 931 // (C++ [class.union]). 932 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) 933 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 934 return BuildAnonymousStructUnionMemberReference(Loc, FD); 935 936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 937 if (!MD->isStatic()) { 938 // C++ [class.mfct.nonstatic]p2: 939 // [...] if name lookup (3.4.1) resolves the name in the 940 // id-expression to a nonstatic nontype member of class X or of 941 // a base class of X, the id-expression is transformed into a 942 // class member access expression (5.2.5) using (*this) (9.3.2) 943 // as the postfix-expression to the left of the '.' operator. 944 DeclContext *Ctx = 0; 945 QualType MemberType; 946 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 947 Ctx = FD->getDeclContext(); 948 MemberType = FD->getType(); 949 950 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>()) 951 MemberType = RefType->getPointeeType(); 952 else if (!FD->isMutable()) { 953 unsigned combinedQualifiers 954 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers(); 955 MemberType = MemberType.getQualifiedType(combinedQualifiers); 956 } 957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 958 if (!Method->isStatic()) { 959 Ctx = Method->getParent(); 960 MemberType = Method->getType(); 961 } 962 } else if (FunctionTemplateDecl *FunTmpl 963 = dyn_cast<FunctionTemplateDecl>(D)) { 964 if (CXXMethodDecl *Method 965 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) { 966 if (!Method->isStatic()) { 967 Ctx = Method->getParent(); 968 MemberType = Context.OverloadTy; 969 } 970 } 971 } else if (OverloadedFunctionDecl *Ovl 972 = dyn_cast<OverloadedFunctionDecl>(D)) { 973 // FIXME: We need an abstraction for iterating over one or more function 974 // templates or functions. This code is far too repetitive! 975 for (OverloadedFunctionDecl::function_iterator 976 Func = Ovl->function_begin(), 977 FuncEnd = Ovl->function_end(); 978 Func != FuncEnd; ++Func) { 979 CXXMethodDecl *DMethod = 0; 980 if (FunctionTemplateDecl *FunTmpl 981 = dyn_cast<FunctionTemplateDecl>(*Func)) 982 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 983 else 984 DMethod = dyn_cast<CXXMethodDecl>(*Func); 985 986 if (DMethod && !DMethod->isStatic()) { 987 Ctx = DMethod->getDeclContext(); 988 MemberType = Context.OverloadTy; 989 break; 990 } 991 } 992 } 993 994 if (Ctx && Ctx->isRecord()) { 995 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx)); 996 QualType ThisType = Context.getTagDeclType(MD->getParent()); 997 if ((Context.getCanonicalType(CtxType) 998 == Context.getCanonicalType(ThisType)) || 999 IsDerivedFrom(ThisType, CtxType)) { 1000 // Build the implicit member access expression. 1001 Expr *This = new (Context) CXXThisExpr(SourceLocation(), 1002 MD->getThisType(Context)); 1003 MarkDeclarationReferenced(Loc, D); 1004 if (PerformObjectMemberConversion(This, D)) 1005 return ExprError(); 1006 if (DiagnoseUseOfDecl(D, Loc)) 1007 return ExprError(); 1008 return Owned(BuildMemberExpr(Context, This, true, SS, D, 1009 Loc, MemberType)); 1010 } 1011 } 1012 } 1013 } 1014 1015 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 1017 if (MD->isStatic()) 1018 // "invalid use of member 'x' in static member function" 1019 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 1020 << FD->getDeclName()); 1021 } 1022 1023 // Any other ways we could have found the field in a well-formed 1024 // program would have been turned into implicit member expressions 1025 // above. 1026 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 1027 << FD->getDeclName()); 1028 } 1029 1030 if (isa<TypedefDecl>(D)) 1031 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name); 1032 if (isa<ObjCInterfaceDecl>(D)) 1033 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name); 1034 if (isa<NamespaceDecl>(D)) 1035 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name); 1036 1037 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 1038 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) 1039 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, 1040 false, false, SS); 1041 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 1042 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc, 1043 false, false, SS); 1044 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D)) 1045 return BuildDeclRefExpr(UD, Context.DependentTy, Loc, 1046 /*TypeDependent=*/true, 1047 /*ValueDependent=*/true, SS); 1048 1049 ValueDecl *VD = cast<ValueDecl>(D); 1050 1051 // Check whether this declaration can be used. Note that we suppress 1052 // this check when we're going to perform argument-dependent lookup 1053 // on this function name, because this might not be the function 1054 // that overload resolution actually selects. 1055 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 1056 HasTrailingLParen; 1057 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc)) 1058 return ExprError(); 1059 1060 // Only create DeclRefExpr's for valid Decl's. 1061 if (VD->isInvalidDecl()) 1062 return ExprError(); 1063 1064 // If the identifier reference is inside a block, and it refers to a value 1065 // that is outside the block, create a BlockDeclRefExpr instead of a 1066 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1067 // the block is formed. 1068 // 1069 // We do not do this for things like enum constants, global variables, etc, 1070 // as they do not get snapshotted. 1071 // 1072 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 1073 MarkDeclarationReferenced(Loc, VD); 1074 QualType ExprTy = VD->getType().getNonReferenceType(); 1075 // The BlocksAttr indicates the variable is bound by-reference. 1076 if (VD->getAttr<BlocksAttr>()) 1077 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1078 // This is to record that a 'const' was actually synthesize and added. 1079 bool constAdded = !ExprTy.isConstQualified(); 1080 // Variable will be bound by-copy, make it const within the closure. 1081 1082 ExprTy.addConst(); 1083 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false, 1084 constAdded)); 1085 } 1086 // If this reference is not in a block or if the referenced variable is 1087 // within the block, create a normal DeclRefExpr. 1088 1089 bool TypeDependent = false; 1090 bool ValueDependent = false; 1091 if (getLangOptions().CPlusPlus) { 1092 // C++ [temp.dep.expr]p3: 1093 // An id-expression is type-dependent if it contains: 1094 // - an identifier that was declared with a dependent type, 1095 if (VD->getType()->isDependentType()) 1096 TypeDependent = true; 1097 // - FIXME: a template-id that is dependent, 1098 // - a conversion-function-id that specifies a dependent type, 1099 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1100 Name.getCXXNameType()->isDependentType()) 1101 TypeDependent = true; 1102 // - a nested-name-specifier that contains a class-name that 1103 // names a dependent type. 1104 else if (SS && !SS->isEmpty()) { 1105 for (DeclContext *DC = computeDeclContext(*SS); 1106 DC; DC = DC->getParent()) { 1107 // FIXME: could stop early at namespace scope. 1108 if (DC->isRecord()) { 1109 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1110 if (Context.getTypeDeclType(Record)->isDependentType()) { 1111 TypeDependent = true; 1112 break; 1113 } 1114 } 1115 } 1116 } 1117 1118 // C++ [temp.dep.constexpr]p2: 1119 // 1120 // An identifier is value-dependent if it is: 1121 // - a name declared with a dependent type, 1122 if (TypeDependent) 1123 ValueDependent = true; 1124 // - the name of a non-type template parameter, 1125 else if (isa<NonTypeTemplateParmDecl>(VD)) 1126 ValueDependent = true; 1127 // - a constant with integral or enumeration type and is 1128 // initialized with an expression that is value-dependent 1129 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) { 1130 if (Dcl->getType().getCVRQualifiers() == QualType::Const && 1131 Dcl->getInit()) { 1132 ValueDependent = Dcl->getInit()->isValueDependent(); 1133 } 1134 } 1135 } 1136 1137 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, 1138 TypeDependent, ValueDependent, SS); 1139} 1140 1141Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1142 tok::TokenKind Kind) { 1143 PredefinedExpr::IdentType IT; 1144 1145 switch (Kind) { 1146 default: assert(0 && "Unknown simple primary expr!"); 1147 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1148 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1149 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1150 } 1151 1152 // Pre-defined identifiers are of type char[x], where x is the length of the 1153 // string. 1154 1155 Decl *currentDecl = getCurFunctionOrMethodDecl(); 1156 if (!currentDecl) { 1157 Diag(Loc, diag::ext_predef_outside_function); 1158 currentDecl = Context.getTranslationUnitDecl(); 1159 } 1160 1161 unsigned Length = 1162 PredefinedExpr::ComputeName(Context, IT, currentDecl).length(); 1163 1164 llvm::APInt LengthI(32, Length + 1); 1165 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 1166 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1167 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1168} 1169 1170Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1171 llvm::SmallString<16> CharBuffer; 1172 CharBuffer.resize(Tok.getLength()); 1173 const char *ThisTokBegin = &CharBuffer[0]; 1174 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1175 1176 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1177 Tok.getLocation(), PP); 1178 if (Literal.hadError()) 1179 return ExprError(); 1180 1181 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 1182 1183 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1184 Literal.isWide(), 1185 type, Tok.getLocation())); 1186} 1187 1188Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1189 // Fast path for a single digit (which is quite common). A single digit 1190 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1191 if (Tok.getLength() == 1) { 1192 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1193 unsigned IntSize = Context.Target.getIntWidth(); 1194 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1195 Context.IntTy, Tok.getLocation())); 1196 } 1197 1198 llvm::SmallString<512> IntegerBuffer; 1199 // Add padding so that NumericLiteralParser can overread by one character. 1200 IntegerBuffer.resize(Tok.getLength()+1); 1201 const char *ThisTokBegin = &IntegerBuffer[0]; 1202 1203 // Get the spelling of the token, which eliminates trigraphs, etc. 1204 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1205 1206 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1207 Tok.getLocation(), PP); 1208 if (Literal.hadError) 1209 return ExprError(); 1210 1211 Expr *Res; 1212 1213 if (Literal.isFloatingLiteral()) { 1214 QualType Ty; 1215 if (Literal.isFloat) 1216 Ty = Context.FloatTy; 1217 else if (!Literal.isLong) 1218 Ty = Context.DoubleTy; 1219 else 1220 Ty = Context.LongDoubleTy; 1221 1222 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1223 1224 // isExact will be set by GetFloatValue(). 1225 bool isExact = false; 1226 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact); 1227 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation()); 1228 1229 } else if (!Literal.isIntegerLiteral()) { 1230 return ExprError(); 1231 } else { 1232 QualType Ty; 1233 1234 // long long is a C99 feature. 1235 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1236 Literal.isLongLong) 1237 Diag(Tok.getLocation(), diag::ext_longlong); 1238 1239 // Get the value in the widest-possible width. 1240 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1241 1242 if (Literal.GetIntegerValue(ResultVal)) { 1243 // If this value didn't fit into uintmax_t, warn and force to ull. 1244 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1245 Ty = Context.UnsignedLongLongTy; 1246 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1247 "long long is not intmax_t?"); 1248 } else { 1249 // If this value fits into a ULL, try to figure out what else it fits into 1250 // according to the rules of C99 6.4.4.1p5. 1251 1252 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1253 // be an unsigned int. 1254 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1255 1256 // Check from smallest to largest, picking the smallest type we can. 1257 unsigned Width = 0; 1258 if (!Literal.isLong && !Literal.isLongLong) { 1259 // Are int/unsigned possibilities? 1260 unsigned IntSize = Context.Target.getIntWidth(); 1261 1262 // Does it fit in a unsigned int? 1263 if (ResultVal.isIntN(IntSize)) { 1264 // Does it fit in a signed int? 1265 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1266 Ty = Context.IntTy; 1267 else if (AllowUnsigned) 1268 Ty = Context.UnsignedIntTy; 1269 Width = IntSize; 1270 } 1271 } 1272 1273 // Are long/unsigned long possibilities? 1274 if (Ty.isNull() && !Literal.isLongLong) { 1275 unsigned LongSize = Context.Target.getLongWidth(); 1276 1277 // Does it fit in a unsigned long? 1278 if (ResultVal.isIntN(LongSize)) { 1279 // Does it fit in a signed long? 1280 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1281 Ty = Context.LongTy; 1282 else if (AllowUnsigned) 1283 Ty = Context.UnsignedLongTy; 1284 Width = LongSize; 1285 } 1286 } 1287 1288 // Finally, check long long if needed. 1289 if (Ty.isNull()) { 1290 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1291 1292 // Does it fit in a unsigned long long? 1293 if (ResultVal.isIntN(LongLongSize)) { 1294 // Does it fit in a signed long long? 1295 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1296 Ty = Context.LongLongTy; 1297 else if (AllowUnsigned) 1298 Ty = Context.UnsignedLongLongTy; 1299 Width = LongLongSize; 1300 } 1301 } 1302 1303 // If we still couldn't decide a type, we probably have something that 1304 // does not fit in a signed long long, but has no U suffix. 1305 if (Ty.isNull()) { 1306 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1307 Ty = Context.UnsignedLongLongTy; 1308 Width = Context.Target.getLongLongWidth(); 1309 } 1310 1311 if (ResultVal.getBitWidth() != Width) 1312 ResultVal.trunc(Width); 1313 } 1314 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1315 } 1316 1317 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1318 if (Literal.isImaginary) 1319 Res = new (Context) ImaginaryLiteral(Res, 1320 Context.getComplexType(Res->getType())); 1321 1322 return Owned(Res); 1323} 1324 1325Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1326 SourceLocation R, ExprArg Val) { 1327 Expr *E = Val.takeAs<Expr>(); 1328 assert((E != 0) && "ActOnParenExpr() missing expr"); 1329 return Owned(new (Context) ParenExpr(L, R, E)); 1330} 1331 1332/// The UsualUnaryConversions() function is *not* called by this routine. 1333/// See C99 6.3.2.1p[2-4] for more details. 1334bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1335 SourceLocation OpLoc, 1336 const SourceRange &ExprRange, 1337 bool isSizeof) { 1338 if (exprType->isDependentType()) 1339 return false; 1340 1341 // C99 6.5.3.4p1: 1342 if (isa<FunctionType>(exprType)) { 1343 // alignof(function) is allowed as an extension. 1344 if (isSizeof) 1345 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1346 return false; 1347 } 1348 1349 // Allow sizeof(void)/alignof(void) as an extension. 1350 if (exprType->isVoidType()) { 1351 Diag(OpLoc, diag::ext_sizeof_void_type) 1352 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1353 return false; 1354 } 1355 1356 if (RequireCompleteType(OpLoc, exprType, 1357 isSizeof ? diag::err_sizeof_incomplete_type : 1358 PDiag(diag::err_alignof_incomplete_type) 1359 << ExprRange)) 1360 return true; 1361 1362 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 1363 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) { 1364 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 1365 << exprType << isSizeof << ExprRange; 1366 return true; 1367 } 1368 1369 return false; 1370} 1371 1372bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1373 const SourceRange &ExprRange) { 1374 E = E->IgnoreParens(); 1375 1376 // alignof decl is always ok. 1377 if (isa<DeclRefExpr>(E)) 1378 return false; 1379 1380 // Cannot know anything else if the expression is dependent. 1381 if (E->isTypeDependent()) 1382 return false; 1383 1384 if (E->getBitField()) { 1385 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1386 return true; 1387 } 1388 1389 // Alignment of a field access is always okay, so long as it isn't a 1390 // bit-field. 1391 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1392 if (isa<FieldDecl>(ME->getMemberDecl())) 1393 return false; 1394 1395 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1396} 1397 1398/// \brief Build a sizeof or alignof expression given a type operand. 1399Action::OwningExprResult 1400Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc, 1401 bool isSizeOf, SourceRange R) { 1402 if (T.isNull()) 1403 return ExprError(); 1404 1405 if (!T->isDependentType() && 1406 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 1407 return ExprError(); 1408 1409 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1410 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T, 1411 Context.getSizeType(), OpLoc, 1412 R.getEnd())); 1413} 1414 1415/// \brief Build a sizeof or alignof expression given an expression 1416/// operand. 1417Action::OwningExprResult 1418Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 1419 bool isSizeOf, SourceRange R) { 1420 // Verify that the operand is valid. 1421 bool isInvalid = false; 1422 if (E->isTypeDependent()) { 1423 // Delay type-checking for type-dependent expressions. 1424 } else if (!isSizeOf) { 1425 isInvalid = CheckAlignOfExpr(E, OpLoc, R); 1426 } else if (E->getBitField()) { // C99 6.5.3.4p1. 1427 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1428 isInvalid = true; 1429 } else { 1430 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 1431 } 1432 1433 if (isInvalid) 1434 return ExprError(); 1435 1436 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1437 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 1438 Context.getSizeType(), OpLoc, 1439 R.getEnd())); 1440} 1441 1442/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1443/// the same for @c alignof and @c __alignof 1444/// Note that the ArgRange is invalid if isType is false. 1445Action::OwningExprResult 1446Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1447 void *TyOrEx, const SourceRange &ArgRange) { 1448 // If error parsing type, ignore. 1449 if (TyOrEx == 0) return ExprError(); 1450 1451 if (isType) { 1452 // FIXME: Preserve type source info. 1453 QualType ArgTy = GetTypeFromParser(TyOrEx); 1454 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange); 1455 } 1456 1457 // Get the end location. 1458 Expr *ArgEx = (Expr *)TyOrEx; 1459 Action::OwningExprResult Result 1460 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 1461 1462 if (Result.isInvalid()) 1463 DeleteExpr(ArgEx); 1464 1465 return move(Result); 1466} 1467 1468QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1469 if (V->isTypeDependent()) 1470 return Context.DependentTy; 1471 1472 // These operators return the element type of a complex type. 1473 if (const ComplexType *CT = V->getType()->getAsComplexType()) 1474 return CT->getElementType(); 1475 1476 // Otherwise they pass through real integer and floating point types here. 1477 if (V->getType()->isArithmeticType()) 1478 return V->getType(); 1479 1480 // Reject anything else. 1481 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1482 << (isReal ? "__real" : "__imag"); 1483 return QualType(); 1484} 1485 1486 1487 1488Action::OwningExprResult 1489Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1490 tok::TokenKind Kind, ExprArg Input) { 1491 // Since this might be a postfix expression, get rid of ParenListExprs. 1492 Input = MaybeConvertParenListExprToParenExpr(S, move(Input)); 1493 Expr *Arg = (Expr *)Input.get(); 1494 1495 UnaryOperator::Opcode Opc; 1496 switch (Kind) { 1497 default: assert(0 && "Unknown unary op!"); 1498 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1499 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1500 } 1501 1502 if (getLangOptions().CPlusPlus && 1503 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 1504 // Which overloaded operator? 1505 OverloadedOperatorKind OverOp = 1506 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 1507 1508 // C++ [over.inc]p1: 1509 // 1510 // [...] If the function is a member function with one 1511 // parameter (which shall be of type int) or a non-member 1512 // function with two parameters (the second of which shall be 1513 // of type int), it defines the postfix increment operator ++ 1514 // for objects of that type. When the postfix increment is 1515 // called as a result of using the ++ operator, the int 1516 // argument will have value zero. 1517 Expr *Args[2] = { 1518 Arg, 1519 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 1520 /*isSigned=*/true), Context.IntTy, SourceLocation()) 1521 }; 1522 1523 // Build the candidate set for overloading 1524 OverloadCandidateSet CandidateSet; 1525 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet); 1526 1527 // Perform overload resolution. 1528 OverloadCandidateSet::iterator Best; 1529 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 1530 case OR_Success: { 1531 // We found a built-in operator or an overloaded operator. 1532 FunctionDecl *FnDecl = Best->Function; 1533 1534 if (FnDecl) { 1535 // We matched an overloaded operator. Build a call to that 1536 // operator. 1537 1538 // Convert the arguments. 1539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1540 if (PerformObjectArgumentInitialization(Arg, Method)) 1541 return ExprError(); 1542 } else { 1543 // Convert the arguments. 1544 if (PerformCopyInitialization(Arg, 1545 FnDecl->getParamDecl(0)->getType(), 1546 "passing")) 1547 return ExprError(); 1548 } 1549 1550 // Determine the result type 1551 QualType ResultTy 1552 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1553 ResultTy = ResultTy.getNonReferenceType(); 1554 1555 // Build the actual expression node. 1556 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1557 SourceLocation()); 1558 UsualUnaryConversions(FnExpr); 1559 1560 Input.release(); 1561 Args[0] = Arg; 1562 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr, 1563 Args, 2, ResultTy, 1564 OpLoc)); 1565 } else { 1566 // We matched a built-in operator. Convert the arguments, then 1567 // break out so that we will build the appropriate built-in 1568 // operator node. 1569 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 1570 "passing")) 1571 return ExprError(); 1572 1573 break; 1574 } 1575 } 1576 1577 case OR_No_Viable_Function: 1578 // No viable function; fall through to handling this as a 1579 // built-in operator, which will produce an error message for us. 1580 break; 1581 1582 case OR_Ambiguous: 1583 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 1584 << UnaryOperator::getOpcodeStr(Opc) 1585 << Arg->getSourceRange(); 1586 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1587 return ExprError(); 1588 1589 case OR_Deleted: 1590 Diag(OpLoc, diag::err_ovl_deleted_oper) 1591 << Best->Function->isDeleted() 1592 << UnaryOperator::getOpcodeStr(Opc) 1593 << Arg->getSourceRange(); 1594 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1595 return ExprError(); 1596 } 1597 1598 // Either we found no viable overloaded operator or we matched a 1599 // built-in operator. In either case, fall through to trying to 1600 // build a built-in operation. 1601 } 1602 1603 Input.release(); 1604 Input = Arg; 1605 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input)); 1606} 1607 1608Action::OwningExprResult 1609Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 1610 ExprArg Idx, SourceLocation RLoc) { 1611 // Since this might be a postfix expression, get rid of ParenListExprs. 1612 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1613 1614 Expr *LHSExp = static_cast<Expr*>(Base.get()), 1615 *RHSExp = static_cast<Expr*>(Idx.get()); 1616 1617 if (getLangOptions().CPlusPlus && 1618 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 1619 Base.release(); 1620 Idx.release(); 1621 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1622 Context.DependentTy, RLoc)); 1623 } 1624 1625 if (getLangOptions().CPlusPlus && 1626 (LHSExp->getType()->isRecordType() || 1627 LHSExp->getType()->isEnumeralType() || 1628 RHSExp->getType()->isRecordType() || 1629 RHSExp->getType()->isEnumeralType())) { 1630 // Add the appropriate overloaded operators (C++ [over.match.oper]) 1631 // to the candidate set. 1632 OverloadCandidateSet CandidateSet; 1633 Expr *Args[2] = { LHSExp, RHSExp }; 1634 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet, 1635 SourceRange(LLoc, RLoc)); 1636 1637 // Perform overload resolution. 1638 OverloadCandidateSet::iterator Best; 1639 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 1640 case OR_Success: { 1641 // We found a built-in operator or an overloaded operator. 1642 FunctionDecl *FnDecl = Best->Function; 1643 1644 if (FnDecl) { 1645 // We matched an overloaded operator. Build a call to that 1646 // operator. 1647 1648 // Convert the arguments. 1649 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1650 if (PerformObjectArgumentInitialization(LHSExp, Method) || 1651 PerformCopyInitialization(RHSExp, 1652 FnDecl->getParamDecl(0)->getType(), 1653 "passing")) 1654 return ExprError(); 1655 } else { 1656 // Convert the arguments. 1657 if (PerformCopyInitialization(LHSExp, 1658 FnDecl->getParamDecl(0)->getType(), 1659 "passing") || 1660 PerformCopyInitialization(RHSExp, 1661 FnDecl->getParamDecl(1)->getType(), 1662 "passing")) 1663 return ExprError(); 1664 } 1665 1666 // Determine the result type 1667 QualType ResultTy 1668 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1669 ResultTy = ResultTy.getNonReferenceType(); 1670 1671 // Build the actual expression node. 1672 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1673 SourceLocation()); 1674 UsualUnaryConversions(FnExpr); 1675 1676 Base.release(); 1677 Idx.release(); 1678 Args[0] = LHSExp; 1679 Args[1] = RHSExp; 1680 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 1681 FnExpr, Args, 2, 1682 ResultTy, LLoc)); 1683 } else { 1684 // We matched a built-in operator. Convert the arguments, then 1685 // break out so that we will build the appropriate built-in 1686 // operator node. 1687 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 1688 "passing") || 1689 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 1690 "passing")) 1691 return ExprError(); 1692 1693 break; 1694 } 1695 } 1696 1697 case OR_No_Viable_Function: 1698 // No viable function; fall through to handling this as a 1699 // built-in operator, which will produce an error message for us. 1700 break; 1701 1702 case OR_Ambiguous: 1703 Diag(LLoc, diag::err_ovl_ambiguous_oper) 1704 << "[]" 1705 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1707 return ExprError(); 1708 1709 case OR_Deleted: 1710 Diag(LLoc, diag::err_ovl_deleted_oper) 1711 << Best->Function->isDeleted() 1712 << "[]" 1713 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1714 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1715 return ExprError(); 1716 } 1717 1718 // Either we found no viable overloaded operator or we matched a 1719 // built-in operator. In either case, fall through to trying to 1720 // build a built-in operation. 1721 } 1722 1723 // Perform default conversions. 1724 DefaultFunctionArrayConversion(LHSExp); 1725 DefaultFunctionArrayConversion(RHSExp); 1726 1727 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 1728 1729 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 1730 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 1731 // in the subscript position. As a result, we need to derive the array base 1732 // and index from the expression types. 1733 Expr *BaseExpr, *IndexExpr; 1734 QualType ResultType; 1735 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 1736 BaseExpr = LHSExp; 1737 IndexExpr = RHSExp; 1738 ResultType = Context.DependentTy; 1739 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 1740 BaseExpr = LHSExp; 1741 IndexExpr = RHSExp; 1742 ResultType = PTy->getPointeeType(); 1743 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 1744 // Handle the uncommon case of "123[Ptr]". 1745 BaseExpr = RHSExp; 1746 IndexExpr = LHSExp; 1747 ResultType = PTy->getPointeeType(); 1748 } else if (const ObjCObjectPointerType *PTy = 1749 LHSTy->getAsObjCObjectPointerType()) { 1750 BaseExpr = LHSExp; 1751 IndexExpr = RHSExp; 1752 ResultType = PTy->getPointeeType(); 1753 } else if (const ObjCObjectPointerType *PTy = 1754 RHSTy->getAsObjCObjectPointerType()) { 1755 // Handle the uncommon case of "123[Ptr]". 1756 BaseExpr = RHSExp; 1757 IndexExpr = LHSExp; 1758 ResultType = PTy->getPointeeType(); 1759 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 1760 BaseExpr = LHSExp; // vectors: V[123] 1761 IndexExpr = RHSExp; 1762 1763 // FIXME: need to deal with const... 1764 ResultType = VTy->getElementType(); 1765 } else if (LHSTy->isArrayType()) { 1766 // If we see an array that wasn't promoted by 1767 // DefaultFunctionArrayConversion, it must be an array that 1768 // wasn't promoted because of the C90 rule that doesn't 1769 // allow promoting non-lvalue arrays. Warn, then 1770 // force the promotion here. 1771 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1772 LHSExp->getSourceRange(); 1773 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy)); 1774 LHSTy = LHSExp->getType(); 1775 1776 BaseExpr = LHSExp; 1777 IndexExpr = RHSExp; 1778 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 1779 } else if (RHSTy->isArrayType()) { 1780 // Same as previous, except for 123[f().a] case 1781 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1782 RHSExp->getSourceRange(); 1783 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy)); 1784 RHSTy = RHSExp->getType(); 1785 1786 BaseExpr = RHSExp; 1787 IndexExpr = LHSExp; 1788 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 1789 } else { 1790 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 1791 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 1792 } 1793 // C99 6.5.2.1p1 1794 if (!(IndexExpr->getType()->isIntegerType() && 1795 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent()) 1796 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 1797 << IndexExpr->getSourceRange()); 1798 1799 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 1800 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 1801 // type. Note that Functions are not objects, and that (in C99 parlance) 1802 // incomplete types are not object types. 1803 if (ResultType->isFunctionType()) { 1804 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 1805 << ResultType << BaseExpr->getSourceRange(); 1806 return ExprError(); 1807 } 1808 1809 if (!ResultType->isDependentType() && 1810 RequireCompleteType(LLoc, ResultType, 1811 PDiag(diag::err_subscript_incomplete_type) 1812 << BaseExpr->getSourceRange())) 1813 return ExprError(); 1814 1815 // Diagnose bad cases where we step over interface counts. 1816 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 1817 Diag(LLoc, diag::err_subscript_nonfragile_interface) 1818 << ResultType << BaseExpr->getSourceRange(); 1819 return ExprError(); 1820 } 1821 1822 Base.release(); 1823 Idx.release(); 1824 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1825 ResultType, RLoc)); 1826} 1827 1828QualType Sema:: 1829CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1830 const IdentifierInfo *CompName, 1831 SourceLocation CompLoc) { 1832 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1833 1834 // The vector accessor can't exceed the number of elements. 1835 const char *compStr = CompName->getName(); 1836 1837 // This flag determines whether or not the component is one of the four 1838 // special names that indicate a subset of exactly half the elements are 1839 // to be selected. 1840 bool HalvingSwizzle = false; 1841 1842 // This flag determines whether or not CompName has an 's' char prefix, 1843 // indicating that it is a string of hex values to be used as vector indices. 1844 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 1845 1846 // Check that we've found one of the special components, or that the component 1847 // names must come from the same set. 1848 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1849 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 1850 HalvingSwizzle = true; 1851 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1852 do 1853 compStr++; 1854 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1855 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 1856 do 1857 compStr++; 1858 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 1859 } 1860 1861 if (!HalvingSwizzle && *compStr) { 1862 // We didn't get to the end of the string. This means the component names 1863 // didn't come from the same set *or* we encountered an illegal name. 1864 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1865 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1866 return QualType(); 1867 } 1868 1869 // Ensure no component accessor exceeds the width of the vector type it 1870 // operates on. 1871 if (!HalvingSwizzle) { 1872 compStr = CompName->getName(); 1873 1874 if (HexSwizzle) 1875 compStr++; 1876 1877 while (*compStr) { 1878 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 1879 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1880 << baseType << SourceRange(CompLoc); 1881 return QualType(); 1882 } 1883 } 1884 } 1885 1886 // If this is a halving swizzle, verify that the base type has an even 1887 // number of elements. 1888 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { 1889 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1890 << baseType << SourceRange(CompLoc); 1891 return QualType(); 1892 } 1893 1894 // The component accessor looks fine - now we need to compute the actual type. 1895 // The vector type is implied by the component accessor. For example, 1896 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1897 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 1898 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1899 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 1900 : CompName->getLength(); 1901 if (HexSwizzle) 1902 CompSize--; 1903 1904 if (CompSize == 1) 1905 return vecType->getElementType(); 1906 1907 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1908 // Now look up the TypeDefDecl from the vector type. Without this, 1909 // diagostics look bad. We want extended vector types to appear built-in. 1910 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1911 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1912 return Context.getTypedefType(ExtVectorDecls[i]); 1913 } 1914 return VT; // should never get here (a typedef type should always be found). 1915} 1916 1917static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 1918 IdentifierInfo *Member, 1919 const Selector &Sel, 1920 ASTContext &Context) { 1921 1922 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 1923 return PD; 1924 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 1925 return OMD; 1926 1927 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 1928 E = PDecl->protocol_end(); I != E; ++I) { 1929 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, 1930 Context)) 1931 return D; 1932 } 1933 return 0; 1934} 1935 1936static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy, 1937 IdentifierInfo *Member, 1938 const Selector &Sel, 1939 ASTContext &Context) { 1940 // Check protocols on qualified interfaces. 1941 Decl *GDecl = 0; 1942 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 1943 E = QIdTy->qual_end(); I != E; ++I) { 1944 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 1945 GDecl = PD; 1946 break; 1947 } 1948 // Also must look for a getter name which uses property syntax. 1949 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 1950 GDecl = OMD; 1951 break; 1952 } 1953 } 1954 if (!GDecl) { 1955 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 1956 E = QIdTy->qual_end(); I != E; ++I) { 1957 // Search in the protocol-qualifier list of current protocol. 1958 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); 1959 if (GDecl) 1960 return GDecl; 1961 } 1962 } 1963 return GDecl; 1964} 1965 1966/// FindMethodInNestedImplementations - Look up a method in current and 1967/// all base class implementations. 1968/// 1969ObjCMethodDecl *Sema::FindMethodInNestedImplementations( 1970 const ObjCInterfaceDecl *IFace, 1971 const Selector &Sel) { 1972 ObjCMethodDecl *Method = 0; 1973 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation()) 1974 Method = ImpDecl->getInstanceMethod(Sel); 1975 1976 if (!Method && IFace->getSuperClass()) 1977 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel); 1978 return Method; 1979} 1980 1981Action::OwningExprResult 1982Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 1983 tok::TokenKind OpKind, SourceLocation MemberLoc, 1984 DeclarationName MemberName, 1985 bool HasExplicitTemplateArgs, 1986 SourceLocation LAngleLoc, 1987 const TemplateArgument *ExplicitTemplateArgs, 1988 unsigned NumExplicitTemplateArgs, 1989 SourceLocation RAngleLoc, 1990 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS, 1991 NamedDecl *FirstQualifierInScope) { 1992 if (SS && SS->isInvalid()) 1993 return ExprError(); 1994 1995 // Since this might be a postfix expression, get rid of ParenListExprs. 1996 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1997 1998 Expr *BaseExpr = Base.takeAs<Expr>(); 1999 assert(BaseExpr && "no base expression"); 2000 2001 // Perform default conversions. 2002 DefaultFunctionArrayConversion(BaseExpr); 2003 2004 QualType BaseType = BaseExpr->getType(); 2005 // If this is an Objective-C pseudo-builtin and a definition is provided then 2006 // use that. 2007 if (BaseType->isObjCIdType()) { 2008 // We have an 'id' type. Rather than fall through, we check if this 2009 // is a reference to 'isa'. 2010 if (BaseType != Context.ObjCIdRedefinitionType) { 2011 BaseType = Context.ObjCIdRedefinitionType; 2012 ImpCastExprToType(BaseExpr, BaseType); 2013 } 2014 } else if (BaseType->isObjCClassType() && 2015 BaseType != Context.ObjCClassRedefinitionType) { 2016 BaseType = Context.ObjCClassRedefinitionType; 2017 ImpCastExprToType(BaseExpr, BaseType); 2018 } 2019 assert(!BaseType.isNull() && "no type for member expression"); 2020 2021 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 2022 // must have pointer type, and the accessed type is the pointee. 2023 if (OpKind == tok::arrow) { 2024 if (BaseType->isDependentType()) { 2025 NestedNameSpecifier *Qualifier = 0; 2026 if (SS) { 2027 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep()); 2028 if (!FirstQualifierInScope) 2029 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier); 2030 } 2031 2032 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true, 2033 OpLoc, Qualifier, 2034 SS? SS->getRange() : SourceRange(), 2035 FirstQualifierInScope, 2036 MemberName, 2037 MemberLoc, 2038 HasExplicitTemplateArgs, 2039 LAngleLoc, 2040 ExplicitTemplateArgs, 2041 NumExplicitTemplateArgs, 2042 RAngleLoc)); 2043 } 2044 else if (const PointerType *PT = BaseType->getAs<PointerType>()) 2045 BaseType = PT->getPointeeType(); 2046 else if (BaseType->isObjCObjectPointerType()) 2047 ; 2048 else 2049 return ExprError(Diag(MemberLoc, 2050 diag::err_typecheck_member_reference_arrow) 2051 << BaseType << BaseExpr->getSourceRange()); 2052 } else { 2053 if (BaseType->isDependentType()) { 2054 // Require that the base type isn't a pointer type 2055 // (so we'll report an error for) 2056 // T* t; 2057 // t.f; 2058 // 2059 // In Obj-C++, however, the above expression is valid, since it could be 2060 // accessing the 'f' property if T is an Obj-C interface. The extra check 2061 // allows this, while still reporting an error if T is a struct pointer. 2062 const PointerType *PT = BaseType->getAs<PointerType>(); 2063 2064 if (!PT || (getLangOptions().ObjC1 && 2065 !PT->getPointeeType()->isRecordType())) { 2066 NestedNameSpecifier *Qualifier = 0; 2067 if (SS) { 2068 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep()); 2069 if (!FirstQualifierInScope) 2070 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier); 2071 } 2072 2073 return Owned(CXXUnresolvedMemberExpr::Create(Context, 2074 BaseExpr, false, 2075 OpLoc, 2076 Qualifier, 2077 SS? SS->getRange() : SourceRange(), 2078 FirstQualifierInScope, 2079 MemberName, 2080 MemberLoc, 2081 HasExplicitTemplateArgs, 2082 LAngleLoc, 2083 ExplicitTemplateArgs, 2084 NumExplicitTemplateArgs, 2085 RAngleLoc)); 2086 } 2087 } 2088 } 2089 2090 // Handle field access to simple records. This also handles access to fields 2091 // of the ObjC 'id' struct. 2092 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 2093 RecordDecl *RDecl = RTy->getDecl(); 2094 if (RequireCompleteType(OpLoc, BaseType, 2095 PDiag(diag::err_typecheck_incomplete_tag) 2096 << BaseExpr->getSourceRange())) 2097 return ExprError(); 2098 2099 DeclContext *DC = RDecl; 2100 if (SS && SS->isSet()) { 2101 // If the member name was a qualified-id, look into the 2102 // nested-name-specifier. 2103 DC = computeDeclContext(*SS, false); 2104 2105 // FIXME: If DC is not computable, we should build a 2106 // CXXUnresolvedMemberExpr. 2107 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 2108 } 2109 2110 // The record definition is complete, now make sure the member is valid. 2111 LookupResult Result 2112 = LookupQualifiedName(DC, MemberName, LookupMemberName, false); 2113 2114 if (!Result) 2115 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated) 2116 << MemberName << BaseExpr->getSourceRange()); 2117 if (Result.isAmbiguous()) { 2118 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc, 2119 BaseExpr->getSourceRange()); 2120 return ExprError(); 2121 } 2122 2123 if (SS && SS->isSet()) { 2124 QualType BaseTypeCanon 2125 = Context.getCanonicalType(BaseType).getUnqualifiedType(); 2126 QualType MemberTypeCanon 2127 = Context.getCanonicalType( 2128 Context.getTypeDeclType( 2129 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext()))); 2130 2131 if (BaseTypeCanon != MemberTypeCanon && 2132 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon)) 2133 return ExprError(Diag(SS->getBeginLoc(), 2134 diag::err_not_direct_base_or_virtual) 2135 << MemberTypeCanon << BaseTypeCanon); 2136 } 2137 2138 NamedDecl *MemberDecl = Result; 2139 2140 // If the decl being referenced had an error, return an error for this 2141 // sub-expr without emitting another error, in order to avoid cascading 2142 // error cases. 2143 if (MemberDecl->isInvalidDecl()) 2144 return ExprError(); 2145 2146 // Check the use of this field 2147 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 2148 return ExprError(); 2149 2150 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2151 // We may have found a field within an anonymous union or struct 2152 // (C++ [class.union]). 2153 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 2154 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2155 BaseExpr, OpLoc); 2156 2157 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2158 QualType MemberType = FD->getType(); 2159 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) 2160 MemberType = Ref->getPointeeType(); 2161 else { 2162 unsigned BaseAddrSpace = BaseType.getAddressSpace(); 2163 unsigned combinedQualifiers = 2164 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 2165 if (FD->isMutable()) 2166 combinedQualifiers &= ~QualType::Const; 2167 MemberType = MemberType.getQualifiedType(combinedQualifiers); 2168 if (BaseAddrSpace != MemberType.getAddressSpace()) 2169 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace); 2170 } 2171 2172 MarkDeclarationReferenced(MemberLoc, FD); 2173 if (PerformObjectMemberConversion(BaseExpr, FD)) 2174 return ExprError(); 2175 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2176 FD, MemberLoc, MemberType)); 2177 } 2178 2179 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2180 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2181 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2182 Var, MemberLoc, 2183 Var->getType().getNonReferenceType())); 2184 } 2185 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2186 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2187 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2188 MemberFn, MemberLoc, 2189 MemberFn->getType())); 2190 } 2191 if (FunctionTemplateDecl *FunTmpl 2192 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) { 2193 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2194 2195 if (HasExplicitTemplateArgs) 2196 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow, 2197 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2198 SS? SS->getRange() : SourceRange(), 2199 FunTmpl, MemberLoc, true, 2200 LAngleLoc, ExplicitTemplateArgs, 2201 NumExplicitTemplateArgs, RAngleLoc, 2202 Context.OverloadTy)); 2203 2204 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2205 FunTmpl, MemberLoc, 2206 Context.OverloadTy)); 2207 } 2208 if (OverloadedFunctionDecl *Ovl 2209 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) { 2210 if (HasExplicitTemplateArgs) 2211 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow, 2212 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2213 SS? SS->getRange() : SourceRange(), 2214 Ovl, MemberLoc, true, 2215 LAngleLoc, ExplicitTemplateArgs, 2216 NumExplicitTemplateArgs, RAngleLoc, 2217 Context.OverloadTy)); 2218 2219 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2220 Ovl, MemberLoc, Context.OverloadTy)); 2221 } 2222 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2223 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2224 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2225 Enum, MemberLoc, Enum->getType())); 2226 } 2227 if (isa<TypeDecl>(MemberDecl)) 2228 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 2229 << MemberName << int(OpKind == tok::arrow)); 2230 2231 // We found a declaration kind that we didn't expect. This is a 2232 // generic error message that tells the user that she can't refer 2233 // to this member with '.' or '->'. 2234 return ExprError(Diag(MemberLoc, 2235 diag::err_typecheck_member_reference_unknown) 2236 << MemberName << int(OpKind == tok::arrow)); 2237 } 2238 2239 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring 2240 // into a record type was handled above, any destructor we see here is a 2241 // pseudo-destructor. 2242 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) { 2243 // C++ [expr.pseudo]p2: 2244 // The left hand side of the dot operator shall be of scalar type. The 2245 // left hand side of the arrow operator shall be of pointer to scalar 2246 // type. 2247 if (!BaseType->isScalarType()) 2248 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 2249 << BaseType << BaseExpr->getSourceRange()); 2250 2251 // [...] The type designated by the pseudo-destructor-name shall be the 2252 // same as the object type. 2253 if (!MemberName.getCXXNameType()->isDependentType() && 2254 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType())) 2255 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch) 2256 << BaseType << MemberName.getCXXNameType() 2257 << BaseExpr->getSourceRange() << SourceRange(MemberLoc)); 2258 2259 // [...] Furthermore, the two type-names in a pseudo-destructor-name of 2260 // the form 2261 // 2262 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name 2263 // 2264 // shall designate the same scalar type. 2265 // 2266 // FIXME: DPG can't see any way to trigger this particular clause, so it 2267 // isn't checked here. 2268 2269 // FIXME: We've lost the precise spelling of the type by going through 2270 // DeclarationName. Can we do better? 2271 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr, 2272 OpKind == tok::arrow, 2273 OpLoc, 2274 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2275 SS? SS->getRange() : SourceRange(), 2276 MemberName.getCXXNameType(), 2277 MemberLoc)); 2278 } 2279 2280 // Handle properties on ObjC 'Class' types. 2281 if (OpKind == tok::period && BaseType->isObjCClassType()) { 2282 // Also must look for a getter name which uses property syntax. 2283 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2284 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2285 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 2286 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 2287 ObjCMethodDecl *Getter; 2288 // FIXME: need to also look locally in the implementation. 2289 if ((Getter = IFace->lookupClassMethod(Sel))) { 2290 // Check the use of this method. 2291 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2292 return ExprError(); 2293 } 2294 // If we found a getter then this may be a valid dot-reference, we 2295 // will look for the matching setter, in case it is needed. 2296 Selector SetterSel = 2297 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2298 PP.getSelectorTable(), Member); 2299 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 2300 if (!Setter) { 2301 // If this reference is in an @implementation, also check for 'private' 2302 // methods. 2303 Setter = FindMethodInNestedImplementations(IFace, SetterSel); 2304 } 2305 // Look through local category implementations associated with the class. 2306 if (!Setter) 2307 Setter = IFace->getCategoryClassMethod(SetterSel); 2308 2309 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2310 return ExprError(); 2311 2312 if (Getter || Setter) { 2313 QualType PType; 2314 2315 if (Getter) 2316 PType = Getter->getResultType(); 2317 else 2318 // Get the expression type from Setter's incoming parameter. 2319 PType = (*(Setter->param_end() -1))->getType(); 2320 // FIXME: we must check that the setter has property type. 2321 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 2322 Setter, MemberLoc, BaseExpr)); 2323 } 2324 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2325 << MemberName << BaseType); 2326 } 2327 } 2328 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 2329 // (*Obj).ivar. 2330 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) || 2331 (OpKind == tok::period && BaseType->isObjCInterfaceType())) { 2332 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType(); 2333 const ObjCInterfaceType *IFaceT = 2334 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType(); 2335 if (IFaceT) { 2336 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2337 2338 ObjCInterfaceDecl *IDecl = IFaceT->getDecl(); 2339 ObjCInterfaceDecl *ClassDeclared; 2340 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 2341 2342 if (IV) { 2343 // If the decl being referenced had an error, return an error for this 2344 // sub-expr without emitting another error, in order to avoid cascading 2345 // error cases. 2346 if (IV->isInvalidDecl()) 2347 return ExprError(); 2348 2349 // Check whether we can reference this field. 2350 if (DiagnoseUseOfDecl(IV, MemberLoc)) 2351 return ExprError(); 2352 if (IV->getAccessControl() != ObjCIvarDecl::Public && 2353 IV->getAccessControl() != ObjCIvarDecl::Package) { 2354 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 2355 if (ObjCMethodDecl *MD = getCurMethodDecl()) 2356 ClassOfMethodDecl = MD->getClassInterface(); 2357 else if (ObjCImpDecl && getCurFunctionDecl()) { 2358 // Case of a c-function declared inside an objc implementation. 2359 // FIXME: For a c-style function nested inside an objc implementation 2360 // class, there is no implementation context available, so we pass 2361 // down the context as argument to this routine. Ideally, this context 2362 // need be passed down in the AST node and somehow calculated from the 2363 // AST for a function decl. 2364 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>(); 2365 if (ObjCImplementationDecl *IMPD = 2366 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 2367 ClassOfMethodDecl = IMPD->getClassInterface(); 2368 else if (ObjCCategoryImplDecl* CatImplClass = 2369 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 2370 ClassOfMethodDecl = CatImplClass->getClassInterface(); 2371 } 2372 2373 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 2374 if (ClassDeclared != IDecl || 2375 ClassOfMethodDecl != ClassDeclared) 2376 Diag(MemberLoc, diag::error_private_ivar_access) 2377 << IV->getDeclName(); 2378 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 2379 // @protected 2380 Diag(MemberLoc, diag::error_protected_ivar_access) 2381 << IV->getDeclName(); 2382 } 2383 2384 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2385 MemberLoc, BaseExpr, 2386 OpKind == tok::arrow)); 2387 } 2388 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 2389 << IDecl->getDeclName() << MemberName 2390 << BaseExpr->getSourceRange()); 2391 } 2392 } 2393 // Handle properties on 'id' and qualified "id". 2394 if (OpKind == tok::period && (BaseType->isObjCIdType() || 2395 BaseType->isObjCQualifiedIdType())) { 2396 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType(); 2397 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2398 2399 // Check protocols on qualified interfaces. 2400 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2401 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { 2402 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 2403 // Check the use of this declaration 2404 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2405 return ExprError(); 2406 2407 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2408 MemberLoc, BaseExpr)); 2409 } 2410 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 2411 // Check the use of this method. 2412 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 2413 return ExprError(); 2414 2415 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 2416 OMD->getResultType(), 2417 OMD, OpLoc, MemberLoc, 2418 NULL, 0)); 2419 } 2420 } 2421 2422 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2423 << MemberName << BaseType); 2424 } 2425 // Handle Objective-C property access, which is "Obj.property" where Obj is a 2426 // pointer to a (potentially qualified) interface type. 2427 const ObjCObjectPointerType *OPT; 2428 if (OpKind == tok::period && 2429 (OPT = BaseType->getAsObjCInterfacePointerType())) { 2430 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 2431 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 2432 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2433 2434 // Search for a declared property first. 2435 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 2436 // Check whether we can reference this property. 2437 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2438 return ExprError(); 2439 QualType ResTy = PD->getType(); 2440 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2441 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2442 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)) 2443 ResTy = Getter->getResultType(); 2444 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 2445 MemberLoc, BaseExpr)); 2446 } 2447 // Check protocols on qualified interfaces. 2448 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 2449 E = OPT->qual_end(); I != E; ++I) 2450 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2451 // Check whether we can reference this property. 2452 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2453 return ExprError(); 2454 2455 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2456 MemberLoc, BaseExpr)); 2457 } 2458 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 2459 E = OPT->qual_end(); I != E; ++I) 2460 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2461 // Check whether we can reference this property. 2462 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2463 return ExprError(); 2464 2465 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2466 MemberLoc, BaseExpr)); 2467 } 2468 // If that failed, look for an "implicit" property by seeing if the nullary 2469 // selector is implemented. 2470 2471 // FIXME: The logic for looking up nullary and unary selectors should be 2472 // shared with the code in ActOnInstanceMessage. 2473 2474 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2475 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2476 2477 // If this reference is in an @implementation, check for 'private' methods. 2478 if (!Getter) 2479 Getter = FindMethodInNestedImplementations(IFace, Sel); 2480 2481 // Look through local category implementations associated with the class. 2482 if (!Getter) 2483 Getter = IFace->getCategoryInstanceMethod(Sel); 2484 if (Getter) { 2485 // Check if we can reference this property. 2486 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2487 return ExprError(); 2488 } 2489 // If we found a getter then this may be a valid dot-reference, we 2490 // will look for the matching setter, in case it is needed. 2491 Selector SetterSel = 2492 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2493 PP.getSelectorTable(), Member); 2494 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 2495 if (!Setter) { 2496 // If this reference is in an @implementation, also check for 'private' 2497 // methods. 2498 Setter = FindMethodInNestedImplementations(IFace, SetterSel); 2499 } 2500 // Look through local category implementations associated with the class. 2501 if (!Setter) 2502 Setter = IFace->getCategoryInstanceMethod(SetterSel); 2503 2504 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2505 return ExprError(); 2506 2507 if (Getter || Setter) { 2508 QualType PType; 2509 2510 if (Getter) 2511 PType = Getter->getResultType(); 2512 else 2513 // Get the expression type from Setter's incoming parameter. 2514 PType = (*(Setter->param_end() -1))->getType(); 2515 // FIXME: we must check that the setter has property type. 2516 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 2517 Setter, MemberLoc, BaseExpr)); 2518 } 2519 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2520 << MemberName << BaseType); 2521 } 2522 2523 // Handle the following exceptional case (*Obj).isa. 2524 if (OpKind == tok::period && 2525 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) && 2526 MemberName.getAsIdentifierInfo()->isStr("isa")) 2527 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc, 2528 Context.getObjCIdType())); 2529 2530 // Handle 'field access' to vectors, such as 'V.xx'. 2531 if (BaseType->isExtVectorType()) { 2532 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2533 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 2534 if (ret.isNull()) 2535 return ExprError(); 2536 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member, 2537 MemberLoc)); 2538 } 2539 2540 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 2541 << BaseType << BaseExpr->getSourceRange(); 2542 2543 // If the user is trying to apply -> or . to a function or function 2544 // pointer, it's probably because they forgot parentheses to call 2545 // the function. Suggest the addition of those parentheses. 2546 if (BaseType == Context.OverloadTy || 2547 BaseType->isFunctionType() || 2548 (BaseType->isPointerType() && 2549 BaseType->getAs<PointerType>()->isFunctionType())) { 2550 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 2551 Diag(Loc, diag::note_member_reference_needs_call) 2552 << CodeModificationHint::CreateInsertion(Loc, "()"); 2553 } 2554 2555 return ExprError(); 2556} 2557 2558Action::OwningExprResult 2559Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 2560 tok::TokenKind OpKind, SourceLocation MemberLoc, 2561 IdentifierInfo &Member, 2562 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) { 2563 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc, 2564 DeclarationName(&Member), ObjCImpDecl, SS); 2565} 2566 2567Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 2568 FunctionDecl *FD, 2569 ParmVarDecl *Param) { 2570 if (Param->hasUnparsedDefaultArg()) { 2571 Diag (CallLoc, 2572 diag::err_use_of_default_argument_to_function_declared_later) << 2573 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 2574 Diag(UnparsedDefaultArgLocs[Param], 2575 diag::note_default_argument_declared_here); 2576 } else { 2577 if (Param->hasUninstantiatedDefaultArg()) { 2578 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 2579 2580 // Instantiate the expression. 2581 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD); 2582 2583 InstantiatingTemplate Inst(*this, CallLoc, Param, 2584 ArgList.getInnermost().getFlatArgumentList(), 2585 ArgList.getInnermost().flat_size()); 2586 2587 OwningExprResult Result = SubstExpr(UninstExpr, ArgList); 2588 if (Result.isInvalid()) 2589 return ExprError(); 2590 2591 if (SetParamDefaultArgument(Param, move(Result), 2592 /*FIXME:EqualLoc*/ 2593 UninstExpr->getSourceRange().getBegin())) 2594 return ExprError(); 2595 } 2596 2597 Expr *DefaultExpr = Param->getDefaultArg(); 2598 2599 // If the default expression creates temporaries, we need to 2600 // push them to the current stack of expression temporaries so they'll 2601 // be properly destroyed. 2602 if (CXXExprWithTemporaries *E 2603 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) { 2604 assert(!E->shouldDestroyTemporaries() && 2605 "Can't destroy temporaries in a default argument expr!"); 2606 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) 2607 ExprTemporaries.push_back(E->getTemporary(I)); 2608 } 2609 } 2610 2611 // We already type-checked the argument, so we know it works. 2612 return Owned(CXXDefaultArgExpr::Create(Context, Param)); 2613} 2614 2615/// ConvertArgumentsForCall - Converts the arguments specified in 2616/// Args/NumArgs to the parameter types of the function FDecl with 2617/// function prototype Proto. Call is the call expression itself, and 2618/// Fn is the function expression. For a C++ member function, this 2619/// routine does not attempt to convert the object argument. Returns 2620/// true if the call is ill-formed. 2621bool 2622Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2623 FunctionDecl *FDecl, 2624 const FunctionProtoType *Proto, 2625 Expr **Args, unsigned NumArgs, 2626 SourceLocation RParenLoc) { 2627 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2628 // assignment, to the types of the corresponding parameter, ... 2629 unsigned NumArgsInProto = Proto->getNumArgs(); 2630 unsigned NumArgsToCheck = NumArgs; 2631 bool Invalid = false; 2632 2633 // If too few arguments are available (and we don't have default 2634 // arguments for the remaining parameters), don't make the call. 2635 if (NumArgs < NumArgsInProto) { 2636 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2637 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2638 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2639 // Use default arguments for missing arguments 2640 NumArgsToCheck = NumArgsInProto; 2641 Call->setNumArgs(Context, NumArgsInProto); 2642 } 2643 2644 // If too many are passed and not variadic, error on the extras and drop 2645 // them. 2646 if (NumArgs > NumArgsInProto) { 2647 if (!Proto->isVariadic()) { 2648 Diag(Args[NumArgsInProto]->getLocStart(), 2649 diag::err_typecheck_call_too_many_args) 2650 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2651 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2652 Args[NumArgs-1]->getLocEnd()); 2653 // This deletes the extra arguments. 2654 Call->setNumArgs(Context, NumArgsInProto); 2655 Invalid = true; 2656 } 2657 NumArgsToCheck = NumArgsInProto; 2658 } 2659 2660 // Continue to check argument types (even if we have too few/many args). 2661 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2662 QualType ProtoArgType = Proto->getArgType(i); 2663 2664 Expr *Arg; 2665 if (i < NumArgs) { 2666 Arg = Args[i]; 2667 2668 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2669 ProtoArgType, 2670 PDiag(diag::err_call_incomplete_argument) 2671 << Arg->getSourceRange())) 2672 return true; 2673 2674 // Pass the argument. 2675 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2676 return true; 2677 } else { 2678 ParmVarDecl *Param = FDecl->getParamDecl(i); 2679 2680 OwningExprResult ArgExpr = 2681 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(), 2682 FDecl, Param); 2683 if (ArgExpr.isInvalid()) 2684 return true; 2685 2686 Arg = ArgExpr.takeAs<Expr>(); 2687 } 2688 2689 Call->setArg(i, Arg); 2690 } 2691 2692 // If this is a variadic call, handle args passed through "...". 2693 if (Proto->isVariadic()) { 2694 VariadicCallType CallType = VariadicFunction; 2695 if (Fn->getType()->isBlockPointerType()) 2696 CallType = VariadicBlock; // Block 2697 else if (isa<MemberExpr>(Fn)) 2698 CallType = VariadicMethod; 2699 2700 // Promote the arguments (C99 6.5.2.2p7). 2701 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2702 Expr *Arg = Args[i]; 2703 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType); 2704 Call->setArg(i, Arg); 2705 } 2706 } 2707 2708 return Invalid; 2709} 2710 2711/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2712/// This provides the location of the left/right parens and a list of comma 2713/// locations. 2714Action::OwningExprResult 2715Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2716 MultiExprArg args, 2717 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2718 unsigned NumArgs = args.size(); 2719 2720 // Since this might be a postfix expression, get rid of ParenListExprs. 2721 fn = MaybeConvertParenListExprToParenExpr(S, move(fn)); 2722 2723 Expr *Fn = fn.takeAs<Expr>(); 2724 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2725 assert(Fn && "no function call expression"); 2726 FunctionDecl *FDecl = NULL; 2727 NamedDecl *NDecl = NULL; 2728 DeclarationName UnqualifiedName; 2729 2730 if (getLangOptions().CPlusPlus) { 2731 // If this is a pseudo-destructor expression, build the call immediately. 2732 if (isa<CXXPseudoDestructorExpr>(Fn)) { 2733 if (NumArgs > 0) { 2734 // Pseudo-destructor calls should not have any arguments. 2735 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 2736 << CodeModificationHint::CreateRemoval( 2737 SourceRange(Args[0]->getLocStart(), 2738 Args[NumArgs-1]->getLocEnd())); 2739 2740 for (unsigned I = 0; I != NumArgs; ++I) 2741 Args[I]->Destroy(Context); 2742 2743 NumArgs = 0; 2744 } 2745 2746 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 2747 RParenLoc)); 2748 } 2749 2750 // Determine whether this is a dependent call inside a C++ template, 2751 // in which case we won't do any semantic analysis now. 2752 // FIXME: Will need to cache the results of name lookup (including ADL) in 2753 // Fn. 2754 bool Dependent = false; 2755 if (Fn->isTypeDependent()) 2756 Dependent = true; 2757 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2758 Dependent = true; 2759 2760 if (Dependent) 2761 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2762 Context.DependentTy, RParenLoc)); 2763 2764 // Determine whether this is a call to an object (C++ [over.call.object]). 2765 if (Fn->getType()->isRecordType()) 2766 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2767 CommaLocs, RParenLoc)); 2768 2769 // Determine whether this is a call to a member function. 2770 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) { 2771 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 2772 if (isa<OverloadedFunctionDecl>(MemDecl) || 2773 isa<CXXMethodDecl>(MemDecl) || 2774 (isa<FunctionTemplateDecl>(MemDecl) && 2775 isa<CXXMethodDecl>( 2776 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl()))) 2777 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2778 CommaLocs, RParenLoc)); 2779 } 2780 } 2781 2782 // If we're directly calling a function, get the appropriate declaration. 2783 // Also, in C++, keep track of whether we should perform argument-dependent 2784 // lookup and whether there were any explicitly-specified template arguments. 2785 Expr *FnExpr = Fn; 2786 bool ADL = true; 2787 bool HasExplicitTemplateArgs = 0; 2788 const TemplateArgument *ExplicitTemplateArgs = 0; 2789 unsigned NumExplicitTemplateArgs = 0; 2790 while (true) { 2791 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2792 FnExpr = IcExpr->getSubExpr(); 2793 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2794 // Parentheses around a function disable ADL 2795 // (C++0x [basic.lookup.argdep]p1). 2796 ADL = false; 2797 FnExpr = PExpr->getSubExpr(); 2798 } else if (isa<UnaryOperator>(FnExpr) && 2799 cast<UnaryOperator>(FnExpr)->getOpcode() 2800 == UnaryOperator::AddrOf) { 2801 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2802 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) { 2803 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). 2804 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); 2805 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl()); 2806 break; 2807 } else if (UnresolvedFunctionNameExpr *DepName 2808 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { 2809 UnqualifiedName = DepName->getName(); 2810 break; 2811 } else if (TemplateIdRefExpr *TemplateIdRef 2812 = dyn_cast<TemplateIdRefExpr>(FnExpr)) { 2813 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl(); 2814 if (!NDecl) 2815 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl(); 2816 HasExplicitTemplateArgs = true; 2817 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs(); 2818 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs(); 2819 2820 // C++ [temp.arg.explicit]p6: 2821 // [Note: For simple function names, argument dependent lookup (3.4.2) 2822 // applies even when the function name is not visible within the 2823 // scope of the call. This is because the call still has the syntactic 2824 // form of a function call (3.4.1). But when a function template with 2825 // explicit template arguments is used, the call does not have the 2826 // correct syntactic form unless there is a function template with 2827 // that name visible at the point of the call. If no such name is 2828 // visible, the call is not syntactically well-formed and 2829 // argument-dependent lookup does not apply. If some such name is 2830 // visible, argument dependent lookup applies and additional function 2831 // templates may be found in other namespaces. 2832 // 2833 // The summary of this paragraph is that, if we get to this point and the 2834 // template-id was not a qualified name, then argument-dependent lookup 2835 // is still possible. 2836 if (TemplateIdRef->getQualifier()) 2837 ADL = false; 2838 break; 2839 } else { 2840 // Any kind of name that does not refer to a declaration (or 2841 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). 2842 ADL = false; 2843 break; 2844 } 2845 } 2846 2847 OverloadedFunctionDecl *Ovl = 0; 2848 FunctionTemplateDecl *FunctionTemplate = 0; 2849 if (NDecl) { 2850 FDecl = dyn_cast<FunctionDecl>(NDecl); 2851 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl))) 2852 FDecl = FunctionTemplate->getTemplatedDecl(); 2853 else 2854 FDecl = dyn_cast<FunctionDecl>(NDecl); 2855 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl); 2856 } 2857 2858 if (Ovl || FunctionTemplate || 2859 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { 2860 // We don't perform ADL for implicit declarations of builtins. 2861 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) 2862 ADL = false; 2863 2864 // We don't perform ADL in C. 2865 if (!getLangOptions().CPlusPlus) 2866 ADL = false; 2867 2868 if (Ovl || FunctionTemplate || ADL) { 2869 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName, 2870 HasExplicitTemplateArgs, 2871 ExplicitTemplateArgs, 2872 NumExplicitTemplateArgs, 2873 LParenLoc, Args, NumArgs, CommaLocs, 2874 RParenLoc, ADL); 2875 if (!FDecl) 2876 return ExprError(); 2877 2878 // Update Fn to refer to the actual function selected. 2879 Expr *NewFn = 0; 2880 if (QualifiedDeclRefExpr *QDRExpr 2881 = dyn_cast<QualifiedDeclRefExpr>(FnExpr)) 2882 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), 2883 QDRExpr->getLocation(), 2884 false, false, 2885 QDRExpr->getQualifierRange(), 2886 QDRExpr->getQualifier()); 2887 else 2888 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), 2889 Fn->getSourceRange().getBegin()); 2890 Fn->Destroy(Context); 2891 Fn = NewFn; 2892 } 2893 } 2894 2895 // Promote the function operand. 2896 UsualUnaryConversions(Fn); 2897 2898 // Make the call expr early, before semantic checks. This guarantees cleanup 2899 // of arguments and function on error. 2900 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2901 Args, NumArgs, 2902 Context.BoolTy, 2903 RParenLoc)); 2904 2905 const FunctionType *FuncT; 2906 if (!Fn->getType()->isBlockPointerType()) { 2907 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2908 // have type pointer to function". 2909 const PointerType *PT = Fn->getType()->getAs<PointerType>(); 2910 if (PT == 0) 2911 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2912 << Fn->getType() << Fn->getSourceRange()); 2913 FuncT = PT->getPointeeType()->getAsFunctionType(); 2914 } else { // This is a block call. 2915 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()-> 2916 getAsFunctionType(); 2917 } 2918 if (FuncT == 0) 2919 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2920 << Fn->getType() << Fn->getSourceRange()); 2921 2922 // Check for a valid return type 2923 if (!FuncT->getResultType()->isVoidType() && 2924 RequireCompleteType(Fn->getSourceRange().getBegin(), 2925 FuncT->getResultType(), 2926 PDiag(diag::err_call_incomplete_return) 2927 << TheCall->getSourceRange())) 2928 return ExprError(); 2929 2930 // We know the result type of the call, set it. 2931 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2932 2933 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2934 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2935 RParenLoc)) 2936 return ExprError(); 2937 } else { 2938 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2939 2940 if (FDecl) { 2941 // Check if we have too few/too many template arguments, based 2942 // on our knowledge of the function definition. 2943 const FunctionDecl *Def = 0; 2944 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) { 2945 const FunctionProtoType *Proto = 2946 Def->getType()->getAsFunctionProtoType(); 2947 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 2948 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 2949 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 2950 } 2951 } 2952 } 2953 2954 // Promote the arguments (C99 6.5.2.2p6). 2955 for (unsigned i = 0; i != NumArgs; i++) { 2956 Expr *Arg = Args[i]; 2957 DefaultArgumentPromotion(Arg); 2958 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2959 Arg->getType(), 2960 PDiag(diag::err_call_incomplete_argument) 2961 << Arg->getSourceRange())) 2962 return ExprError(); 2963 TheCall->setArg(i, Arg); 2964 } 2965 } 2966 2967 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2968 if (!Method->isStatic()) 2969 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2970 << Fn->getSourceRange()); 2971 2972 // Check for sentinels 2973 if (NDecl) 2974 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 2975 2976 // Do special checking on direct calls to functions. 2977 if (FDecl) { 2978 if (CheckFunctionCall(FDecl, TheCall.get())) 2979 return ExprError(); 2980 2981 if (unsigned BuiltinID = FDecl->getBuiltinID(Context)) 2982 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take()); 2983 } else if (NDecl) { 2984 if (CheckBlockCall(NDecl, TheCall.get())) 2985 return ExprError(); 2986 } 2987 2988 return MaybeBindToTemporary(TheCall.take()); 2989} 2990 2991Action::OwningExprResult 2992Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 2993 SourceLocation RParenLoc, ExprArg InitExpr) { 2994 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 2995 //FIXME: Preserve type source info. 2996 QualType literalType = GetTypeFromParser(Ty); 2997 // FIXME: put back this assert when initializers are worked out. 2998 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 2999 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 3000 3001 if (literalType->isArrayType()) { 3002 if (literalType->isVariableArrayType()) 3003 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3004 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3005 } else if (!literalType->isDependentType() && 3006 RequireCompleteType(LParenLoc, literalType, 3007 PDiag(diag::err_typecheck_decl_incomplete_type) 3008 << SourceRange(LParenLoc, 3009 literalExpr->getSourceRange().getEnd()))) 3010 return ExprError(); 3011 3012 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 3013 DeclarationName(), /*FIXME:DirectInit=*/false)) 3014 return ExprError(); 3015 3016 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3017 if (isFileScope) { // 6.5.2.5p3 3018 if (CheckForConstantInitializer(literalExpr, literalType)) 3019 return ExprError(); 3020 } 3021 InitExpr.release(); 3022 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 3023 literalExpr, isFileScope)); 3024} 3025 3026Action::OwningExprResult 3027Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3028 SourceLocation RBraceLoc) { 3029 unsigned NumInit = initlist.size(); 3030 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 3031 3032 // Semantic analysis for initializers is done by ActOnDeclarator() and 3033 // CheckInitializer() - it requires knowledge of the object being intialized. 3034 3035 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 3036 RBraceLoc); 3037 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3038 return Owned(E); 3039} 3040 3041/// CheckCastTypes - Check type constraints for casting between types. 3042bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr, 3043 CastExpr::CastKind& Kind, 3044 CXXMethodDecl *& ConversionDecl, 3045 bool FunctionalStyle) { 3046 if (getLangOptions().CPlusPlus) 3047 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle, 3048 ConversionDecl); 3049 3050 DefaultFunctionArrayConversion(castExpr); 3051 3052 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3053 // type needs to be scalar. 3054 if (castType->isVoidType()) { 3055 // Cast to void allows any expr type. 3056 } else if (!castType->isScalarType() && !castType->isVectorType()) { 3057 if (Context.getCanonicalType(castType).getUnqualifiedType() == 3058 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && 3059 (castType->isStructureType() || castType->isUnionType())) { 3060 // GCC struct/union extension: allow cast to self. 3061 // FIXME: Check that the cast destination type is complete. 3062 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3063 << castType << castExpr->getSourceRange(); 3064 Kind = CastExpr::CK_NoOp; 3065 } else if (castType->isUnionType()) { 3066 // GCC cast to union extension 3067 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 3068 RecordDecl::field_iterator Field, FieldEnd; 3069 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 3070 Field != FieldEnd; ++Field) { 3071 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == 3072 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { 3073 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 3074 << castExpr->getSourceRange(); 3075 break; 3076 } 3077 } 3078 if (Field == FieldEnd) 3079 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 3080 << castExpr->getType() << castExpr->getSourceRange(); 3081 Kind = CastExpr::CK_ToUnion; 3082 } else { 3083 // Reject any other conversions to non-scalar types. 3084 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 3085 << castType << castExpr->getSourceRange(); 3086 } 3087 } else if (!castExpr->getType()->isScalarType() && 3088 !castExpr->getType()->isVectorType()) { 3089 return Diag(castExpr->getLocStart(), 3090 diag::err_typecheck_expect_scalar_operand) 3091 << castExpr->getType() << castExpr->getSourceRange(); 3092 } else if (castType->isExtVectorType()) { 3093 if (CheckExtVectorCast(TyR, castType, castExpr->getType())) 3094 return true; 3095 } else if (castType->isVectorType()) { 3096 if (CheckVectorCast(TyR, castType, castExpr->getType())) 3097 return true; 3098 } else if (castExpr->getType()->isVectorType()) { 3099 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 3100 return true; 3101 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { 3102 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 3103 } else if (!castType->isArithmeticType()) { 3104 QualType castExprType = castExpr->getType(); 3105 if (!castExprType->isIntegralType() && castExprType->isArithmeticType()) 3106 return Diag(castExpr->getLocStart(), 3107 diag::err_cast_pointer_from_non_pointer_int) 3108 << castExprType << castExpr->getSourceRange(); 3109 } else if (!castExpr->getType()->isArithmeticType()) { 3110 if (!castType->isIntegralType() && castType->isArithmeticType()) 3111 return Diag(castExpr->getLocStart(), 3112 diag::err_cast_pointer_to_non_pointer_int) 3113 << castType << castExpr->getSourceRange(); 3114 } 3115 if (isa<ObjCSelectorExpr>(castExpr)) 3116 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 3117 return false; 3118} 3119 3120bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 3121 assert(VectorTy->isVectorType() && "Not a vector type!"); 3122 3123 if (Ty->isVectorType() || Ty->isIntegerType()) { 3124 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 3125 return Diag(R.getBegin(), 3126 Ty->isVectorType() ? 3127 diag::err_invalid_conversion_between_vectors : 3128 diag::err_invalid_conversion_between_vector_and_integer) 3129 << VectorTy << Ty << R; 3130 } else 3131 return Diag(R.getBegin(), 3132 diag::err_invalid_conversion_between_vector_and_scalar) 3133 << VectorTy << Ty << R; 3134 3135 return false; 3136} 3137 3138bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) { 3139 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 3140 3141 // If SrcTy is a VectorType, the total size must match to explicitly cast to 3142 // an ExtVectorType. 3143 if (SrcTy->isVectorType()) { 3144 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 3145 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 3146 << DestTy << SrcTy << R; 3147 return false; 3148 } 3149 3150 // All non-pointer scalars can be cast to ExtVector type. The appropriate 3151 // conversion will take place first from scalar to elt type, and then 3152 // splat from elt type to vector. 3153 if (SrcTy->isPointerType()) 3154 return Diag(R.getBegin(), 3155 diag::err_invalid_conversion_between_vector_and_scalar) 3156 << DestTy << SrcTy << R; 3157 return false; 3158} 3159 3160Action::OwningExprResult 3161Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty, 3162 SourceLocation RParenLoc, ExprArg Op) { 3163 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 3164 3165 assert((Ty != 0) && (Op.get() != 0) && 3166 "ActOnCastExpr(): missing type or expr"); 3167 3168 Expr *castExpr = (Expr *)Op.get(); 3169 //FIXME: Preserve type source info. 3170 QualType castType = GetTypeFromParser(Ty); 3171 3172 // If the Expr being casted is a ParenListExpr, handle it specially. 3173 if (isa<ParenListExpr>(castExpr)) 3174 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType); 3175 CXXMethodDecl *ConversionDecl = 0; 3176 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr, 3177 Kind, ConversionDecl)) 3178 return ExprError(); 3179 if (ConversionDecl) { 3180 // encounterred a c-style cast requiring a conversion function. 3181 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) { 3182 castExpr = 3183 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(), 3184 castType, LParenLoc, 3185 CastExpr::CK_UserDefinedConversion, 3186 castExpr, CD, 3187 RParenLoc); 3188 Kind = CastExpr::CK_UserDefinedConversion; 3189 } 3190 // FIXME. AST for when dealing with conversion functions (FunctionDecl). 3191 } 3192 3193 Op.release(); 3194 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(), 3195 Kind, castExpr, castType, 3196 LParenLoc, RParenLoc)); 3197} 3198 3199/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 3200/// of comma binary operators. 3201Action::OwningExprResult 3202Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) { 3203 Expr *expr = EA.takeAs<Expr>(); 3204 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 3205 if (!E) 3206 return Owned(expr); 3207 3208 OwningExprResult Result(*this, E->getExpr(0)); 3209 3210 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 3211 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result), 3212 Owned(E->getExpr(i))); 3213 3214 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result)); 3215} 3216 3217Action::OwningExprResult 3218Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 3219 SourceLocation RParenLoc, ExprArg Op, 3220 QualType Ty) { 3221 ParenListExpr *PE = (ParenListExpr *)Op.get(); 3222 3223 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 3224 // then handle it as such. 3225 if (getLangOptions().AltiVec && Ty->isVectorType()) { 3226 if (PE->getNumExprs() == 0) { 3227 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 3228 return ExprError(); 3229 } 3230 3231 llvm::SmallVector<Expr *, 8> initExprs; 3232 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 3233 initExprs.push_back(PE->getExpr(i)); 3234 3235 // FIXME: This means that pretty-printing the final AST will produce curly 3236 // braces instead of the original commas. 3237 Op.release(); 3238 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0], 3239 initExprs.size(), RParenLoc); 3240 E->setType(Ty); 3241 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc, 3242 Owned(E)); 3243 } else { 3244 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 3245 // sequence of BinOp comma operators. 3246 Op = MaybeConvertParenListExprToParenExpr(S, move(Op)); 3247 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op)); 3248 } 3249} 3250 3251Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L, 3252 SourceLocation R, 3253 MultiExprArg Val) { 3254 unsigned nexprs = Val.size(); 3255 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 3256 assert((exprs != 0) && "ActOnParenListExpr() missing expr list"); 3257 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 3258 return Owned(expr); 3259} 3260 3261/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 3262/// In that case, lhs = cond. 3263/// C99 6.5.15 3264QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 3265 SourceLocation QuestionLoc) { 3266 // C++ is sufficiently different to merit its own checker. 3267 if (getLangOptions().CPlusPlus) 3268 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc); 3269 3270 UsualUnaryConversions(Cond); 3271 UsualUnaryConversions(LHS); 3272 UsualUnaryConversions(RHS); 3273 QualType CondTy = Cond->getType(); 3274 QualType LHSTy = LHS->getType(); 3275 QualType RHSTy = RHS->getType(); 3276 3277 // first, check the condition. 3278 if (!CondTy->isScalarType()) { // C99 6.5.15p2 3279 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 3280 << CondTy; 3281 return QualType(); 3282 } 3283 3284 // Now check the two expressions. 3285 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 3286 return CheckVectorOperands(QuestionLoc, LHS, RHS); 3287 3288 // If both operands have arithmetic type, do the usual arithmetic conversions 3289 // to find a common type: C99 6.5.15p3,5. 3290 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 3291 UsualArithmeticConversions(LHS, RHS); 3292 return LHS->getType(); 3293 } 3294 3295 // If both operands are the same structure or union type, the result is that 3296 // type. 3297 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 3298 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 3299 if (LHSRT->getDecl() == RHSRT->getDecl()) 3300 // "If both the operands have structure or union type, the result has 3301 // that type." This implies that CV qualifiers are dropped. 3302 return LHSTy.getUnqualifiedType(); 3303 // FIXME: Type of conditional expression must be complete in C mode. 3304 } 3305 3306 // C99 6.5.15p5: "If both operands have void type, the result has void type." 3307 // The following || allows only one side to be void (a GCC-ism). 3308 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 3309 if (!LHSTy->isVoidType()) 3310 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3311 << RHS->getSourceRange(); 3312 if (!RHSTy->isVoidType()) 3313 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3314 << LHS->getSourceRange(); 3315 ImpCastExprToType(LHS, Context.VoidTy); 3316 ImpCastExprToType(RHS, Context.VoidTy); 3317 return Context.VoidTy; 3318 } 3319 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 3320 // the type of the other operand." 3321 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 3322 RHS->isNullPointerConstant(Context)) { 3323 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. 3324 return LHSTy; 3325 } 3326 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 3327 LHS->isNullPointerConstant(Context)) { 3328 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. 3329 return RHSTy; 3330 } 3331 // Handle things like Class and struct objc_class*. Here we case the result 3332 // to the pseudo-builtin, because that will be implicitly cast back to the 3333 // redefinition type if an attempt is made to access its fields. 3334 if (LHSTy->isObjCClassType() && 3335 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 3336 ImpCastExprToType(RHS, LHSTy); 3337 return LHSTy; 3338 } 3339 if (RHSTy->isObjCClassType() && 3340 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 3341 ImpCastExprToType(LHS, RHSTy); 3342 return RHSTy; 3343 } 3344 // And the same for struct objc_object* / id 3345 if (LHSTy->isObjCIdType() && 3346 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 3347 ImpCastExprToType(RHS, LHSTy); 3348 return LHSTy; 3349 } 3350 if (RHSTy->isObjCIdType() && 3351 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 3352 ImpCastExprToType(LHS, RHSTy); 3353 return RHSTy; 3354 } 3355 // Handle block pointer types. 3356 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 3357 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 3358 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 3359 QualType destType = Context.getPointerType(Context.VoidTy); 3360 ImpCastExprToType(LHS, destType); 3361 ImpCastExprToType(RHS, destType); 3362 return destType; 3363 } 3364 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3365 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3366 return QualType(); 3367 } 3368 // We have 2 block pointer types. 3369 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3370 // Two identical block pointer types are always compatible. 3371 return LHSTy; 3372 } 3373 // The block pointer types aren't identical, continue checking. 3374 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 3375 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 3376 3377 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3378 rhptee.getUnqualifiedType())) { 3379 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3380 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3381 // In this situation, we assume void* type. No especially good 3382 // reason, but this is what gcc does, and we do have to pick 3383 // to get a consistent AST. 3384 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3385 ImpCastExprToType(LHS, incompatTy); 3386 ImpCastExprToType(RHS, incompatTy); 3387 return incompatTy; 3388 } 3389 // The block pointer types are compatible. 3390 ImpCastExprToType(LHS, LHSTy); 3391 ImpCastExprToType(RHS, LHSTy); 3392 return LHSTy; 3393 } 3394 // Check constraints for Objective-C object pointers types. 3395 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 3396 3397 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3398 // Two identical object pointer types are always compatible. 3399 return LHSTy; 3400 } 3401 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType(); 3402 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType(); 3403 QualType compositeType = LHSTy; 3404 3405 // If both operands are interfaces and either operand can be 3406 // assigned to the other, use that type as the composite 3407 // type. This allows 3408 // xxx ? (A*) a : (B*) b 3409 // where B is a subclass of A. 3410 // 3411 // Additionally, as for assignment, if either type is 'id' 3412 // allow silent coercion. Finally, if the types are 3413 // incompatible then make sure to use 'id' as the composite 3414 // type so the result is acceptable for sending messages to. 3415 3416 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 3417 // It could return the composite type. 3418 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 3419 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 3420 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 3421 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 3422 } else if ((LHSTy->isObjCQualifiedIdType() || 3423 RHSTy->isObjCQualifiedIdType()) && 3424 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 3425 // Need to handle "id<xx>" explicitly. 3426 // GCC allows qualified id and any Objective-C type to devolve to 3427 // id. Currently localizing to here until clear this should be 3428 // part of ObjCQualifiedIdTypesAreCompatible. 3429 compositeType = Context.getObjCIdType(); 3430 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 3431 compositeType = Context.getObjCIdType(); 3432 } else { 3433 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 3434 << LHSTy << RHSTy 3435 << LHS->getSourceRange() << RHS->getSourceRange(); 3436 QualType incompatTy = Context.getObjCIdType(); 3437 ImpCastExprToType(LHS, incompatTy); 3438 ImpCastExprToType(RHS, incompatTy); 3439 return incompatTy; 3440 } 3441 // The object pointer types are compatible. 3442 ImpCastExprToType(LHS, compositeType); 3443 ImpCastExprToType(RHS, compositeType); 3444 return compositeType; 3445 } 3446 // Check Objective-C object pointer types and 'void *' 3447 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 3448 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 3449 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType(); 3450 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 3451 QualType destType = Context.getPointerType(destPointee); 3452 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 3453 ImpCastExprToType(RHS, destType); // promote to void* 3454 return destType; 3455 } 3456 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 3457 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType(); 3458 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 3459 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 3460 QualType destType = Context.getPointerType(destPointee); 3461 ImpCastExprToType(RHS, destType); // add qualifiers if necessary 3462 ImpCastExprToType(LHS, destType); // promote to void* 3463 return destType; 3464 } 3465 // Check constraints for C object pointers types (C99 6.5.15p3,6). 3466 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 3467 // get the "pointed to" types 3468 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 3469 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 3470 3471 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 3472 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 3473 // Figure out necessary qualifiers (C99 6.5.15p6) 3474 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 3475 QualType destType = Context.getPointerType(destPointee); 3476 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 3477 ImpCastExprToType(RHS, destType); // promote to void* 3478 return destType; 3479 } 3480 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 3481 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 3482 QualType destType = Context.getPointerType(destPointee); 3483 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 3484 ImpCastExprToType(RHS, destType); // promote to void* 3485 return destType; 3486 } 3487 3488 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3489 // Two identical pointer types are always compatible. 3490 return LHSTy; 3491 } 3492 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3493 rhptee.getUnqualifiedType())) { 3494 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3495 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3496 // In this situation, we assume void* type. No especially good 3497 // reason, but this is what gcc does, and we do have to pick 3498 // to get a consistent AST. 3499 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3500 ImpCastExprToType(LHS, incompatTy); 3501 ImpCastExprToType(RHS, incompatTy); 3502 return incompatTy; 3503 } 3504 // The pointer types are compatible. 3505 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 3506 // differently qualified versions of compatible types, the result type is 3507 // a pointer to an appropriately qualified version of the *composite* 3508 // type. 3509 // FIXME: Need to calculate the composite type. 3510 // FIXME: Need to add qualifiers 3511 ImpCastExprToType(LHS, LHSTy); 3512 ImpCastExprToType(RHS, LHSTy); 3513 return LHSTy; 3514 } 3515 3516 // GCC compatibility: soften pointer/integer mismatch. 3517 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 3518 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3519 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3520 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer. 3521 return RHSTy; 3522 } 3523 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 3524 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3525 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3526 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer. 3527 return LHSTy; 3528 } 3529 3530 // Otherwise, the operands are not compatible. 3531 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3532 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3533 return QualType(); 3534} 3535 3536/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3537/// in the case of a the GNU conditional expr extension. 3538Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 3539 SourceLocation ColonLoc, 3540 ExprArg Cond, ExprArg LHS, 3541 ExprArg RHS) { 3542 Expr *CondExpr = (Expr *) Cond.get(); 3543 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 3544 3545 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 3546 // was the condition. 3547 bool isLHSNull = LHSExpr == 0; 3548 if (isLHSNull) 3549 LHSExpr = CondExpr; 3550 3551 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 3552 RHSExpr, QuestionLoc); 3553 if (result.isNull()) 3554 return ExprError(); 3555 3556 Cond.release(); 3557 LHS.release(); 3558 RHS.release(); 3559 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 3560 isLHSNull ? 0 : LHSExpr, 3561 ColonLoc, RHSExpr, result)); 3562} 3563 3564// CheckPointerTypesForAssignment - This is a very tricky routine (despite 3565// being closely modeled after the C99 spec:-). The odd characteristic of this 3566// routine is it effectively iqnores the qualifiers on the top level pointee. 3567// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 3568// FIXME: add a couple examples in this comment. 3569Sema::AssignConvertType 3570Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 3571 QualType lhptee, rhptee; 3572 3573 if ((lhsType->isObjCClassType() && 3574 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 3575 (rhsType->isObjCClassType() && 3576 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 3577 return Compatible; 3578 } 3579 3580 // get the "pointed to" type (ignoring qualifiers at the top level) 3581 lhptee = lhsType->getAs<PointerType>()->getPointeeType(); 3582 rhptee = rhsType->getAs<PointerType>()->getPointeeType(); 3583 3584 // make sure we operate on the canonical type 3585 lhptee = Context.getCanonicalType(lhptee); 3586 rhptee = Context.getCanonicalType(rhptee); 3587 3588 AssignConvertType ConvTy = Compatible; 3589 3590 // C99 6.5.16.1p1: This following citation is common to constraints 3591 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 3592 // qualifiers of the type *pointed to* by the right; 3593 // FIXME: Handle ExtQualType 3594 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 3595 ConvTy = CompatiblePointerDiscardsQualifiers; 3596 3597 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 3598 // incomplete type and the other is a pointer to a qualified or unqualified 3599 // version of void... 3600 if (lhptee->isVoidType()) { 3601 if (rhptee->isIncompleteOrObjectType()) 3602 return ConvTy; 3603 3604 // As an extension, we allow cast to/from void* to function pointer. 3605 assert(rhptee->isFunctionType()); 3606 return FunctionVoidPointer; 3607 } 3608 3609 if (rhptee->isVoidType()) { 3610 if (lhptee->isIncompleteOrObjectType()) 3611 return ConvTy; 3612 3613 // As an extension, we allow cast to/from void* to function pointer. 3614 assert(lhptee->isFunctionType()); 3615 return FunctionVoidPointer; 3616 } 3617 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 3618 // unqualified versions of compatible types, ... 3619 lhptee = lhptee.getUnqualifiedType(); 3620 rhptee = rhptee.getUnqualifiedType(); 3621 if (!Context.typesAreCompatible(lhptee, rhptee)) { 3622 // Check if the pointee types are compatible ignoring the sign. 3623 // We explicitly check for char so that we catch "char" vs 3624 // "unsigned char" on systems where "char" is unsigned. 3625 if (lhptee->isCharType()) { 3626 lhptee = Context.UnsignedCharTy; 3627 } else if (lhptee->isSignedIntegerType()) { 3628 lhptee = Context.getCorrespondingUnsignedType(lhptee); 3629 } 3630 if (rhptee->isCharType()) { 3631 rhptee = Context.UnsignedCharTy; 3632 } else if (rhptee->isSignedIntegerType()) { 3633 rhptee = Context.getCorrespondingUnsignedType(rhptee); 3634 } 3635 if (lhptee == rhptee) { 3636 // Types are compatible ignoring the sign. Qualifier incompatibility 3637 // takes priority over sign incompatibility because the sign 3638 // warning can be disabled. 3639 if (ConvTy != Compatible) 3640 return ConvTy; 3641 return IncompatiblePointerSign; 3642 } 3643 // General pointer incompatibility takes priority over qualifiers. 3644 return IncompatiblePointer; 3645 } 3646 return ConvTy; 3647} 3648 3649/// CheckBlockPointerTypesForAssignment - This routine determines whether two 3650/// block pointer types are compatible or whether a block and normal pointer 3651/// are compatible. It is more restrict than comparing two function pointer 3652// types. 3653Sema::AssignConvertType 3654Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 3655 QualType rhsType) { 3656 QualType lhptee, rhptee; 3657 3658 // get the "pointed to" type (ignoring qualifiers at the top level) 3659 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType(); 3660 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType(); 3661 3662 // make sure we operate on the canonical type 3663 lhptee = Context.getCanonicalType(lhptee); 3664 rhptee = Context.getCanonicalType(rhptee); 3665 3666 AssignConvertType ConvTy = Compatible; 3667 3668 // For blocks we enforce that qualifiers are identical. 3669 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 3670 ConvTy = CompatiblePointerDiscardsQualifiers; 3671 3672 if (!Context.typesAreCompatible(lhptee, rhptee)) 3673 return IncompatibleBlockPointer; 3674 return ConvTy; 3675} 3676 3677/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 3678/// has code to accommodate several GCC extensions when type checking 3679/// pointers. Here are some objectionable examples that GCC considers warnings: 3680/// 3681/// int a, *pint; 3682/// short *pshort; 3683/// struct foo *pfoo; 3684/// 3685/// pint = pshort; // warning: assignment from incompatible pointer type 3686/// a = pint; // warning: assignment makes integer from pointer without a cast 3687/// pint = a; // warning: assignment makes pointer from integer without a cast 3688/// pint = pfoo; // warning: assignment from incompatible pointer type 3689/// 3690/// As a result, the code for dealing with pointers is more complex than the 3691/// C99 spec dictates. 3692/// 3693Sema::AssignConvertType 3694Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 3695 // Get canonical types. We're not formatting these types, just comparing 3696 // them. 3697 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 3698 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 3699 3700 if (lhsType == rhsType) 3701 return Compatible; // Common case: fast path an exact match. 3702 3703 if ((lhsType->isObjCClassType() && 3704 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 3705 (rhsType->isObjCClassType() && 3706 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 3707 return Compatible; 3708 } 3709 3710 // If the left-hand side is a reference type, then we are in a 3711 // (rare!) case where we've allowed the use of references in C, 3712 // e.g., as a parameter type in a built-in function. In this case, 3713 // just make sure that the type referenced is compatible with the 3714 // right-hand side type. The caller is responsible for adjusting 3715 // lhsType so that the resulting expression does not have reference 3716 // type. 3717 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 3718 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 3719 return Compatible; 3720 return Incompatible; 3721 } 3722 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 3723 // to the same ExtVector type. 3724 if (lhsType->isExtVectorType()) { 3725 if (rhsType->isExtVectorType()) 3726 return lhsType == rhsType ? Compatible : Incompatible; 3727 if (!rhsType->isVectorType() && rhsType->isArithmeticType()) 3728 return Compatible; 3729 } 3730 3731 if (lhsType->isVectorType() || rhsType->isVectorType()) { 3732 // If we are allowing lax vector conversions, and LHS and RHS are both 3733 // vectors, the total size only needs to be the same. This is a bitcast; 3734 // no bits are changed but the result type is different. 3735 if (getLangOptions().LaxVectorConversions && 3736 lhsType->isVectorType() && rhsType->isVectorType()) { 3737 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 3738 return IncompatibleVectors; 3739 } 3740 return Incompatible; 3741 } 3742 3743 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 3744 return Compatible; 3745 3746 if (isa<PointerType>(lhsType)) { 3747 if (rhsType->isIntegerType()) 3748 return IntToPointer; 3749 3750 if (isa<PointerType>(rhsType)) 3751 return CheckPointerTypesForAssignment(lhsType, rhsType); 3752 3753 // In general, C pointers are not compatible with ObjC object pointers. 3754 if (isa<ObjCObjectPointerType>(rhsType)) { 3755 if (lhsType->isVoidPointerType()) // an exception to the rule. 3756 return Compatible; 3757 return IncompatiblePointer; 3758 } 3759 if (rhsType->getAs<BlockPointerType>()) { 3760 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3761 return Compatible; 3762 3763 // Treat block pointers as objects. 3764 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) 3765 return Compatible; 3766 } 3767 return Incompatible; 3768 } 3769 3770 if (isa<BlockPointerType>(lhsType)) { 3771 if (rhsType->isIntegerType()) 3772 return IntToBlockPointer; 3773 3774 // Treat block pointers as objects. 3775 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) 3776 return Compatible; 3777 3778 if (rhsType->isBlockPointerType()) 3779 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 3780 3781 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 3782 if (RHSPT->getPointeeType()->isVoidType()) 3783 return Compatible; 3784 } 3785 return Incompatible; 3786 } 3787 3788 if (isa<ObjCObjectPointerType>(lhsType)) { 3789 if (rhsType->isIntegerType()) 3790 return IntToPointer; 3791 3792 // In general, C pointers are not compatible with ObjC object pointers. 3793 if (isa<PointerType>(rhsType)) { 3794 if (rhsType->isVoidPointerType()) // an exception to the rule. 3795 return Compatible; 3796 return IncompatiblePointer; 3797 } 3798 if (rhsType->isObjCObjectPointerType()) { 3799 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType()) 3800 return Compatible; 3801 if (Context.typesAreCompatible(lhsType, rhsType)) 3802 return Compatible; 3803 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 3804 return IncompatibleObjCQualifiedId; 3805 return IncompatiblePointer; 3806 } 3807 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 3808 if (RHSPT->getPointeeType()->isVoidType()) 3809 return Compatible; 3810 } 3811 // Treat block pointers as objects. 3812 if (rhsType->isBlockPointerType()) 3813 return Compatible; 3814 return Incompatible; 3815 } 3816 if (isa<PointerType>(rhsType)) { 3817 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 3818 if (lhsType == Context.BoolTy) 3819 return Compatible; 3820 3821 if (lhsType->isIntegerType()) 3822 return PointerToInt; 3823 3824 if (isa<PointerType>(lhsType)) 3825 return CheckPointerTypesForAssignment(lhsType, rhsType); 3826 3827 if (isa<BlockPointerType>(lhsType) && 3828 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3829 return Compatible; 3830 return Incompatible; 3831 } 3832 if (isa<ObjCObjectPointerType>(rhsType)) { 3833 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 3834 if (lhsType == Context.BoolTy) 3835 return Compatible; 3836 3837 if (lhsType->isIntegerType()) 3838 return PointerToInt; 3839 3840 // In general, C pointers are not compatible with ObjC object pointers. 3841 if (isa<PointerType>(lhsType)) { 3842 if (lhsType->isVoidPointerType()) // an exception to the rule. 3843 return Compatible; 3844 return IncompatiblePointer; 3845 } 3846 if (isa<BlockPointerType>(lhsType) && 3847 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3848 return Compatible; 3849 return Incompatible; 3850 } 3851 3852 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 3853 if (Context.typesAreCompatible(lhsType, rhsType)) 3854 return Compatible; 3855 } 3856 return Incompatible; 3857} 3858 3859/// \brief Constructs a transparent union from an expression that is 3860/// used to initialize the transparent union. 3861static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 3862 QualType UnionType, FieldDecl *Field) { 3863 // Build an initializer list that designates the appropriate member 3864 // of the transparent union. 3865 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(), 3866 &E, 1, 3867 SourceLocation()); 3868 Initializer->setType(UnionType); 3869 Initializer->setInitializedFieldInUnion(Field); 3870 3871 // Build a compound literal constructing a value of the transparent 3872 // union type from this initializer list. 3873 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer, 3874 false); 3875} 3876 3877Sema::AssignConvertType 3878Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 3879 QualType FromType = rExpr->getType(); 3880 3881 // If the ArgType is a Union type, we want to handle a potential 3882 // transparent_union GCC extension. 3883 const RecordType *UT = ArgType->getAsUnionType(); 3884 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3885 return Incompatible; 3886 3887 // The field to initialize within the transparent union. 3888 RecordDecl *UD = UT->getDecl(); 3889 FieldDecl *InitField = 0; 3890 // It's compatible if the expression matches any of the fields. 3891 for (RecordDecl::field_iterator it = UD->field_begin(), 3892 itend = UD->field_end(); 3893 it != itend; ++it) { 3894 if (it->getType()->isPointerType()) { 3895 // If the transparent union contains a pointer type, we allow: 3896 // 1) void pointer 3897 // 2) null pointer constant 3898 if (FromType->isPointerType()) 3899 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 3900 ImpCastExprToType(rExpr, it->getType()); 3901 InitField = *it; 3902 break; 3903 } 3904 3905 if (rExpr->isNullPointerConstant(Context)) { 3906 ImpCastExprToType(rExpr, it->getType()); 3907 InitField = *it; 3908 break; 3909 } 3910 } 3911 3912 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 3913 == Compatible) { 3914 InitField = *it; 3915 break; 3916 } 3917 } 3918 3919 if (!InitField) 3920 return Incompatible; 3921 3922 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 3923 return Compatible; 3924} 3925 3926Sema::AssignConvertType 3927Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 3928 if (getLangOptions().CPlusPlus) { 3929 if (!lhsType->isRecordType()) { 3930 // C++ 5.17p3: If the left operand is not of class type, the 3931 // expression is implicitly converted (C++ 4) to the 3932 // cv-unqualified type of the left operand. 3933 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 3934 "assigning")) 3935 return Incompatible; 3936 return Compatible; 3937 } 3938 3939 // FIXME: Currently, we fall through and treat C++ classes like C 3940 // structures. 3941 } 3942 3943 // C99 6.5.16.1p1: the left operand is a pointer and the right is 3944 // a null pointer constant. 3945 if ((lhsType->isPointerType() || 3946 lhsType->isObjCObjectPointerType() || 3947 lhsType->isBlockPointerType()) 3948 && rExpr->isNullPointerConstant(Context)) { 3949 ImpCastExprToType(rExpr, lhsType); 3950 return Compatible; 3951 } 3952 3953 // This check seems unnatural, however it is necessary to ensure the proper 3954 // conversion of functions/arrays. If the conversion were done for all 3955 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 3956 // expressions that surpress this implicit conversion (&, sizeof). 3957 // 3958 // Suppress this for references: C++ 8.5.3p5. 3959 if (!lhsType->isReferenceType()) 3960 DefaultFunctionArrayConversion(rExpr); 3961 3962 Sema::AssignConvertType result = 3963 CheckAssignmentConstraints(lhsType, rExpr->getType()); 3964 3965 // C99 6.5.16.1p2: The value of the right operand is converted to the 3966 // type of the assignment expression. 3967 // CheckAssignmentConstraints allows the left-hand side to be a reference, 3968 // so that we can use references in built-in functions even in C. 3969 // The getNonReferenceType() call makes sure that the resulting expression 3970 // does not have reference type. 3971 if (result != Incompatible && rExpr->getType() != lhsType) 3972 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 3973 return result; 3974} 3975 3976QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 3977 Diag(Loc, diag::err_typecheck_invalid_operands) 3978 << lex->getType() << rex->getType() 3979 << lex->getSourceRange() << rex->getSourceRange(); 3980 return QualType(); 3981} 3982 3983inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 3984 Expr *&rex) { 3985 // For conversion purposes, we ignore any qualifiers. 3986 // For example, "const float" and "float" are equivalent. 3987 QualType lhsType = 3988 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 3989 QualType rhsType = 3990 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 3991 3992 // If the vector types are identical, return. 3993 if (lhsType == rhsType) 3994 return lhsType; 3995 3996 // Handle the case of a vector & extvector type of the same size and element 3997 // type. It would be nice if we only had one vector type someday. 3998 if (getLangOptions().LaxVectorConversions) { 3999 // FIXME: Should we warn here? 4000 if (const VectorType *LV = lhsType->getAsVectorType()) { 4001 if (const VectorType *RV = rhsType->getAsVectorType()) 4002 if (LV->getElementType() == RV->getElementType() && 4003 LV->getNumElements() == RV->getNumElements()) { 4004 return lhsType->isExtVectorType() ? lhsType : rhsType; 4005 } 4006 } 4007 } 4008 4009 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 4010 // swap back (so that we don't reverse the inputs to a subtract, for instance. 4011 bool swapped = false; 4012 if (rhsType->isExtVectorType()) { 4013 swapped = true; 4014 std::swap(rex, lex); 4015 std::swap(rhsType, lhsType); 4016 } 4017 4018 // Handle the case of an ext vector and scalar. 4019 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) { 4020 QualType EltTy = LV->getElementType(); 4021 if (EltTy->isIntegralType() && rhsType->isIntegralType()) { 4022 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 4023 ImpCastExprToType(rex, lhsType); 4024 if (swapped) std::swap(rex, lex); 4025 return lhsType; 4026 } 4027 } 4028 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 4029 rhsType->isRealFloatingType()) { 4030 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 4031 ImpCastExprToType(rex, lhsType); 4032 if (swapped) std::swap(rex, lex); 4033 return lhsType; 4034 } 4035 } 4036 } 4037 4038 // Vectors of different size or scalar and non-ext-vector are errors. 4039 Diag(Loc, diag::err_typecheck_vector_not_convertable) 4040 << lex->getType() << rex->getType() 4041 << lex->getSourceRange() << rex->getSourceRange(); 4042 return QualType(); 4043} 4044 4045inline QualType Sema::CheckMultiplyDivideOperands( 4046 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 4047{ 4048 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4049 return CheckVectorOperands(Loc, lex, rex); 4050 4051 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4052 4053 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 4054 return compType; 4055 return InvalidOperands(Loc, lex, rex); 4056} 4057 4058inline QualType Sema::CheckRemainderOperands( 4059 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 4060{ 4061 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4062 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4063 return CheckVectorOperands(Loc, lex, rex); 4064 return InvalidOperands(Loc, lex, rex); 4065 } 4066 4067 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4068 4069 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4070 return compType; 4071 return InvalidOperands(Loc, lex, rex); 4072} 4073 4074inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 4075 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) 4076{ 4077 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4078 QualType compType = CheckVectorOperands(Loc, lex, rex); 4079 if (CompLHSTy) *CompLHSTy = compType; 4080 return compType; 4081 } 4082 4083 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 4084 4085 // handle the common case first (both operands are arithmetic). 4086 if (lex->getType()->isArithmeticType() && 4087 rex->getType()->isArithmeticType()) { 4088 if (CompLHSTy) *CompLHSTy = compType; 4089 return compType; 4090 } 4091 4092 // Put any potential pointer into PExp 4093 Expr* PExp = lex, *IExp = rex; 4094 if (IExp->getType()->isAnyPointerType()) 4095 std::swap(PExp, IExp); 4096 4097 if (PExp->getType()->isAnyPointerType()) { 4098 4099 if (IExp->getType()->isIntegerType()) { 4100 QualType PointeeTy = PExp->getType()->getPointeeType(); 4101 4102 // Check for arithmetic on pointers to incomplete types. 4103 if (PointeeTy->isVoidType()) { 4104 if (getLangOptions().CPlusPlus) { 4105 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4106 << lex->getSourceRange() << rex->getSourceRange(); 4107 return QualType(); 4108 } 4109 4110 // GNU extension: arithmetic on pointer to void 4111 Diag(Loc, diag::ext_gnu_void_ptr) 4112 << lex->getSourceRange() << rex->getSourceRange(); 4113 } else if (PointeeTy->isFunctionType()) { 4114 if (getLangOptions().CPlusPlus) { 4115 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4116 << lex->getType() << lex->getSourceRange(); 4117 return QualType(); 4118 } 4119 4120 // GNU extension: arithmetic on pointer to function 4121 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4122 << lex->getType() << lex->getSourceRange(); 4123 } else { 4124 // Check if we require a complete type. 4125 if (((PExp->getType()->isPointerType() && 4126 !PExp->getType()->isDependentType()) || 4127 PExp->getType()->isObjCObjectPointerType()) && 4128 RequireCompleteType(Loc, PointeeTy, 4129 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 4130 << PExp->getSourceRange() 4131 << PExp->getType())) 4132 return QualType(); 4133 } 4134 // Diagnose bad cases where we step over interface counts. 4135 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 4136 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 4137 << PointeeTy << PExp->getSourceRange(); 4138 return QualType(); 4139 } 4140 4141 if (CompLHSTy) { 4142 QualType LHSTy = Context.isPromotableBitField(lex); 4143 if (LHSTy.isNull()) { 4144 LHSTy = lex->getType(); 4145 if (LHSTy->isPromotableIntegerType()) 4146 LHSTy = Context.getPromotedIntegerType(LHSTy); 4147 } 4148 *CompLHSTy = LHSTy; 4149 } 4150 return PExp->getType(); 4151 } 4152 } 4153 4154 return InvalidOperands(Loc, lex, rex); 4155} 4156 4157// C99 6.5.6 4158QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 4159 SourceLocation Loc, QualType* CompLHSTy) { 4160 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4161 QualType compType = CheckVectorOperands(Loc, lex, rex); 4162 if (CompLHSTy) *CompLHSTy = compType; 4163 return compType; 4164 } 4165 4166 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 4167 4168 // Enforce type constraints: C99 6.5.6p3. 4169 4170 // Handle the common case first (both operands are arithmetic). 4171 if (lex->getType()->isArithmeticType() 4172 && rex->getType()->isArithmeticType()) { 4173 if (CompLHSTy) *CompLHSTy = compType; 4174 return compType; 4175 } 4176 4177 // Either ptr - int or ptr - ptr. 4178 if (lex->getType()->isAnyPointerType()) { 4179 QualType lpointee = lex->getType()->getPointeeType(); 4180 4181 // The LHS must be an completely-defined object type. 4182 4183 bool ComplainAboutVoid = false; 4184 Expr *ComplainAboutFunc = 0; 4185 if (lpointee->isVoidType()) { 4186 if (getLangOptions().CPlusPlus) { 4187 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4188 << lex->getSourceRange() << rex->getSourceRange(); 4189 return QualType(); 4190 } 4191 4192 // GNU C extension: arithmetic on pointer to void 4193 ComplainAboutVoid = true; 4194 } else if (lpointee->isFunctionType()) { 4195 if (getLangOptions().CPlusPlus) { 4196 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4197 << lex->getType() << lex->getSourceRange(); 4198 return QualType(); 4199 } 4200 4201 // GNU C extension: arithmetic on pointer to function 4202 ComplainAboutFunc = lex; 4203 } else if (!lpointee->isDependentType() && 4204 RequireCompleteType(Loc, lpointee, 4205 PDiag(diag::err_typecheck_sub_ptr_object) 4206 << lex->getSourceRange() 4207 << lex->getType())) 4208 return QualType(); 4209 4210 // Diagnose bad cases where we step over interface counts. 4211 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 4212 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 4213 << lpointee << lex->getSourceRange(); 4214 return QualType(); 4215 } 4216 4217 // The result type of a pointer-int computation is the pointer type. 4218 if (rex->getType()->isIntegerType()) { 4219 if (ComplainAboutVoid) 4220 Diag(Loc, diag::ext_gnu_void_ptr) 4221 << lex->getSourceRange() << rex->getSourceRange(); 4222 if (ComplainAboutFunc) 4223 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4224 << ComplainAboutFunc->getType() 4225 << ComplainAboutFunc->getSourceRange(); 4226 4227 if (CompLHSTy) *CompLHSTy = lex->getType(); 4228 return lex->getType(); 4229 } 4230 4231 // Handle pointer-pointer subtractions. 4232 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 4233 QualType rpointee = RHSPTy->getPointeeType(); 4234 4235 // RHS must be a completely-type object type. 4236 // Handle the GNU void* extension. 4237 if (rpointee->isVoidType()) { 4238 if (getLangOptions().CPlusPlus) { 4239 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4240 << lex->getSourceRange() << rex->getSourceRange(); 4241 return QualType(); 4242 } 4243 4244 ComplainAboutVoid = true; 4245 } else if (rpointee->isFunctionType()) { 4246 if (getLangOptions().CPlusPlus) { 4247 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4248 << rex->getType() << rex->getSourceRange(); 4249 return QualType(); 4250 } 4251 4252 // GNU extension: arithmetic on pointer to function 4253 if (!ComplainAboutFunc) 4254 ComplainAboutFunc = rex; 4255 } else if (!rpointee->isDependentType() && 4256 RequireCompleteType(Loc, rpointee, 4257 PDiag(diag::err_typecheck_sub_ptr_object) 4258 << rex->getSourceRange() 4259 << rex->getType())) 4260 return QualType(); 4261 4262 if (getLangOptions().CPlusPlus) { 4263 // Pointee types must be the same: C++ [expr.add] 4264 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 4265 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 4266 << lex->getType() << rex->getType() 4267 << lex->getSourceRange() << rex->getSourceRange(); 4268 return QualType(); 4269 } 4270 } else { 4271 // Pointee types must be compatible C99 6.5.6p3 4272 if (!Context.typesAreCompatible( 4273 Context.getCanonicalType(lpointee).getUnqualifiedType(), 4274 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 4275 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 4276 << lex->getType() << rex->getType() 4277 << lex->getSourceRange() << rex->getSourceRange(); 4278 return QualType(); 4279 } 4280 } 4281 4282 if (ComplainAboutVoid) 4283 Diag(Loc, diag::ext_gnu_void_ptr) 4284 << lex->getSourceRange() << rex->getSourceRange(); 4285 if (ComplainAboutFunc) 4286 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4287 << ComplainAboutFunc->getType() 4288 << ComplainAboutFunc->getSourceRange(); 4289 4290 if (CompLHSTy) *CompLHSTy = lex->getType(); 4291 return Context.getPointerDiffType(); 4292 } 4293 } 4294 4295 return InvalidOperands(Loc, lex, rex); 4296} 4297 4298// C99 6.5.7 4299QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 4300 bool isCompAssign) { 4301 // C99 6.5.7p2: Each of the operands shall have integer type. 4302 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 4303 return InvalidOperands(Loc, lex, rex); 4304 4305 // Shifts don't perform usual arithmetic conversions, they just do integer 4306 // promotions on each operand. C99 6.5.7p3 4307 QualType LHSTy = Context.isPromotableBitField(lex); 4308 if (LHSTy.isNull()) { 4309 LHSTy = lex->getType(); 4310 if (LHSTy->isPromotableIntegerType()) 4311 LHSTy = Context.getPromotedIntegerType(LHSTy); 4312 } 4313 if (!isCompAssign) 4314 ImpCastExprToType(lex, LHSTy); 4315 4316 UsualUnaryConversions(rex); 4317 4318 // Sanity-check shift operands 4319 llvm::APSInt Right; 4320 // Check right/shifter operand 4321 if (rex->isIntegerConstantExpr(Right, Context)) { 4322 if (Right.isNegative()) 4323 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange(); 4324 else { 4325 llvm::APInt LeftBits(Right.getBitWidth(), 4326 Context.getTypeSize(lex->getType())); 4327 if (Right.uge(LeftBits)) 4328 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange(); 4329 } 4330 } 4331 4332 // "The type of the result is that of the promoted left operand." 4333 return LHSTy; 4334} 4335 4336// C99 6.5.8, C++ [expr.rel] 4337QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 4338 unsigned OpaqueOpc, bool isRelational) { 4339 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; 4340 4341 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4342 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 4343 4344 // C99 6.5.8p3 / C99 6.5.9p4 4345 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 4346 UsualArithmeticConversions(lex, rex); 4347 else { 4348 UsualUnaryConversions(lex); 4349 UsualUnaryConversions(rex); 4350 } 4351 QualType lType = lex->getType(); 4352 QualType rType = rex->getType(); 4353 4354 if (!lType->isFloatingType() 4355 && !(lType->isBlockPointerType() && isRelational)) { 4356 // For non-floating point types, check for self-comparisons of the form 4357 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4358 // often indicate logic errors in the program. 4359 // NOTE: Don't warn about comparisons of enum constants. These can arise 4360 // from macro expansions, and are usually quite deliberate. 4361 Expr *LHSStripped = lex->IgnoreParens(); 4362 Expr *RHSStripped = rex->IgnoreParens(); 4363 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 4364 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 4365 if (DRL->getDecl() == DRR->getDecl() && 4366 !isa<EnumConstantDecl>(DRL->getDecl())) 4367 Diag(Loc, diag::warn_selfcomparison); 4368 4369 if (isa<CastExpr>(LHSStripped)) 4370 LHSStripped = LHSStripped->IgnoreParenCasts(); 4371 if (isa<CastExpr>(RHSStripped)) 4372 RHSStripped = RHSStripped->IgnoreParenCasts(); 4373 4374 // Warn about comparisons against a string constant (unless the other 4375 // operand is null), the user probably wants strcmp. 4376 Expr *literalString = 0; 4377 Expr *literalStringStripped = 0; 4378 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 4379 !RHSStripped->isNullPointerConstant(Context)) { 4380 literalString = lex; 4381 literalStringStripped = LHSStripped; 4382 } else if ((isa<StringLiteral>(RHSStripped) || 4383 isa<ObjCEncodeExpr>(RHSStripped)) && 4384 !LHSStripped->isNullPointerConstant(Context)) { 4385 literalString = rex; 4386 literalStringStripped = RHSStripped; 4387 } 4388 4389 if (literalString) { 4390 std::string resultComparison; 4391 switch (Opc) { 4392 case BinaryOperator::LT: resultComparison = ") < 0"; break; 4393 case BinaryOperator::GT: resultComparison = ") > 0"; break; 4394 case BinaryOperator::LE: resultComparison = ") <= 0"; break; 4395 case BinaryOperator::GE: resultComparison = ") >= 0"; break; 4396 case BinaryOperator::EQ: resultComparison = ") == 0"; break; 4397 case BinaryOperator::NE: resultComparison = ") != 0"; break; 4398 default: assert(false && "Invalid comparison operator"); 4399 } 4400 Diag(Loc, diag::warn_stringcompare) 4401 << isa<ObjCEncodeExpr>(literalStringStripped) 4402 << literalString->getSourceRange() 4403 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ") 4404 << CodeModificationHint::CreateInsertion(lex->getLocStart(), 4405 "strcmp(") 4406 << CodeModificationHint::CreateInsertion( 4407 PP.getLocForEndOfToken(rex->getLocEnd()), 4408 resultComparison); 4409 } 4410 } 4411 4412 // The result of comparisons is 'bool' in C++, 'int' in C. 4413 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; 4414 4415 if (isRelational) { 4416 if (lType->isRealType() && rType->isRealType()) 4417 return ResultTy; 4418 } else { 4419 // Check for comparisons of floating point operands using != and ==. 4420 if (lType->isFloatingType()) { 4421 assert(rType->isFloatingType()); 4422 CheckFloatComparison(Loc,lex,rex); 4423 } 4424 4425 if (lType->isArithmeticType() && rType->isArithmeticType()) 4426 return ResultTy; 4427 } 4428 4429 bool LHSIsNull = lex->isNullPointerConstant(Context); 4430 bool RHSIsNull = rex->isNullPointerConstant(Context); 4431 4432 // All of the following pointer related warnings are GCC extensions, except 4433 // when handling null pointer constants. One day, we can consider making them 4434 // errors (when -pedantic-errors is enabled). 4435 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 4436 QualType LCanPointeeTy = 4437 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 4438 QualType RCanPointeeTy = 4439 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 4440 4441 if (getLangOptions().CPlusPlus) { 4442 if (LCanPointeeTy == RCanPointeeTy) 4443 return ResultTy; 4444 4445 // C++ [expr.rel]p2: 4446 // [...] Pointer conversions (4.10) and qualification 4447 // conversions (4.4) are performed on pointer operands (or on 4448 // a pointer operand and a null pointer constant) to bring 4449 // them to their composite pointer type. [...] 4450 // 4451 // C++ [expr.eq]p1 uses the same notion for (in)equality 4452 // comparisons of pointers. 4453 QualType T = FindCompositePointerType(lex, rex); 4454 if (T.isNull()) { 4455 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 4456 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4457 return QualType(); 4458 } 4459 4460 ImpCastExprToType(lex, T); 4461 ImpCastExprToType(rex, T); 4462 return ResultTy; 4463 } 4464 // C99 6.5.9p2 and C99 6.5.8p2 4465 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 4466 RCanPointeeTy.getUnqualifiedType())) { 4467 // Valid unless a relational comparison of function pointers 4468 if (isRelational && LCanPointeeTy->isFunctionType()) { 4469 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 4470 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4471 } 4472 } else if (!isRelational && 4473 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 4474 // Valid unless comparison between non-null pointer and function pointer 4475 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 4476 && !LHSIsNull && !RHSIsNull) { 4477 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 4478 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4479 } 4480 } else { 4481 // Invalid 4482 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4483 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4484 } 4485 if (LCanPointeeTy != RCanPointeeTy) 4486 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4487 return ResultTy; 4488 } 4489 4490 if (getLangOptions().CPlusPlus) { 4491 // Comparison of pointers with null pointer constants and equality 4492 // comparisons of member pointers to null pointer constants. 4493 if (RHSIsNull && 4494 (lType->isPointerType() || 4495 (!isRelational && lType->isMemberPointerType()))) { 4496 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer); 4497 return ResultTy; 4498 } 4499 if (LHSIsNull && 4500 (rType->isPointerType() || 4501 (!isRelational && rType->isMemberPointerType()))) { 4502 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer); 4503 return ResultTy; 4504 } 4505 4506 // Comparison of member pointers. 4507 if (!isRelational && 4508 lType->isMemberPointerType() && rType->isMemberPointerType()) { 4509 // C++ [expr.eq]p2: 4510 // In addition, pointers to members can be compared, or a pointer to 4511 // member and a null pointer constant. Pointer to member conversions 4512 // (4.11) and qualification conversions (4.4) are performed to bring 4513 // them to a common type. If one operand is a null pointer constant, 4514 // the common type is the type of the other operand. Otherwise, the 4515 // common type is a pointer to member type similar (4.4) to the type 4516 // of one of the operands, with a cv-qualification signature (4.4) 4517 // that is the union of the cv-qualification signatures of the operand 4518 // types. 4519 QualType T = FindCompositePointerType(lex, rex); 4520 if (T.isNull()) { 4521 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 4522 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4523 return QualType(); 4524 } 4525 4526 ImpCastExprToType(lex, T); 4527 ImpCastExprToType(rex, T); 4528 return ResultTy; 4529 } 4530 4531 // Comparison of nullptr_t with itself. 4532 if (lType->isNullPtrType() && rType->isNullPtrType()) 4533 return ResultTy; 4534 } 4535 4536 // Handle block pointer types. 4537 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 4538 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 4539 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 4540 4541 if (!LHSIsNull && !RHSIsNull && 4542 !Context.typesAreCompatible(lpointee, rpointee)) { 4543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4544 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4545 } 4546 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4547 return ResultTy; 4548 } 4549 // Allow block pointers to be compared with null pointer constants. 4550 if (!isRelational 4551 && ((lType->isBlockPointerType() && rType->isPointerType()) 4552 || (lType->isPointerType() && rType->isBlockPointerType()))) { 4553 if (!LHSIsNull && !RHSIsNull) { 4554 if (!((rType->isPointerType() && rType->getAs<PointerType>() 4555 ->getPointeeType()->isVoidType()) 4556 || (lType->isPointerType() && lType->getAs<PointerType>() 4557 ->getPointeeType()->isVoidType()))) 4558 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4559 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4560 } 4561 ImpCastExprToType(rex, lType); // promote the pointer to pointer 4562 return ResultTy; 4563 } 4564 4565 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) { 4566 if (lType->isPointerType() || rType->isPointerType()) { 4567 const PointerType *LPT = lType->getAs<PointerType>(); 4568 const PointerType *RPT = rType->getAs<PointerType>(); 4569 bool LPtrToVoid = LPT ? 4570 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 4571 bool RPtrToVoid = RPT ? 4572 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 4573 4574 if (!LPtrToVoid && !RPtrToVoid && 4575 !Context.typesAreCompatible(lType, rType)) { 4576 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4577 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4578 } 4579 ImpCastExprToType(rex, lType); 4580 return ResultTy; 4581 } 4582 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 4583 if (!Context.areComparableObjCPointerTypes(lType, rType)) 4584 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4585 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4586 ImpCastExprToType(rex, lType); 4587 return ResultTy; 4588 } 4589 } 4590 if (lType->isAnyPointerType() && rType->isIntegerType()) { 4591 unsigned DiagID = 0; 4592 if (RHSIsNull) { 4593 if (isRelational) 4594 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 4595 } else if (isRelational) 4596 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 4597 else 4598 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 4599 4600 if (DiagID) { 4601 Diag(Loc, DiagID) 4602 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4603 } 4604 ImpCastExprToType(rex, lType); // promote the integer to pointer 4605 return ResultTy; 4606 } 4607 if (lType->isIntegerType() && rType->isAnyPointerType()) { 4608 unsigned DiagID = 0; 4609 if (LHSIsNull) { 4610 if (isRelational) 4611 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 4612 } else if (isRelational) 4613 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 4614 else 4615 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 4616 4617 if (DiagID) { 4618 Diag(Loc, DiagID) 4619 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4620 } 4621 ImpCastExprToType(lex, rType); // promote the integer to pointer 4622 return ResultTy; 4623 } 4624 // Handle block pointers. 4625 if (!isRelational && RHSIsNull 4626 && lType->isBlockPointerType() && rType->isIntegerType()) { 4627 ImpCastExprToType(rex, lType); // promote the integer to pointer 4628 return ResultTy; 4629 } 4630 if (!isRelational && LHSIsNull 4631 && lType->isIntegerType() && rType->isBlockPointerType()) { 4632 ImpCastExprToType(lex, rType); // promote the integer to pointer 4633 return ResultTy; 4634 } 4635 return InvalidOperands(Loc, lex, rex); 4636} 4637 4638/// CheckVectorCompareOperands - vector comparisons are a clang extension that 4639/// operates on extended vector types. Instead of producing an IntTy result, 4640/// like a scalar comparison, a vector comparison produces a vector of integer 4641/// types. 4642QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 4643 SourceLocation Loc, 4644 bool isRelational) { 4645 // Check to make sure we're operating on vectors of the same type and width, 4646 // Allowing one side to be a scalar of element type. 4647 QualType vType = CheckVectorOperands(Loc, lex, rex); 4648 if (vType.isNull()) 4649 return vType; 4650 4651 QualType lType = lex->getType(); 4652 QualType rType = rex->getType(); 4653 4654 // For non-floating point types, check for self-comparisons of the form 4655 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4656 // often indicate logic errors in the program. 4657 if (!lType->isFloatingType()) { 4658 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 4659 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 4660 if (DRL->getDecl() == DRR->getDecl()) 4661 Diag(Loc, diag::warn_selfcomparison); 4662 } 4663 4664 // Check for comparisons of floating point operands using != and ==. 4665 if (!isRelational && lType->isFloatingType()) { 4666 assert (rType->isFloatingType()); 4667 CheckFloatComparison(Loc,lex,rex); 4668 } 4669 4670 // Return the type for the comparison, which is the same as vector type for 4671 // integer vectors, or an integer type of identical size and number of 4672 // elements for floating point vectors. 4673 if (lType->isIntegerType()) 4674 return lType; 4675 4676 const VectorType *VTy = lType->getAsVectorType(); 4677 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 4678 if (TypeSize == Context.getTypeSize(Context.IntTy)) 4679 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 4680 if (TypeSize == Context.getTypeSize(Context.LongTy)) 4681 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 4682 4683 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 4684 "Unhandled vector element size in vector compare"); 4685 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 4686} 4687 4688inline QualType Sema::CheckBitwiseOperands( 4689 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 4690{ 4691 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4692 return CheckVectorOperands(Loc, lex, rex); 4693 4694 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4695 4696 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4697 return compType; 4698 return InvalidOperands(Loc, lex, rex); 4699} 4700 4701inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 4702 Expr *&lex, Expr *&rex, SourceLocation Loc) 4703{ 4704 UsualUnaryConversions(lex); 4705 UsualUnaryConversions(rex); 4706 4707 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 4708 return Context.IntTy; 4709 return InvalidOperands(Loc, lex, rex); 4710} 4711 4712/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 4713/// is a read-only property; return true if so. A readonly property expression 4714/// depends on various declarations and thus must be treated specially. 4715/// 4716static bool IsReadonlyProperty(Expr *E, Sema &S) 4717{ 4718 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 4719 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 4720 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 4721 QualType BaseType = PropExpr->getBase()->getType(); 4722 if (const ObjCObjectPointerType *OPT = 4723 BaseType->getAsObjCInterfacePointerType()) 4724 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 4725 if (S.isPropertyReadonly(PDecl, IFace)) 4726 return true; 4727 } 4728 } 4729 return false; 4730} 4731 4732/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 4733/// emit an error and return true. If so, return false. 4734static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 4735 SourceLocation OrigLoc = Loc; 4736 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 4737 &Loc); 4738 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 4739 IsLV = Expr::MLV_ReadonlyProperty; 4740 if (IsLV == Expr::MLV_Valid) 4741 return false; 4742 4743 unsigned Diag = 0; 4744 bool NeedType = false; 4745 switch (IsLV) { // C99 6.5.16p2 4746 default: assert(0 && "Unknown result from isModifiableLvalue!"); 4747 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 4748 case Expr::MLV_ArrayType: 4749 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 4750 NeedType = true; 4751 break; 4752 case Expr::MLV_NotObjectType: 4753 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 4754 NeedType = true; 4755 break; 4756 case Expr::MLV_LValueCast: 4757 Diag = diag::err_typecheck_lvalue_casts_not_supported; 4758 break; 4759 case Expr::MLV_InvalidExpression: 4760 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 4761 break; 4762 case Expr::MLV_IncompleteType: 4763 case Expr::MLV_IncompleteVoidType: 4764 return S.RequireCompleteType(Loc, E->getType(), 4765 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 4766 << E->getSourceRange()); 4767 case Expr::MLV_DuplicateVectorComponents: 4768 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 4769 break; 4770 case Expr::MLV_NotBlockQualified: 4771 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 4772 break; 4773 case Expr::MLV_ReadonlyProperty: 4774 Diag = diag::error_readonly_property_assignment; 4775 break; 4776 case Expr::MLV_NoSetterProperty: 4777 Diag = diag::error_nosetter_property_assignment; 4778 break; 4779 } 4780 4781 SourceRange Assign; 4782 if (Loc != OrigLoc) 4783 Assign = SourceRange(OrigLoc, OrigLoc); 4784 if (NeedType) 4785 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 4786 else 4787 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 4788 return true; 4789} 4790 4791 4792 4793// C99 6.5.16.1 4794QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 4795 SourceLocation Loc, 4796 QualType CompoundType) { 4797 // Verify that LHS is a modifiable lvalue, and emit error if not. 4798 if (CheckForModifiableLvalue(LHS, Loc, *this)) 4799 return QualType(); 4800 4801 QualType LHSType = LHS->getType(); 4802 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 4803 4804 AssignConvertType ConvTy; 4805 if (CompoundType.isNull()) { 4806 // Simple assignment "x = y". 4807 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 4808 // Special case of NSObject attributes on c-style pointer types. 4809 if (ConvTy == IncompatiblePointer && 4810 ((Context.isObjCNSObjectType(LHSType) && 4811 RHSType->isObjCObjectPointerType()) || 4812 (Context.isObjCNSObjectType(RHSType) && 4813 LHSType->isObjCObjectPointerType()))) 4814 ConvTy = Compatible; 4815 4816 // If the RHS is a unary plus or minus, check to see if they = and + are 4817 // right next to each other. If so, the user may have typo'd "x =+ 4" 4818 // instead of "x += 4". 4819 Expr *RHSCheck = RHS; 4820 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 4821 RHSCheck = ICE->getSubExpr(); 4822 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 4823 if ((UO->getOpcode() == UnaryOperator::Plus || 4824 UO->getOpcode() == UnaryOperator::Minus) && 4825 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 4826 // Only if the two operators are exactly adjacent. 4827 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 4828 // And there is a space or other character before the subexpr of the 4829 // unary +/-. We don't want to warn on "x=-1". 4830 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 4831 UO->getSubExpr()->getLocStart().isFileID()) { 4832 Diag(Loc, diag::warn_not_compound_assign) 4833 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 4834 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 4835 } 4836 } 4837 } else { 4838 // Compound assignment "x += y" 4839 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 4840 } 4841 4842 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 4843 RHS, "assigning")) 4844 return QualType(); 4845 4846 // C99 6.5.16p3: The type of an assignment expression is the type of the 4847 // left operand unless the left operand has qualified type, in which case 4848 // it is the unqualified version of the type of the left operand. 4849 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 4850 // is converted to the type of the assignment expression (above). 4851 // C++ 5.17p1: the type of the assignment expression is that of its left 4852 // operand. 4853 return LHSType.getUnqualifiedType(); 4854} 4855 4856// C99 6.5.17 4857QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 4858 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 4859 DefaultFunctionArrayConversion(RHS); 4860 4861 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be 4862 // incomplete in C++). 4863 4864 return RHS->getType(); 4865} 4866 4867/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 4868/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 4869QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 4870 bool isInc) { 4871 if (Op->isTypeDependent()) 4872 return Context.DependentTy; 4873 4874 QualType ResType = Op->getType(); 4875 assert(!ResType.isNull() && "no type for increment/decrement expression"); 4876 4877 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 4878 // Decrement of bool is not allowed. 4879 if (!isInc) { 4880 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 4881 return QualType(); 4882 } 4883 // Increment of bool sets it to true, but is deprecated. 4884 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 4885 } else if (ResType->isRealType()) { 4886 // OK! 4887 } else if (ResType->isAnyPointerType()) { 4888 QualType PointeeTy = ResType->getPointeeType(); 4889 4890 // C99 6.5.2.4p2, 6.5.6p2 4891 if (PointeeTy->isVoidType()) { 4892 if (getLangOptions().CPlusPlus) { 4893 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 4894 << Op->getSourceRange(); 4895 return QualType(); 4896 } 4897 4898 // Pointer to void is a GNU extension in C. 4899 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 4900 } else if (PointeeTy->isFunctionType()) { 4901 if (getLangOptions().CPlusPlus) { 4902 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 4903 << Op->getType() << Op->getSourceRange(); 4904 return QualType(); 4905 } 4906 4907 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 4908 << ResType << Op->getSourceRange(); 4909 } else if (RequireCompleteType(OpLoc, PointeeTy, 4910 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 4911 << Op->getSourceRange() 4912 << ResType)) 4913 return QualType(); 4914 // Diagnose bad cases where we step over interface counts. 4915 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 4916 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 4917 << PointeeTy << Op->getSourceRange(); 4918 return QualType(); 4919 } 4920 } else if (ResType->isComplexType()) { 4921 // C99 does not support ++/-- on complex types, we allow as an extension. 4922 Diag(OpLoc, diag::ext_integer_increment_complex) 4923 << ResType << Op->getSourceRange(); 4924 } else { 4925 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 4926 << ResType << Op->getSourceRange(); 4927 return QualType(); 4928 } 4929 // At this point, we know we have a real, complex or pointer type. 4930 // Now make sure the operand is a modifiable lvalue. 4931 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 4932 return QualType(); 4933 return ResType; 4934} 4935 4936/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 4937/// This routine allows us to typecheck complex/recursive expressions 4938/// where the declaration is needed for type checking. We only need to 4939/// handle cases when the expression references a function designator 4940/// or is an lvalue. Here are some examples: 4941/// - &(x) => x 4942/// - &*****f => f for f a function designator. 4943/// - &s.xx => s 4944/// - &s.zz[1].yy -> s, if zz is an array 4945/// - *(x + 1) -> x, if x is an array 4946/// - &"123"[2] -> 0 4947/// - & __real__ x -> x 4948static NamedDecl *getPrimaryDecl(Expr *E) { 4949 switch (E->getStmtClass()) { 4950 case Stmt::DeclRefExprClass: 4951 case Stmt::QualifiedDeclRefExprClass: 4952 return cast<DeclRefExpr>(E)->getDecl(); 4953 case Stmt::MemberExprClass: 4954 // If this is an arrow operator, the address is an offset from 4955 // the base's value, so the object the base refers to is 4956 // irrelevant. 4957 if (cast<MemberExpr>(E)->isArrow()) 4958 return 0; 4959 // Otherwise, the expression refers to a part of the base 4960 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 4961 case Stmt::ArraySubscriptExprClass: { 4962 // FIXME: This code shouldn't be necessary! We should catch the implicit 4963 // promotion of register arrays earlier. 4964 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 4965 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 4966 if (ICE->getSubExpr()->getType()->isArrayType()) 4967 return getPrimaryDecl(ICE->getSubExpr()); 4968 } 4969 return 0; 4970 } 4971 case Stmt::UnaryOperatorClass: { 4972 UnaryOperator *UO = cast<UnaryOperator>(E); 4973 4974 switch(UO->getOpcode()) { 4975 case UnaryOperator::Real: 4976 case UnaryOperator::Imag: 4977 case UnaryOperator::Extension: 4978 return getPrimaryDecl(UO->getSubExpr()); 4979 default: 4980 return 0; 4981 } 4982 } 4983 case Stmt::ParenExprClass: 4984 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 4985 case Stmt::ImplicitCastExprClass: 4986 // If the result of an implicit cast is an l-value, we care about 4987 // the sub-expression; otherwise, the result here doesn't matter. 4988 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 4989 default: 4990 return 0; 4991 } 4992} 4993 4994/// CheckAddressOfOperand - The operand of & must be either a function 4995/// designator or an lvalue designating an object. If it is an lvalue, the 4996/// object cannot be declared with storage class register or be a bit field. 4997/// Note: The usual conversions are *not* applied to the operand of the & 4998/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 4999/// In C++, the operand might be an overloaded function name, in which case 5000/// we allow the '&' but retain the overloaded-function type. 5001QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 5002 // Make sure to ignore parentheses in subsequent checks 5003 op = op->IgnoreParens(); 5004 5005 if (op->isTypeDependent()) 5006 return Context.DependentTy; 5007 5008 if (getLangOptions().C99) { 5009 // Implement C99-only parts of addressof rules. 5010 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 5011 if (uOp->getOpcode() == UnaryOperator::Deref) 5012 // Per C99 6.5.3.2, the address of a deref always returns a valid result 5013 // (assuming the deref expression is valid). 5014 return uOp->getSubExpr()->getType(); 5015 } 5016 // Technically, there should be a check for array subscript 5017 // expressions here, but the result of one is always an lvalue anyway. 5018 } 5019 NamedDecl *dcl = getPrimaryDecl(op); 5020 Expr::isLvalueResult lval = op->isLvalue(Context); 5021 5022 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 5023 // C99 6.5.3.2p1 5024 // The operand must be either an l-value or a function designator 5025 if (!op->getType()->isFunctionType()) { 5026 // FIXME: emit more specific diag... 5027 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 5028 << op->getSourceRange(); 5029 return QualType(); 5030 } 5031 } else if (op->getBitField()) { // C99 6.5.3.2p1 5032 // The operand cannot be a bit-field 5033 Diag(OpLoc, diag::err_typecheck_address_of) 5034 << "bit-field" << op->getSourceRange(); 5035 return QualType(); 5036 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 5037 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 5038 // The operand cannot be an element of a vector 5039 Diag(OpLoc, diag::err_typecheck_address_of) 5040 << "vector element" << op->getSourceRange(); 5041 return QualType(); 5042 } else if (isa<ObjCPropertyRefExpr>(op)) { 5043 // cannot take address of a property expression. 5044 Diag(OpLoc, diag::err_typecheck_address_of) 5045 << "property expression" << op->getSourceRange(); 5046 return QualType(); 5047 } else if (dcl) { // C99 6.5.3.2p1 5048 // We have an lvalue with a decl. Make sure the decl is not declared 5049 // with the register storage-class specifier. 5050 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 5051 if (vd->getStorageClass() == VarDecl::Register) { 5052 Diag(OpLoc, diag::err_typecheck_address_of) 5053 << "register variable" << op->getSourceRange(); 5054 return QualType(); 5055 } 5056 } else if (isa<OverloadedFunctionDecl>(dcl) || 5057 isa<FunctionTemplateDecl>(dcl)) { 5058 return Context.OverloadTy; 5059 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 5060 // Okay: we can take the address of a field. 5061 // Could be a pointer to member, though, if there is an explicit 5062 // scope qualifier for the class. 5063 if (isa<QualifiedDeclRefExpr>(op)) { 5064 DeclContext *Ctx = dcl->getDeclContext(); 5065 if (Ctx && Ctx->isRecord()) { 5066 if (FD->getType()->isReferenceType()) { 5067 Diag(OpLoc, 5068 diag::err_cannot_form_pointer_to_member_of_reference_type) 5069 << FD->getDeclName() << FD->getType(); 5070 return QualType(); 5071 } 5072 5073 return Context.getMemberPointerType(op->getType(), 5074 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 5075 } 5076 } 5077 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) { 5078 // Okay: we can take the address of a function. 5079 // As above. 5080 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance()) 5081 return Context.getMemberPointerType(op->getType(), 5082 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 5083 } else if (!isa<FunctionDecl>(dcl)) 5084 assert(0 && "Unknown/unexpected decl type"); 5085 } 5086 5087 if (lval == Expr::LV_IncompleteVoidType) { 5088 // Taking the address of a void variable is technically illegal, but we 5089 // allow it in cases which are otherwise valid. 5090 // Example: "extern void x; void* y = &x;". 5091 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 5092 } 5093 5094 // If the operand has type "type", the result has type "pointer to type". 5095 return Context.getPointerType(op->getType()); 5096} 5097 5098QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 5099 if (Op->isTypeDependent()) 5100 return Context.DependentTy; 5101 5102 UsualUnaryConversions(Op); 5103 QualType Ty = Op->getType(); 5104 5105 // Note that per both C89 and C99, this is always legal, even if ptype is an 5106 // incomplete type or void. It would be possible to warn about dereferencing 5107 // a void pointer, but it's completely well-defined, and such a warning is 5108 // unlikely to catch any mistakes. 5109 if (const PointerType *PT = Ty->getAs<PointerType>()) 5110 return PT->getPointeeType(); 5111 5112 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType()) 5113 return OPT->getPointeeType(); 5114 5115 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 5116 << Ty << Op->getSourceRange(); 5117 return QualType(); 5118} 5119 5120static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 5121 tok::TokenKind Kind) { 5122 BinaryOperator::Opcode Opc; 5123 switch (Kind) { 5124 default: assert(0 && "Unknown binop!"); 5125 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 5126 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 5127 case tok::star: Opc = BinaryOperator::Mul; break; 5128 case tok::slash: Opc = BinaryOperator::Div; break; 5129 case tok::percent: Opc = BinaryOperator::Rem; break; 5130 case tok::plus: Opc = BinaryOperator::Add; break; 5131 case tok::minus: Opc = BinaryOperator::Sub; break; 5132 case tok::lessless: Opc = BinaryOperator::Shl; break; 5133 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 5134 case tok::lessequal: Opc = BinaryOperator::LE; break; 5135 case tok::less: Opc = BinaryOperator::LT; break; 5136 case tok::greaterequal: Opc = BinaryOperator::GE; break; 5137 case tok::greater: Opc = BinaryOperator::GT; break; 5138 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 5139 case tok::equalequal: Opc = BinaryOperator::EQ; break; 5140 case tok::amp: Opc = BinaryOperator::And; break; 5141 case tok::caret: Opc = BinaryOperator::Xor; break; 5142 case tok::pipe: Opc = BinaryOperator::Or; break; 5143 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 5144 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 5145 case tok::equal: Opc = BinaryOperator::Assign; break; 5146 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 5147 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 5148 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 5149 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 5150 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 5151 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 5152 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 5153 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 5154 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 5155 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 5156 case tok::comma: Opc = BinaryOperator::Comma; break; 5157 } 5158 return Opc; 5159} 5160 5161static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 5162 tok::TokenKind Kind) { 5163 UnaryOperator::Opcode Opc; 5164 switch (Kind) { 5165 default: assert(0 && "Unknown unary op!"); 5166 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 5167 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 5168 case tok::amp: Opc = UnaryOperator::AddrOf; break; 5169 case tok::star: Opc = UnaryOperator::Deref; break; 5170 case tok::plus: Opc = UnaryOperator::Plus; break; 5171 case tok::minus: Opc = UnaryOperator::Minus; break; 5172 case tok::tilde: Opc = UnaryOperator::Not; break; 5173 case tok::exclaim: Opc = UnaryOperator::LNot; break; 5174 case tok::kw___real: Opc = UnaryOperator::Real; break; 5175 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 5176 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 5177 } 5178 return Opc; 5179} 5180 5181/// CreateBuiltinBinOp - Creates a new built-in binary operation with 5182/// operator @p Opc at location @c TokLoc. This routine only supports 5183/// built-in operations; ActOnBinOp handles overloaded operators. 5184Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 5185 unsigned Op, 5186 Expr *lhs, Expr *rhs) { 5187 QualType ResultTy; // Result type of the binary operator. 5188 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 5189 // The following two variables are used for compound assignment operators 5190 QualType CompLHSTy; // Type of LHS after promotions for computation 5191 QualType CompResultTy; // Type of computation result 5192 5193 switch (Opc) { 5194 case BinaryOperator::Assign: 5195 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 5196 break; 5197 case BinaryOperator::PtrMemD: 5198 case BinaryOperator::PtrMemI: 5199 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 5200 Opc == BinaryOperator::PtrMemI); 5201 break; 5202 case BinaryOperator::Mul: 5203 case BinaryOperator::Div: 5204 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 5205 break; 5206 case BinaryOperator::Rem: 5207 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 5208 break; 5209 case BinaryOperator::Add: 5210 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 5211 break; 5212 case BinaryOperator::Sub: 5213 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 5214 break; 5215 case BinaryOperator::Shl: 5216 case BinaryOperator::Shr: 5217 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 5218 break; 5219 case BinaryOperator::LE: 5220 case BinaryOperator::LT: 5221 case BinaryOperator::GE: 5222 case BinaryOperator::GT: 5223 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 5224 break; 5225 case BinaryOperator::EQ: 5226 case BinaryOperator::NE: 5227 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 5228 break; 5229 case BinaryOperator::And: 5230 case BinaryOperator::Xor: 5231 case BinaryOperator::Or: 5232 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 5233 break; 5234 case BinaryOperator::LAnd: 5235 case BinaryOperator::LOr: 5236 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 5237 break; 5238 case BinaryOperator::MulAssign: 5239 case BinaryOperator::DivAssign: 5240 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 5241 CompLHSTy = CompResultTy; 5242 if (!CompResultTy.isNull()) 5243 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5244 break; 5245 case BinaryOperator::RemAssign: 5246 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 5247 CompLHSTy = CompResultTy; 5248 if (!CompResultTy.isNull()) 5249 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5250 break; 5251 case BinaryOperator::AddAssign: 5252 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 5253 if (!CompResultTy.isNull()) 5254 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5255 break; 5256 case BinaryOperator::SubAssign: 5257 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 5258 if (!CompResultTy.isNull()) 5259 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5260 break; 5261 case BinaryOperator::ShlAssign: 5262 case BinaryOperator::ShrAssign: 5263 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 5264 CompLHSTy = CompResultTy; 5265 if (!CompResultTy.isNull()) 5266 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5267 break; 5268 case BinaryOperator::AndAssign: 5269 case BinaryOperator::XorAssign: 5270 case BinaryOperator::OrAssign: 5271 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 5272 CompLHSTy = CompResultTy; 5273 if (!CompResultTy.isNull()) 5274 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5275 break; 5276 case BinaryOperator::Comma: 5277 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 5278 break; 5279 } 5280 if (ResultTy.isNull()) 5281 return ExprError(); 5282 if (CompResultTy.isNull()) 5283 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 5284 else 5285 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 5286 CompLHSTy, CompResultTy, 5287 OpLoc)); 5288} 5289 5290// Binary Operators. 'Tok' is the token for the operator. 5291Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 5292 tok::TokenKind Kind, 5293 ExprArg LHS, ExprArg RHS) { 5294 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 5295 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>(); 5296 5297 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 5298 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 5299 5300 if (getLangOptions().CPlusPlus && 5301 (lhs->getType()->isOverloadableType() || 5302 rhs->getType()->isOverloadableType())) { 5303 // Find all of the overloaded operators visible from this 5304 // point. We perform both an operator-name lookup from the local 5305 // scope and an argument-dependent lookup based on the types of 5306 // the arguments. 5307 FunctionSet Functions; 5308 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 5309 if (OverOp != OO_None) { 5310 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 5311 Functions); 5312 Expr *Args[2] = { lhs, rhs }; 5313 DeclarationName OpName 5314 = Context.DeclarationNames.getCXXOperatorName(OverOp); 5315 ArgumentDependentLookup(OpName, Args, 2, Functions); 5316 } 5317 5318 // Build the (potentially-overloaded, potentially-dependent) 5319 // binary operation. 5320 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs); 5321 } 5322 5323 // Build a built-in binary operation. 5324 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 5325} 5326 5327Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 5328 unsigned OpcIn, 5329 ExprArg InputArg) { 5330 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 5331 5332 // FIXME: Input is modified below, but InputArg is not updated appropriately. 5333 Expr *Input = (Expr *)InputArg.get(); 5334 QualType resultType; 5335 switch (Opc) { 5336 case UnaryOperator::OffsetOf: 5337 assert(false && "Invalid unary operator"); 5338 break; 5339 5340 case UnaryOperator::PreInc: 5341 case UnaryOperator::PreDec: 5342 case UnaryOperator::PostInc: 5343 case UnaryOperator::PostDec: 5344 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 5345 Opc == UnaryOperator::PreInc || 5346 Opc == UnaryOperator::PostInc); 5347 break; 5348 case UnaryOperator::AddrOf: 5349 resultType = CheckAddressOfOperand(Input, OpLoc); 5350 break; 5351 case UnaryOperator::Deref: 5352 DefaultFunctionArrayConversion(Input); 5353 resultType = CheckIndirectionOperand(Input, OpLoc); 5354 break; 5355 case UnaryOperator::Plus: 5356 case UnaryOperator::Minus: 5357 UsualUnaryConversions(Input); 5358 resultType = Input->getType(); 5359 if (resultType->isDependentType()) 5360 break; 5361 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 5362 break; 5363 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 5364 resultType->isEnumeralType()) 5365 break; 5366 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 5367 Opc == UnaryOperator::Plus && 5368 resultType->isPointerType()) 5369 break; 5370 5371 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5372 << resultType << Input->getSourceRange()); 5373 case UnaryOperator::Not: // bitwise complement 5374 UsualUnaryConversions(Input); 5375 resultType = Input->getType(); 5376 if (resultType->isDependentType()) 5377 break; 5378 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 5379 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 5380 // C99 does not support '~' for complex conjugation. 5381 Diag(OpLoc, diag::ext_integer_complement_complex) 5382 << resultType << Input->getSourceRange(); 5383 else if (!resultType->isIntegerType()) 5384 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5385 << resultType << Input->getSourceRange()); 5386 break; 5387 case UnaryOperator::LNot: // logical negation 5388 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 5389 DefaultFunctionArrayConversion(Input); 5390 resultType = Input->getType(); 5391 if (resultType->isDependentType()) 5392 break; 5393 if (!resultType->isScalarType()) // C99 6.5.3.3p1 5394 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5395 << resultType << Input->getSourceRange()); 5396 // LNot always has type int. C99 6.5.3.3p5. 5397 // In C++, it's bool. C++ 5.3.1p8 5398 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 5399 break; 5400 case UnaryOperator::Real: 5401 case UnaryOperator::Imag: 5402 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 5403 break; 5404 case UnaryOperator::Extension: 5405 resultType = Input->getType(); 5406 break; 5407 } 5408 if (resultType.isNull()) 5409 return ExprError(); 5410 5411 InputArg.release(); 5412 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 5413} 5414 5415// Unary Operators. 'Tok' is the token for the operator. 5416Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 5417 tok::TokenKind Op, ExprArg input) { 5418 Expr *Input = (Expr*)input.get(); 5419 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 5420 5421 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) { 5422 // Find all of the overloaded operators visible from this 5423 // point. We perform both an operator-name lookup from the local 5424 // scope and an argument-dependent lookup based on the types of 5425 // the arguments. 5426 FunctionSet Functions; 5427 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 5428 if (OverOp != OO_None) { 5429 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 5430 Functions); 5431 DeclarationName OpName 5432 = Context.DeclarationNames.getCXXOperatorName(OverOp); 5433 ArgumentDependentLookup(OpName, &Input, 1, Functions); 5434 } 5435 5436 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input)); 5437 } 5438 5439 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input)); 5440} 5441 5442/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5443Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 5444 SourceLocation LabLoc, 5445 IdentifierInfo *LabelII) { 5446 // Look up the record for this label identifier. 5447 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 5448 5449 // If we haven't seen this label yet, create a forward reference. It 5450 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 5451 if (LabelDecl == 0) 5452 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 5453 5454 // Create the AST node. The address of a label always has type 'void*'. 5455 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 5456 Context.getPointerType(Context.VoidTy))); 5457} 5458 5459Sema::OwningExprResult 5460Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt, 5461 SourceLocation RPLoc) { // "({..})" 5462 Stmt *SubStmt = static_cast<Stmt*>(substmt.get()); 5463 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 5464 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 5465 5466 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 5467 if (isFileScope) 5468 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 5469 5470 // FIXME: there are a variety of strange constraints to enforce here, for 5471 // example, it is not possible to goto into a stmt expression apparently. 5472 // More semantic analysis is needed. 5473 5474 // If there are sub stmts in the compound stmt, take the type of the last one 5475 // as the type of the stmtexpr. 5476 QualType Ty = Context.VoidTy; 5477 5478 if (!Compound->body_empty()) { 5479 Stmt *LastStmt = Compound->body_back(); 5480 // If LastStmt is a label, skip down through into the body. 5481 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 5482 LastStmt = Label->getSubStmt(); 5483 5484 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 5485 Ty = LastExpr->getType(); 5486 } 5487 5488 // FIXME: Check that expression type is complete/non-abstract; statement 5489 // expressions are not lvalues. 5490 5491 substmt.release(); 5492 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 5493} 5494 5495Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 5496 SourceLocation BuiltinLoc, 5497 SourceLocation TypeLoc, 5498 TypeTy *argty, 5499 OffsetOfComponent *CompPtr, 5500 unsigned NumComponents, 5501 SourceLocation RPLoc) { 5502 // FIXME: This function leaks all expressions in the offset components on 5503 // error. 5504 // FIXME: Preserve type source info. 5505 QualType ArgTy = GetTypeFromParser(argty); 5506 assert(!ArgTy.isNull() && "Missing type argument!"); 5507 5508 bool Dependent = ArgTy->isDependentType(); 5509 5510 // We must have at least one component that refers to the type, and the first 5511 // one is known to be a field designator. Verify that the ArgTy represents 5512 // a struct/union/class. 5513 if (!Dependent && !ArgTy->isRecordType()) 5514 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy); 5515 5516 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable 5517 // with an incomplete type would be illegal. 5518 5519 // Otherwise, create a null pointer as the base, and iteratively process 5520 // the offsetof designators. 5521 QualType ArgTyPtr = Context.getPointerType(ArgTy); 5522 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 5523 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 5524 ArgTy, SourceLocation()); 5525 5526 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 5527 // GCC extension, diagnose them. 5528 // FIXME: This diagnostic isn't actually visible because the location is in 5529 // a system header! 5530 if (NumComponents != 1) 5531 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 5532 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 5533 5534 if (!Dependent) { 5535 bool DidWarnAboutNonPOD = false; 5536 5537 // FIXME: Dependent case loses a lot of information here. And probably 5538 // leaks like a sieve. 5539 for (unsigned i = 0; i != NumComponents; ++i) { 5540 const OffsetOfComponent &OC = CompPtr[i]; 5541 if (OC.isBrackets) { 5542 // Offset of an array sub-field. TODO: Should we allow vector elements? 5543 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 5544 if (!AT) { 5545 Res->Destroy(Context); 5546 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 5547 << Res->getType()); 5548 } 5549 5550 // FIXME: C++: Verify that operator[] isn't overloaded. 5551 5552 // Promote the array so it looks more like a normal array subscript 5553 // expression. 5554 DefaultFunctionArrayConversion(Res); 5555 5556 // C99 6.5.2.1p1 5557 Expr *Idx = static_cast<Expr*>(OC.U.E); 5558 // FIXME: Leaks Res 5559 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 5560 return ExprError(Diag(Idx->getLocStart(), 5561 diag::err_typecheck_subscript_not_integer) 5562 << Idx->getSourceRange()); 5563 5564 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 5565 OC.LocEnd); 5566 continue; 5567 } 5568 5569 const RecordType *RC = Res->getType()->getAs<RecordType>(); 5570 if (!RC) { 5571 Res->Destroy(Context); 5572 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 5573 << Res->getType()); 5574 } 5575 5576 // Get the decl corresponding to this. 5577 RecordDecl *RD = RC->getDecl(); 5578 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 5579 if (!CRD->isPOD() && !DidWarnAboutNonPOD) { 5580 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type) 5581 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 5582 << Res->getType()); 5583 DidWarnAboutNonPOD = true; 5584 } 5585 } 5586 5587 FieldDecl *MemberDecl 5588 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, 5589 LookupMemberName) 5590 .getAsDecl()); 5591 // FIXME: Leaks Res 5592 if (!MemberDecl) 5593 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated) 5594 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd)); 5595 5596 // FIXME: C++: Verify that MemberDecl isn't a static field. 5597 // FIXME: Verify that MemberDecl isn't a bitfield. 5598 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) { 5599 Res = BuildAnonymousStructUnionMemberReference( 5600 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>(); 5601 } else { 5602 // MemberDecl->getType() doesn't get the right qualifiers, but it 5603 // doesn't matter here. 5604 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 5605 MemberDecl->getType().getNonReferenceType()); 5606 } 5607 } 5608 } 5609 5610 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 5611 Context.getSizeType(), BuiltinLoc)); 5612} 5613 5614 5615Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 5616 TypeTy *arg1,TypeTy *arg2, 5617 SourceLocation RPLoc) { 5618 // FIXME: Preserve type source info. 5619 QualType argT1 = GetTypeFromParser(arg1); 5620 QualType argT2 = GetTypeFromParser(arg2); 5621 5622 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 5623 5624 if (getLangOptions().CPlusPlus) { 5625 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 5626 << SourceRange(BuiltinLoc, RPLoc); 5627 return ExprError(); 5628 } 5629 5630 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 5631 argT1, argT2, RPLoc)); 5632} 5633 5634Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 5635 ExprArg cond, 5636 ExprArg expr1, ExprArg expr2, 5637 SourceLocation RPLoc) { 5638 Expr *CondExpr = static_cast<Expr*>(cond.get()); 5639 Expr *LHSExpr = static_cast<Expr*>(expr1.get()); 5640 Expr *RHSExpr = static_cast<Expr*>(expr2.get()); 5641 5642 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 5643 5644 QualType resType; 5645 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 5646 resType = Context.DependentTy; 5647 } else { 5648 // The conditional expression is required to be a constant expression. 5649 llvm::APSInt condEval(32); 5650 SourceLocation ExpLoc; 5651 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 5652 return ExprError(Diag(ExpLoc, 5653 diag::err_typecheck_choose_expr_requires_constant) 5654 << CondExpr->getSourceRange()); 5655 5656 // If the condition is > zero, then the AST type is the same as the LSHExpr. 5657 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 5658 } 5659 5660 cond.release(); expr1.release(); expr2.release(); 5661 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 5662 resType, RPLoc)); 5663} 5664 5665//===----------------------------------------------------------------------===// 5666// Clang Extensions. 5667//===----------------------------------------------------------------------===// 5668 5669/// ActOnBlockStart - This callback is invoked when a block literal is started. 5670void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 5671 // Analyze block parameters. 5672 BlockSemaInfo *BSI = new BlockSemaInfo(); 5673 5674 // Add BSI to CurBlock. 5675 BSI->PrevBlockInfo = CurBlock; 5676 CurBlock = BSI; 5677 5678 BSI->ReturnType = QualType(); 5679 BSI->TheScope = BlockScope; 5680 BSI->hasBlockDeclRefExprs = false; 5681 BSI->hasPrototype = false; 5682 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking; 5683 CurFunctionNeedsScopeChecking = false; 5684 5685 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 5686 PushDeclContext(BlockScope, BSI->TheDecl); 5687} 5688 5689void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 5690 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 5691 5692 if (ParamInfo.getNumTypeObjects() == 0 5693 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 5694 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 5695 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 5696 5697 if (T->isArrayType()) { 5698 Diag(ParamInfo.getSourceRange().getBegin(), 5699 diag::err_block_returns_array); 5700 return; 5701 } 5702 5703 // The parameter list is optional, if there was none, assume (). 5704 if (!T->isFunctionType()) 5705 T = Context.getFunctionType(T, NULL, 0, 0, 0); 5706 5707 CurBlock->hasPrototype = true; 5708 CurBlock->isVariadic = false; 5709 // Check for a valid sentinel attribute on this block. 5710 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) { 5711 Diag(ParamInfo.getAttributes()->getLoc(), 5712 diag::warn_attribute_sentinel_not_variadic) << 1; 5713 // FIXME: remove the attribute. 5714 } 5715 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType(); 5716 5717 // Do not allow returning a objc interface by-value. 5718 if (RetTy->isObjCInterfaceType()) { 5719 Diag(ParamInfo.getSourceRange().getBegin(), 5720 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 5721 return; 5722 } 5723 return; 5724 } 5725 5726 // Analyze arguments to block. 5727 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 5728 "Not a function declarator!"); 5729 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 5730 5731 CurBlock->hasPrototype = FTI.hasPrototype; 5732 CurBlock->isVariadic = true; 5733 5734 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 5735 // no arguments, not a function that takes a single void argument. 5736 if (FTI.hasPrototype && 5737 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5738 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&& 5739 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) { 5740 // empty arg list, don't push any params. 5741 CurBlock->isVariadic = false; 5742 } else if (FTI.hasPrototype) { 5743 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 5744 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); 5745 CurBlock->isVariadic = FTI.isVariadic; 5746 } 5747 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(), 5748 CurBlock->Params.size()); 5749 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic); 5750 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 5751 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 5752 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 5753 // If this has an identifier, add it to the scope stack. 5754 if ((*AI)->getIdentifier()) 5755 PushOnScopeChains(*AI, CurBlock->TheScope); 5756 5757 // Check for a valid sentinel attribute on this block. 5758 if (!CurBlock->isVariadic && 5759 CurBlock->TheDecl->getAttr<SentinelAttr>()) { 5760 Diag(ParamInfo.getAttributes()->getLoc(), 5761 diag::warn_attribute_sentinel_not_variadic) << 1; 5762 // FIXME: remove the attribute. 5763 } 5764 5765 // Analyze the return type. 5766 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 5767 QualType RetTy = T->getAsFunctionType()->getResultType(); 5768 5769 // Do not allow returning a objc interface by-value. 5770 if (RetTy->isObjCInterfaceType()) { 5771 Diag(ParamInfo.getSourceRange().getBegin(), 5772 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 5773 } else if (!RetTy->isDependentType()) 5774 CurBlock->ReturnType = RetTy; 5775} 5776 5777/// ActOnBlockError - If there is an error parsing a block, this callback 5778/// is invoked to pop the information about the block from the action impl. 5779void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 5780 // Ensure that CurBlock is deleted. 5781 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 5782 5783 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking; 5784 5785 // Pop off CurBlock, handle nested blocks. 5786 PopDeclContext(); 5787 CurBlock = CurBlock->PrevBlockInfo; 5788 // FIXME: Delete the ParmVarDecl objects as well??? 5789} 5790 5791/// ActOnBlockStmtExpr - This is called when the body of a block statement 5792/// literal was successfully completed. ^(int x){...} 5793Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 5794 StmtArg body, Scope *CurScope) { 5795 // If blocks are disabled, emit an error. 5796 if (!LangOpts.Blocks) 5797 Diag(CaretLoc, diag::err_blocks_disable); 5798 5799 // Ensure that CurBlock is deleted. 5800 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 5801 5802 PopDeclContext(); 5803 5804 // Pop off CurBlock, handle nested blocks. 5805 CurBlock = CurBlock->PrevBlockInfo; 5806 5807 QualType RetTy = Context.VoidTy; 5808 if (!BSI->ReturnType.isNull()) 5809 RetTy = BSI->ReturnType; 5810 5811 llvm::SmallVector<QualType, 8> ArgTypes; 5812 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 5813 ArgTypes.push_back(BSI->Params[i]->getType()); 5814 5815 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 5816 QualType BlockTy; 5817 if (!BSI->hasPrototype) 5818 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0, 5819 NoReturn); 5820 else 5821 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(), 5822 BSI->isVariadic, 0, false, false, 0, 0, 5823 NoReturn); 5824 5825 // FIXME: Check that return/parameter types are complete/non-abstract 5826 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end()); 5827 BlockTy = Context.getBlockPointerType(BlockTy); 5828 5829 // If needed, diagnose invalid gotos and switches in the block. 5830 if (CurFunctionNeedsScopeChecking) 5831 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get())); 5832 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking; 5833 5834 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>()); 5835 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody()); 5836 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy, 5837 BSI->hasBlockDeclRefExprs)); 5838} 5839 5840Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 5841 ExprArg expr, TypeTy *type, 5842 SourceLocation RPLoc) { 5843 QualType T = GetTypeFromParser(type); 5844 Expr *E = static_cast<Expr*>(expr.get()); 5845 Expr *OrigExpr = E; 5846 5847 InitBuiltinVaListType(); 5848 5849 // Get the va_list type 5850 QualType VaListType = Context.getBuiltinVaListType(); 5851 if (VaListType->isArrayType()) { 5852 // Deal with implicit array decay; for example, on x86-64, 5853 // va_list is an array, but it's supposed to decay to 5854 // a pointer for va_arg. 5855 VaListType = Context.getArrayDecayedType(VaListType); 5856 // Make sure the input expression also decays appropriately. 5857 UsualUnaryConversions(E); 5858 } else { 5859 // Otherwise, the va_list argument must be an l-value because 5860 // it is modified by va_arg. 5861 if (!E->isTypeDependent() && 5862 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 5863 return ExprError(); 5864 } 5865 5866 if (!E->isTypeDependent() && 5867 !Context.hasSameType(VaListType, E->getType())) { 5868 return ExprError(Diag(E->getLocStart(), 5869 diag::err_first_argument_to_va_arg_not_of_type_va_list) 5870 << OrigExpr->getType() << E->getSourceRange()); 5871 } 5872 5873 // FIXME: Check that type is complete/non-abstract 5874 // FIXME: Warn if a non-POD type is passed in. 5875 5876 expr.release(); 5877 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), 5878 RPLoc)); 5879} 5880 5881Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 5882 // The type of __null will be int or long, depending on the size of 5883 // pointers on the target. 5884 QualType Ty; 5885 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 5886 Ty = Context.IntTy; 5887 else 5888 Ty = Context.LongTy; 5889 5890 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 5891} 5892 5893bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 5894 SourceLocation Loc, 5895 QualType DstType, QualType SrcType, 5896 Expr *SrcExpr, const char *Flavor) { 5897 // Decode the result (notice that AST's are still created for extensions). 5898 bool isInvalid = false; 5899 unsigned DiagKind; 5900 switch (ConvTy) { 5901 default: assert(0 && "Unknown conversion type"); 5902 case Compatible: return false; 5903 case PointerToInt: 5904 DiagKind = diag::ext_typecheck_convert_pointer_int; 5905 break; 5906 case IntToPointer: 5907 DiagKind = diag::ext_typecheck_convert_int_pointer; 5908 break; 5909 case IncompatiblePointer: 5910 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 5911 break; 5912 case IncompatiblePointerSign: 5913 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 5914 break; 5915 case FunctionVoidPointer: 5916 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 5917 break; 5918 case CompatiblePointerDiscardsQualifiers: 5919 // If the qualifiers lost were because we were applying the 5920 // (deprecated) C++ conversion from a string literal to a char* 5921 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 5922 // Ideally, this check would be performed in 5923 // CheckPointerTypesForAssignment. However, that would require a 5924 // bit of refactoring (so that the second argument is an 5925 // expression, rather than a type), which should be done as part 5926 // of a larger effort to fix CheckPointerTypesForAssignment for 5927 // C++ semantics. 5928 if (getLangOptions().CPlusPlus && 5929 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 5930 return false; 5931 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 5932 break; 5933 case IntToBlockPointer: 5934 DiagKind = diag::err_int_to_block_pointer; 5935 break; 5936 case IncompatibleBlockPointer: 5937 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 5938 break; 5939 case IncompatibleObjCQualifiedId: 5940 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 5941 // it can give a more specific diagnostic. 5942 DiagKind = diag::warn_incompatible_qualified_id; 5943 break; 5944 case IncompatibleVectors: 5945 DiagKind = diag::warn_incompatible_vectors; 5946 break; 5947 case Incompatible: 5948 DiagKind = diag::err_typecheck_convert_incompatible; 5949 isInvalid = true; 5950 break; 5951 } 5952 5953 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 5954 << SrcExpr->getSourceRange(); 5955 return isInvalid; 5956} 5957 5958bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 5959 llvm::APSInt ICEResult; 5960 if (E->isIntegerConstantExpr(ICEResult, Context)) { 5961 if (Result) 5962 *Result = ICEResult; 5963 return false; 5964 } 5965 5966 Expr::EvalResult EvalResult; 5967 5968 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 5969 EvalResult.HasSideEffects) { 5970 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 5971 5972 if (EvalResult.Diag) { 5973 // We only show the note if it's not the usual "invalid subexpression" 5974 // or if it's actually in a subexpression. 5975 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 5976 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 5977 Diag(EvalResult.DiagLoc, EvalResult.Diag); 5978 } 5979 5980 return true; 5981 } 5982 5983 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 5984 E->getSourceRange(); 5985 5986 if (EvalResult.Diag && 5987 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 5988 Diag(EvalResult.DiagLoc, EvalResult.Diag); 5989 5990 if (Result) 5991 *Result = EvalResult.Val.getInt(); 5992 return false; 5993} 5994 5995Sema::ExpressionEvaluationContext 5996Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 5997 // Introduce a new set of potentially referenced declarations to the stack. 5998 if (NewContext == PotentiallyPotentiallyEvaluated) 5999 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls()); 6000 6001 std::swap(ExprEvalContext, NewContext); 6002 return NewContext; 6003} 6004 6005void 6006Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext, 6007 ExpressionEvaluationContext NewContext) { 6008 ExprEvalContext = NewContext; 6009 6010 if (OldContext == PotentiallyPotentiallyEvaluated) { 6011 // Mark any remaining declarations in the current position of the stack 6012 // as "referenced". If they were not meant to be referenced, semantic 6013 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 6014 PotentiallyReferencedDecls RemainingDecls; 6015 RemainingDecls.swap(PotentiallyReferencedDeclStack.back()); 6016 PotentiallyReferencedDeclStack.pop_back(); 6017 6018 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(), 6019 IEnd = RemainingDecls.end(); 6020 I != IEnd; ++I) 6021 MarkDeclarationReferenced(I->first, I->second); 6022 } 6023} 6024 6025/// \brief Note that the given declaration was referenced in the source code. 6026/// 6027/// This routine should be invoke whenever a given declaration is referenced 6028/// in the source code, and where that reference occurred. If this declaration 6029/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 6030/// C99 6.9p3), then the declaration will be marked as used. 6031/// 6032/// \param Loc the location where the declaration was referenced. 6033/// 6034/// \param D the declaration that has been referenced by the source code. 6035void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 6036 assert(D && "No declaration?"); 6037 6038 if (D->isUsed()) 6039 return; 6040 6041 // Mark a parameter declaration "used", regardless of whether we're in a 6042 // template or not. 6043 if (isa<ParmVarDecl>(D)) 6044 D->setUsed(true); 6045 6046 // Do not mark anything as "used" within a dependent context; wait for 6047 // an instantiation. 6048 if (CurContext->isDependentContext()) 6049 return; 6050 6051 switch (ExprEvalContext) { 6052 case Unevaluated: 6053 // We are in an expression that is not potentially evaluated; do nothing. 6054 return; 6055 6056 case PotentiallyEvaluated: 6057 // We are in a potentially-evaluated expression, so this declaration is 6058 // "used"; handle this below. 6059 break; 6060 6061 case PotentiallyPotentiallyEvaluated: 6062 // We are in an expression that may be potentially evaluated; queue this 6063 // declaration reference until we know whether the expression is 6064 // potentially evaluated. 6065 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D)); 6066 return; 6067 } 6068 6069 // Note that this declaration has been used. 6070 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 6071 unsigned TypeQuals; 6072 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 6073 if (!Constructor->isUsed()) 6074 DefineImplicitDefaultConstructor(Loc, Constructor); 6075 } else if (Constructor->isImplicit() && 6076 Constructor->isCopyConstructor(Context, TypeQuals)) { 6077 if (!Constructor->isUsed()) 6078 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 6079 } 6080 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 6081 if (Destructor->isImplicit() && !Destructor->isUsed()) 6082 DefineImplicitDestructor(Loc, Destructor); 6083 6084 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 6085 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 6086 MethodDecl->getOverloadedOperator() == OO_Equal) { 6087 if (!MethodDecl->isUsed()) 6088 DefineImplicitOverloadedAssign(Loc, MethodDecl); 6089 } 6090 } 6091 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 6092 // Implicit instantiation of function templates and member functions of 6093 // class templates. 6094 if (!Function->getBody()) { 6095 // FIXME: distinguish between implicit instantiations of function 6096 // templates and explicit specializations (the latter don't get 6097 // instantiated, naturally). 6098 if (Function->getInstantiatedFromMemberFunction() || 6099 Function->getPrimaryTemplate()) 6100 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc)); 6101 } 6102 6103 6104 // FIXME: keep track of references to static functions 6105 Function->setUsed(true); 6106 return; 6107 } 6108 6109 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 6110 // Implicit instantiation of static data members of class templates. 6111 // FIXME: distinguish between implicit instantiations (which we need to 6112 // actually instantiate) and explicit specializations. 6113 if (Var->isStaticDataMember() && 6114 Var->getInstantiatedFromStaticDataMember()) 6115 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc)); 6116 6117 // FIXME: keep track of references to static data? 6118 6119 D->setUsed(true); 6120 return; 6121} 6122} 6123 6124