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