SemaExpr.cpp revision 2e9eb0477039797d8c3bb2e651a0e044a24d3576
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/ExprCXX.h" 18#include "clang/AST/ExprObjC.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Lex/LiteralSupport.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Designator.h" 26#include "clang/Parse/Scope.h" 27using namespace clang; 28 29/// \brief Determine whether the use of this declaration is valid, and 30/// emit any corresponding diagnostics. 31/// 32/// This routine diagnoses various problems with referencing 33/// declarations that can occur when using a declaration. For example, 34/// it might warn if a deprecated or unavailable declaration is being 35/// used, or produce an error (and return true) if a C++0x deleted 36/// function is being used. 37/// 38/// \returns true if there was an error (this declaration cannot be 39/// referenced), false otherwise. 40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 41 // See if the decl is deprecated. 42 if (D->getAttr<DeprecatedAttr>()) { 43 // Implementing deprecated stuff requires referencing deprecated 44 // stuff. Don't warn if we are implementing a deprecated 45 // construct. 46 bool isSilenced = false; 47 48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) { 49 // If this reference happens *in* a deprecated function or method, don't 50 // warn. 51 isSilenced = ND->getAttr<DeprecatedAttr>(); 52 53 // If this is an Objective-C method implementation, check to see if the 54 // method was deprecated on the declaration, not the definition. 55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) { 56 // The semantic decl context of a ObjCMethodDecl is the 57 // ObjCImplementationDecl. 58 if (ObjCImplementationDecl *Impl 59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) { 60 61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(), 62 MD->isInstanceMethod()); 63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>(); 64 } 65 } 66 } 67 68 if (!isSilenced) 69 Diag(Loc, diag::warn_deprecated) << D->getDeclName(); 70 } 71 72 // See if this is a deleted function. 73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 74 if (FD->isDeleted()) { 75 Diag(Loc, diag::err_deleted_function_use); 76 Diag(D->getLocation(), diag::note_unavailable_here) << true; 77 return true; 78 } 79 } 80 81 // See if the decl is unavailable 82 if (D->getAttr<UnavailableAttr>()) { 83 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 84 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 85 } 86 87 return false; 88} 89 90SourceRange Sema::getExprRange(ExprTy *E) const { 91 Expr *Ex = (Expr *)E; 92 return Ex? Ex->getSourceRange() : SourceRange(); 93} 94 95//===----------------------------------------------------------------------===// 96// Standard Promotions and Conversions 97//===----------------------------------------------------------------------===// 98 99/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 100void Sema::DefaultFunctionArrayConversion(Expr *&E) { 101 QualType Ty = E->getType(); 102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 103 104 if (Ty->isFunctionType()) 105 ImpCastExprToType(E, Context.getPointerType(Ty)); 106 else if (Ty->isArrayType()) { 107 // In C90 mode, arrays only promote to pointers if the array expression is 108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 109 // type 'array of type' is converted to an expression that has type 'pointer 110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 111 // that has type 'array of type' ...". The relevant change is "an lvalue" 112 // (C90) to "an expression" (C99). 113 // 114 // C++ 4.2p1: 115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 116 // T" can be converted to an rvalue of type "pointer to T". 117 // 118 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 119 E->isLvalue(Context) == Expr::LV_Valid) 120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 121 } 122} 123 124/// UsualUnaryConversions - Performs various conversions that are common to most 125/// operators (C99 6.3). The conversions of array and function types are 126/// sometimes surpressed. For example, the array->pointer conversion doesn't 127/// apply if the array is an argument to the sizeof or address (&) operators. 128/// In these instances, this routine should *not* be called. 129Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 130 QualType Ty = Expr->getType(); 131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 132 133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 134 ImpCastExprToType(Expr, Context.IntTy); 135 else 136 DefaultFunctionArrayConversion(Expr); 137 138 return Expr; 139} 140 141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 142/// do not have a prototype. Arguments that have type float are promoted to 143/// double. All other argument types are converted by UsualUnaryConversions(). 144void Sema::DefaultArgumentPromotion(Expr *&Expr) { 145 QualType Ty = Expr->getType(); 146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 147 148 // If this is a 'float' (CVR qualified or typedef) promote to double. 149 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 150 if (BT->getKind() == BuiltinType::Float) 151 return ImpCastExprToType(Expr, Context.DoubleTy); 152 153 UsualUnaryConversions(Expr); 154} 155 156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 157// will warn if the resulting type is not a POD type. 158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 159 DefaultArgumentPromotion(Expr); 160 161 if (!Expr->getType()->isPODType()) { 162 Diag(Expr->getLocStart(), 163 diag::warn_cannot_pass_non_pod_arg_to_vararg) << 164 Expr->getType() << CT; 165 } 166} 167 168 169/// UsualArithmeticConversions - Performs various conversions that are common to 170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 171/// routine returns the first non-arithmetic type found. The client is 172/// responsible for emitting appropriate error diagnostics. 173/// FIXME: verify the conversion rules for "complex int" are consistent with 174/// GCC. 175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 176 bool isCompAssign) { 177 if (!isCompAssign) { 178 UsualUnaryConversions(lhsExpr); 179 UsualUnaryConversions(rhsExpr); 180 } 181 182 // For conversion purposes, we ignore any qualifiers. 183 // For example, "const float" and "float" are equivalent. 184 QualType lhs = 185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 186 QualType rhs = 187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 188 189 // If both types are identical, no conversion is needed. 190 if (lhs == rhs) 191 return lhs; 192 193 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 194 // The caller can deal with this (e.g. pointer + int). 195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 196 return lhs; 197 198 QualType destType = UsualArithmeticConversionsType(lhs, rhs); 199 if (!isCompAssign) { 200 ImpCastExprToType(lhsExpr, destType); 201 ImpCastExprToType(rhsExpr, destType); 202 } 203 return destType; 204} 205 206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 207 // Perform the usual unary conversions. We do this early so that 208 // integral promotions to "int" can allow us to exit early, in the 209 // lhs == rhs check. Also, for conversion purposes, we ignore any 210 // qualifiers. For example, "const float" and "float" are 211 // equivalent. 212 if (lhs->isPromotableIntegerType()) 213 lhs = Context.IntTy; 214 else 215 lhs = lhs.getUnqualifiedType(); 216 if (rhs->isPromotableIntegerType()) 217 rhs = Context.IntTy; 218 else 219 rhs = rhs.getUnqualifiedType(); 220 221 // If both types are identical, no conversion is needed. 222 if (lhs == rhs) 223 return lhs; 224 225 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 226 // The caller can deal with this (e.g. pointer + int). 227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 228 return lhs; 229 230 // At this point, we have two different arithmetic types. 231 232 // Handle complex types first (C99 6.3.1.8p1). 233 if (lhs->isComplexType() || rhs->isComplexType()) { 234 // if we have an integer operand, the result is the complex type. 235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 236 // convert the rhs to the lhs complex type. 237 return lhs; 238 } 239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 240 // convert the lhs to the rhs complex type. 241 return rhs; 242 } 243 // This handles complex/complex, complex/float, or float/complex. 244 // When both operands are complex, the shorter operand is converted to the 245 // type of the longer, and that is the type of the result. This corresponds 246 // to what is done when combining two real floating-point operands. 247 // The fun begins when size promotion occur across type domains. 248 // From H&S 6.3.4: When one operand is complex and the other is a real 249 // floating-point type, the less precise type is converted, within it's 250 // real or complex domain, to the precision of the other type. For example, 251 // when combining a "long double" with a "double _Complex", the 252 // "double _Complex" is promoted to "long double _Complex". 253 int result = Context.getFloatingTypeOrder(lhs, rhs); 254 255 if (result > 0) { // The left side is bigger, convert rhs. 256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 257 } else if (result < 0) { // The right side is bigger, convert lhs. 258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 259 } 260 // At this point, lhs and rhs have the same rank/size. Now, make sure the 261 // domains match. This is a requirement for our implementation, C99 262 // does not require this promotion. 263 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 265 return rhs; 266 } else { // handle "_Complex double, double". 267 return lhs; 268 } 269 } 270 return lhs; // The domain/size match exactly. 271 } 272 // Now handle "real" floating types (i.e. float, double, long double). 273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 274 // if we have an integer operand, the result is the real floating type. 275 if (rhs->isIntegerType()) { 276 // convert rhs to the lhs floating point type. 277 return lhs; 278 } 279 if (rhs->isComplexIntegerType()) { 280 // convert rhs to the complex floating point type. 281 return Context.getComplexType(lhs); 282 } 283 if (lhs->isIntegerType()) { 284 // convert lhs to the rhs floating point type. 285 return rhs; 286 } 287 if (lhs->isComplexIntegerType()) { 288 // convert lhs to the complex floating point type. 289 return Context.getComplexType(rhs); 290 } 291 // We have two real floating types, float/complex combos were handled above. 292 // Convert the smaller operand to the bigger result. 293 int result = Context.getFloatingTypeOrder(lhs, rhs); 294 if (result > 0) // convert the rhs 295 return lhs; 296 assert(result < 0 && "illegal float comparison"); 297 return rhs; // convert the lhs 298 } 299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 300 // Handle GCC complex int extension. 301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 303 304 if (lhsComplexInt && rhsComplexInt) { 305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 306 rhsComplexInt->getElementType()) >= 0) 307 return lhs; // convert the rhs 308 return rhs; 309 } else if (lhsComplexInt && rhs->isIntegerType()) { 310 // convert the rhs to the lhs complex type. 311 return lhs; 312 } else if (rhsComplexInt && lhs->isIntegerType()) { 313 // convert the lhs to the rhs complex type. 314 return rhs; 315 } 316 } 317 // Finally, we have two differing integer types. 318 // The rules for this case are in C99 6.3.1.8 319 int compare = Context.getIntegerTypeOrder(lhs, rhs); 320 bool lhsSigned = lhs->isSignedIntegerType(), 321 rhsSigned = rhs->isSignedIntegerType(); 322 QualType destType; 323 if (lhsSigned == rhsSigned) { 324 // Same signedness; use the higher-ranked type 325 destType = compare >= 0 ? lhs : rhs; 326 } else if (compare != (lhsSigned ? 1 : -1)) { 327 // The unsigned type has greater than or equal rank to the 328 // signed type, so use the unsigned type 329 destType = lhsSigned ? rhs : lhs; 330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 331 // The two types are different widths; if we are here, that 332 // means the signed type is larger than the unsigned type, so 333 // use the signed type. 334 destType = lhsSigned ? lhs : rhs; 335 } else { 336 // The signed type is higher-ranked than the unsigned type, 337 // but isn't actually any bigger (like unsigned int and long 338 // on most 32-bit systems). Use the unsigned type corresponding 339 // to the signed type. 340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 341 } 342 return destType; 343} 344 345//===----------------------------------------------------------------------===// 346// Semantic Analysis for various Expression Types 347//===----------------------------------------------------------------------===// 348 349 350/// ActOnStringLiteral - The specified tokens were lexed as pasted string 351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 353/// multiple tokens. However, the common case is that StringToks points to one 354/// string. 355/// 356Action::OwningExprResult 357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 358 assert(NumStringToks && "Must have at least one string!"); 359 360 StringLiteralParser Literal(StringToks, NumStringToks, PP); 361 if (Literal.hadError) 362 return ExprError(); 363 364 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 365 for (unsigned i = 0; i != NumStringToks; ++i) 366 StringTokLocs.push_back(StringToks[i].getLocation()); 367 368 QualType StrTy = Context.CharTy; 369 if (Literal.AnyWide) StrTy = Context.getWCharType(); 370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 371 372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 373 if (getLangOptions().CPlusPlus) 374 StrTy.addConst(); 375 376 // Get an array type for the string, according to C99 6.4.5. This includes 377 // the nul terminator character as well as the string length for pascal 378 // strings. 379 StrTy = Context.getConstantArrayType(StrTy, 380 llvm::APInt(32, Literal.GetNumStringChars()+1), 381 ArrayType::Normal, 0); 382 383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 384 return Owned(StringLiteral::Create(Context, Literal.GetString(), 385 Literal.GetStringLength(), 386 Literal.AnyWide, StrTy, 387 &StringTokLocs[0], 388 StringTokLocs.size())); 389} 390 391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 392/// CurBlock to VD should cause it to be snapshotted (as we do for auto 393/// variables defined outside the block) or false if this is not needed (e.g. 394/// for values inside the block or for globals). 395/// 396/// FIXME: This will create BlockDeclRefExprs for global variables, 397/// function references, etc which is suboptimal :) and breaks 398/// things like "integer constant expression" tests. 399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 400 ValueDecl *VD) { 401 // If the value is defined inside the block, we couldn't snapshot it even if 402 // we wanted to. 403 if (CurBlock->TheDecl == VD->getDeclContext()) 404 return false; 405 406 // If this is an enum constant or function, it is constant, don't snapshot. 407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 408 return false; 409 410 // If this is a reference to an extern, static, or global variable, no need to 411 // snapshot it. 412 // FIXME: What about 'const' variables in C++? 413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 414 return Var->hasLocalStorage(); 415 416 return true; 417} 418 419 420 421/// ActOnIdentifierExpr - The parser read an identifier in expression context, 422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 423/// identifier is used in a function call context. 424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the 425/// class or namespace that the identifier must be a member of. 426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 427 IdentifierInfo &II, 428 bool HasTrailingLParen, 429 const CXXScopeSpec *SS, 430 bool isAddressOfOperand) { 431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS, 432 isAddressOfOperand); 433} 434 435/// BuildDeclRefExpr - Build either a DeclRefExpr or a 436/// QualifiedDeclRefExpr based on whether or not SS is a 437/// nested-name-specifier. 438DeclRefExpr * 439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, 440 bool TypeDependent, bool ValueDependent, 441 const CXXScopeSpec *SS) { 442 if (SS && !SS->isEmpty()) 443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, 444 ValueDependent, 445 SS->getRange().getBegin()); 446 else 447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent); 448} 449 450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 451/// variable corresponding to the anonymous union or struct whose type 452/// is Record. 453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) { 454 assert(Record->isAnonymousStructOrUnion() && 455 "Record must be an anonymous struct or union!"); 456 457 // FIXME: Once Decls are directly linked together, this will 458 // be an O(1) operation rather than a slow walk through DeclContext's 459 // vector (which itself will be eliminated). DeclGroups might make 460 // this even better. 461 DeclContext *Ctx = Record->getDeclContext(); 462 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 463 DEnd = Ctx->decls_end(); 464 D != DEnd; ++D) { 465 if (*D == Record) { 466 // The object for the anonymous struct/union directly 467 // follows its type in the list of declarations. 468 ++D; 469 assert(D != DEnd && "Missing object for anonymous record"); 470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 471 return *D; 472 } 473 } 474 475 assert(false && "Missing object for anonymous record"); 476 return 0; 477} 478 479Sema::OwningExprResult 480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 481 FieldDecl *Field, 482 Expr *BaseObjectExpr, 483 SourceLocation OpLoc) { 484 assert(Field->getDeclContext()->isRecord() && 485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 486 && "Field must be stored inside an anonymous struct or union"); 487 488 // Construct the sequence of field member references 489 // we'll have to perform to get to the field in the anonymous 490 // union/struct. The list of members is built from the field 491 // outward, so traverse it backwards to go from an object in 492 // the current context to the field we found. 493 llvm::SmallVector<FieldDecl *, 4> AnonFields; 494 AnonFields.push_back(Field); 495 VarDecl *BaseObject = 0; 496 DeclContext *Ctx = Field->getDeclContext(); 497 do { 498 RecordDecl *Record = cast<RecordDecl>(Ctx); 499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record); 500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 501 AnonFields.push_back(AnonField); 502 else { 503 BaseObject = cast<VarDecl>(AnonObject); 504 break; 505 } 506 Ctx = Ctx->getParent(); 507 } while (Ctx->isRecord() && 508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 509 510 // Build the expression that refers to the base object, from 511 // which we will build a sequence of member references to each 512 // of the anonymous union objects and, eventually, the field we 513 // found via name lookup. 514 bool BaseObjectIsPointer = false; 515 unsigned ExtraQuals = 0; 516 if (BaseObject) { 517 // BaseObject is an anonymous struct/union variable (and is, 518 // therefore, not part of another non-anonymous record). 519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 521 SourceLocation()); 522 ExtraQuals 523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers(); 524 } else if (BaseObjectExpr) { 525 // The caller provided the base object expression. Determine 526 // whether its a pointer and whether it adds any qualifiers to the 527 // anonymous struct/union fields we're looking into. 528 QualType ObjectType = BaseObjectExpr->getType(); 529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) { 530 BaseObjectIsPointer = true; 531 ObjectType = ObjectPtr->getPointeeType(); 532 } 533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers(); 534 } else { 535 // We've found a member of an anonymous struct/union that is 536 // inside a non-anonymous struct/union, so in a well-formed 537 // program our base object expression is "this". 538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 539 if (!MD->isStatic()) { 540 QualType AnonFieldType 541 = Context.getTagDeclType( 542 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 543 QualType ThisType = Context.getTagDeclType(MD->getParent()); 544 if ((Context.getCanonicalType(AnonFieldType) 545 == Context.getCanonicalType(ThisType)) || 546 IsDerivedFrom(ThisType, AnonFieldType)) { 547 // Our base object expression is "this". 548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), 549 MD->getThisType(Context)); 550 BaseObjectIsPointer = true; 551 } 552 } else { 553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 554 << Field->getDeclName()); 555 } 556 ExtraQuals = MD->getTypeQualifiers(); 557 } 558 559 if (!BaseObjectExpr) 560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 561 << Field->getDeclName()); 562 } 563 564 // Build the implicit member references to the field of the 565 // anonymous struct/union. 566 Expr *Result = BaseObjectExpr; 567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 569 FI != FIEnd; ++FI) { 570 QualType MemberType = (*FI)->getType(); 571 if (!(*FI)->isMutable()) { 572 unsigned combinedQualifiers 573 = MemberType.getCVRQualifiers() | ExtraQuals; 574 MemberType = MemberType.getQualifiedType(combinedQualifiers); 575 } 576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 577 OpLoc, MemberType); 578 BaseObjectIsPointer = false; 579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers(); 580 } 581 582 return Owned(Result); 583} 584 585/// ActOnDeclarationNameExpr - The parser has read some kind of name 586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine 587/// performs lookup on that name and returns an expression that refers 588/// to that name. This routine isn't directly called from the parser, 589/// because the parser doesn't know about DeclarationName. Rather, 590/// this routine is called by ActOnIdentifierExpr, 591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, 592/// which form the DeclarationName from the corresponding syntactic 593/// forms. 594/// 595/// HasTrailingLParen indicates whether this identifier is used in a 596/// function call context. LookupCtx is only used for a C++ 597/// qualified-id (foo::bar) to indicate the class or namespace that 598/// the identifier must be a member of. 599/// 600/// isAddressOfOperand means that this expression is the direct operand 601/// of an address-of operator. This matters because this is the only 602/// situation where a qualified name referencing a non-static member may 603/// appear outside a member function of this class. 604Sema::OwningExprResult 605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, 606 DeclarationName Name, bool HasTrailingLParen, 607 const CXXScopeSpec *SS, 608 bool isAddressOfOperand) { 609 // Could be enum-constant, value decl, instance variable, etc. 610 if (SS && SS->isInvalid()) 611 return ExprError(); 612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName, 613 false, true, Loc); 614 615 NamedDecl *D = 0; 616 if (Lookup.isAmbiguous()) { 617 DiagnoseAmbiguousLookup(Lookup, Name, Loc, 618 SS && SS->isSet() ? SS->getRange() 619 : SourceRange()); 620 return ExprError(); 621 } else 622 D = Lookup.getAsDecl(); 623 624 // If this reference is in an Objective-C method, then ivar lookup happens as 625 // well. 626 IdentifierInfo *II = Name.getAsIdentifierInfo(); 627 if (II && getCurMethodDecl()) { 628 // There are two cases to handle here. 1) scoped lookup could have failed, 629 // in which case we should look for an ivar. 2) scoped lookup could have 630 // found a decl, but that decl is outside the current instance method (i.e. 631 // a global variable). In these two cases, we do a lookup for an ivar with 632 // this name, if the lookup sucedes, we replace it our current decl. 633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) { 634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 635 ObjCInterfaceDecl *ClassDeclared; 636 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 637 // Check if referencing a field with __attribute__((deprecated)). 638 if (DiagnoseUseOfDecl(IV, Loc)) 639 return ExprError(); 640 bool IsClsMethod = getCurMethodDecl()->isClassMethod(); 641 // If a class method attemps to use a free standing ivar, this is 642 // an error. 643 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod()) 644 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 645 << IV->getDeclName()); 646 // If a class method uses a global variable, even if an ivar with 647 // same name exists, use the global. 648 if (!IsClsMethod) { 649 if (IV->getAccessControl() == ObjCIvarDecl::Private && 650 ClassDeclared != IFace) 651 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 652 // FIXME: This should use a new expr for a direct reference, don't turn 653 // this into Self->ivar, just return a BareIVarExpr or something. 654 IdentifierInfo &II = Context.Idents.get("self"); 655 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 656 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 657 Loc, static_cast<Expr*>(SelfExpr.release()), 658 true, true); 659 Context.setFieldDecl(IFace, IV, MRef); 660 return Owned(MRef); 661 } 662 } 663 } 664 else if (getCurMethodDecl()->isInstanceMethod()) { 665 // We should warn if a local variable hides an ivar. 666 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 667 ObjCInterfaceDecl *ClassDeclared; 668 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 669 if (IV->getAccessControl() != ObjCIvarDecl::Private || 670 IFace == ClassDeclared) 671 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName(); 672 } 673 } 674 // Needed to implement property "super.method" notation. 675 if (D == 0 && II->isStr("super")) { 676 QualType T; 677 678 if (getCurMethodDecl()->isInstanceMethod()) 679 T = Context.getPointerType(Context.getObjCInterfaceType( 680 getCurMethodDecl()->getClassInterface())); 681 else 682 T = Context.getObjCClassType(); 683 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 684 } 685 } 686 687 // Determine whether this name might be a candidate for 688 // argument-dependent lookup. 689 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && 690 HasTrailingLParen; 691 692 if (ADL && D == 0) { 693 // We've seen something of the form 694 // 695 // identifier( 696 // 697 // and we did not find any entity by the name 698 // "identifier". However, this identifier is still subject to 699 // argument-dependent lookup, so keep track of the name. 700 return Owned(new (Context) UnresolvedFunctionNameExpr(Name, 701 Context.OverloadTy, 702 Loc)); 703 } 704 705 if (D == 0) { 706 // Otherwise, this could be an implicitly declared function reference (legal 707 // in C90, extension in C99). 708 if (HasTrailingLParen && II && 709 !getLangOptions().CPlusPlus) // Not in C++. 710 D = ImplicitlyDefineFunction(Loc, *II, S); 711 else { 712 // If this name wasn't predeclared and if this is not a function call, 713 // diagnose the problem. 714 if (SS && !SS->isEmpty()) 715 return ExprError(Diag(Loc, diag::err_typecheck_no_member) 716 << Name << SS->getRange()); 717 else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 718 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 719 return ExprError(Diag(Loc, diag::err_undeclared_use) 720 << Name.getAsString()); 721 else 722 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name); 723 } 724 } 725 726 // If this is an expression of the form &Class::member, don't build an 727 // implicit member ref, because we want a pointer to the member in general, 728 // not any specific instance's member. 729 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) { 730 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 731 if (D && isa<CXXRecordDecl>(DC)) { 732 QualType DType; 733 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 734 DType = FD->getType().getNonReferenceType(); 735 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 736 DType = Method->getType(); 737 } else if (isa<OverloadedFunctionDecl>(D)) { 738 DType = Context.OverloadTy; 739 } 740 // Could be an inner type. That's diagnosed below, so ignore it here. 741 if (!DType.isNull()) { 742 // The pointer is type- and value-dependent if it points into something 743 // dependent. 744 bool Dependent = false; 745 for (; DC; DC = DC->getParent()) { 746 // FIXME: could stop early at namespace scope. 747 if (DC->isRecord()) { 748 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 749 if (Context.getTypeDeclType(Record)->isDependentType()) { 750 Dependent = true; 751 break; 752 } 753 } 754 } 755 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS)); 756 } 757 } 758 } 759 760 // We may have found a field within an anonymous union or struct 761 // (C++ [class.union]). 762 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) 763 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 764 return BuildAnonymousStructUnionMemberReference(Loc, FD); 765 766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 767 if (!MD->isStatic()) { 768 // C++ [class.mfct.nonstatic]p2: 769 // [...] if name lookup (3.4.1) resolves the name in the 770 // id-expression to a nonstatic nontype member of class X or of 771 // a base class of X, the id-expression is transformed into a 772 // class member access expression (5.2.5) using (*this) (9.3.2) 773 // as the postfix-expression to the left of the '.' operator. 774 DeclContext *Ctx = 0; 775 QualType MemberType; 776 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 777 Ctx = FD->getDeclContext(); 778 MemberType = FD->getType(); 779 780 if (const ReferenceType *RefType = MemberType->getAsReferenceType()) 781 MemberType = RefType->getPointeeType(); 782 else if (!FD->isMutable()) { 783 unsigned combinedQualifiers 784 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers(); 785 MemberType = MemberType.getQualifiedType(combinedQualifiers); 786 } 787 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 788 if (!Method->isStatic()) { 789 Ctx = Method->getParent(); 790 MemberType = Method->getType(); 791 } 792 } else if (OverloadedFunctionDecl *Ovl 793 = dyn_cast<OverloadedFunctionDecl>(D)) { 794 for (OverloadedFunctionDecl::function_iterator 795 Func = Ovl->function_begin(), 796 FuncEnd = Ovl->function_end(); 797 Func != FuncEnd; ++Func) { 798 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func)) 799 if (!DMethod->isStatic()) { 800 Ctx = Ovl->getDeclContext(); 801 MemberType = Context.OverloadTy; 802 break; 803 } 804 } 805 } 806 807 if (Ctx && Ctx->isRecord()) { 808 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx)); 809 QualType ThisType = Context.getTagDeclType(MD->getParent()); 810 if ((Context.getCanonicalType(CtxType) 811 == Context.getCanonicalType(ThisType)) || 812 IsDerivedFrom(ThisType, CtxType)) { 813 // Build the implicit member access expression. 814 Expr *This = new (Context) CXXThisExpr(SourceLocation(), 815 MD->getThisType(Context)); 816 return Owned(new (Context) MemberExpr(This, true, D, 817 SourceLocation(), MemberType)); 818 } 819 } 820 } 821 } 822 823 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 825 if (MD->isStatic()) 826 // "invalid use of member 'x' in static member function" 827 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 828 << FD->getDeclName()); 829 } 830 831 // Any other ways we could have found the field in a well-formed 832 // program would have been turned into implicit member expressions 833 // above. 834 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 835 << FD->getDeclName()); 836 } 837 838 if (isa<TypedefDecl>(D)) 839 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name); 840 if (isa<ObjCInterfaceDecl>(D)) 841 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name); 842 if (isa<NamespaceDecl>(D)) 843 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name); 844 845 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 846 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) 847 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, 848 false, false, SS)); 849 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 850 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc, 851 false, false, SS)); 852 ValueDecl *VD = cast<ValueDecl>(D); 853 854 // Check whether this declaration can be used. Note that we suppress 855 // this check when we're going to perform argument-dependent lookup 856 // on this function name, because this might not be the function 857 // that overload resolution actually selects. 858 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc)) 859 return ExprError(); 860 861 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) { 862 // Warn about constructs like: 863 // if (void *X = foo()) { ... } else { X }. 864 // In the else block, the pointer is always false. 865 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 866 Scope *CheckS = S; 867 while (CheckS) { 868 if (CheckS->isWithinElse() && 869 CheckS->getControlParent()->isDeclScope(Var)) { 870 if (Var->getType()->isBooleanType()) 871 ExprError(Diag(Loc, diag::warn_value_always_false) 872 << Var->getDeclName()); 873 else 874 ExprError(Diag(Loc, diag::warn_value_always_zero) 875 << Var->getDeclName()); 876 break; 877 } 878 879 // Move up one more control parent to check again. 880 CheckS = CheckS->getControlParent(); 881 if (CheckS) 882 CheckS = CheckS->getParent(); 883 } 884 } 885 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) { 886 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 887 // C99 DR 316 says that, if a function type comes from a 888 // function definition (without a prototype), that type is only 889 // used for checking compatibility. Therefore, when referencing 890 // the function, we pretend that we don't have the full function 891 // type. 892 QualType T = Func->getType(); 893 QualType NoProtoType = T; 894 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType()) 895 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 896 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS)); 897 } 898 } 899 900 // Only create DeclRefExpr's for valid Decl's. 901 if (VD->isInvalidDecl()) 902 return ExprError(); 903 904 // If the identifier reference is inside a block, and it refers to a value 905 // that is outside the block, create a BlockDeclRefExpr instead of a 906 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 907 // the block is formed. 908 // 909 // We do not do this for things like enum constants, global variables, etc, 910 // as they do not get snapshotted. 911 // 912 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 913 // Blocks that have these can't be constant. 914 CurBlock->hasBlockDeclRefExprs = true; 915 916 // The BlocksAttr indicates the variable is bound by-reference. 917 if (VD->getAttr<BlocksAttr>()) 918 return Owned(new (Context) BlockDeclRefExpr(VD, 919 VD->getType().getNonReferenceType(), Loc, true)); 920 921 // Variable will be bound by-copy, make it const within the closure. 922 VD->getType().addConst(); 923 return Owned(new (Context) BlockDeclRefExpr(VD, 924 VD->getType().getNonReferenceType(), Loc, false)); 925 } 926 // If this reference is not in a block or if the referenced variable is 927 // within the block, create a normal DeclRefExpr. 928 929 bool TypeDependent = false; 930 bool ValueDependent = false; 931 if (getLangOptions().CPlusPlus) { 932 // C++ [temp.dep.expr]p3: 933 // An id-expression is type-dependent if it contains: 934 // - an identifier that was declared with a dependent type, 935 if (VD->getType()->isDependentType()) 936 TypeDependent = true; 937 // - FIXME: a template-id that is dependent, 938 // - a conversion-function-id that specifies a dependent type, 939 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 940 Name.getCXXNameType()->isDependentType()) 941 TypeDependent = true; 942 // - a nested-name-specifier that contains a class-name that 943 // names a dependent type. 944 else if (SS && !SS->isEmpty()) { 945 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 946 DC; DC = DC->getParent()) { 947 // FIXME: could stop early at namespace scope. 948 if (DC->isRecord()) { 949 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 950 if (Context.getTypeDeclType(Record)->isDependentType()) { 951 TypeDependent = true; 952 break; 953 } 954 } 955 } 956 } 957 958 // C++ [temp.dep.constexpr]p2: 959 // 960 // An identifier is value-dependent if it is: 961 // - a name declared with a dependent type, 962 if (TypeDependent) 963 ValueDependent = true; 964 // - the name of a non-type template parameter, 965 else if (isa<NonTypeTemplateParmDecl>(VD)) 966 ValueDependent = true; 967 // - a constant with integral or enumeration type and is 968 // initialized with an expression that is value-dependent 969 // (FIXME!). 970 } 971 972 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, 973 TypeDependent, ValueDependent, SS)); 974} 975 976Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 977 tok::TokenKind Kind) { 978 PredefinedExpr::IdentType IT; 979 980 switch (Kind) { 981 default: assert(0 && "Unknown simple primary expr!"); 982 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 983 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 984 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 985 } 986 987 // Pre-defined identifiers are of type char[x], where x is the length of the 988 // string. 989 unsigned Length; 990 if (FunctionDecl *FD = getCurFunctionDecl()) 991 Length = FD->getIdentifier()->getLength(); 992 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 993 Length = MD->getSynthesizedMethodSize(); 994 else { 995 Diag(Loc, diag::ext_predef_outside_function); 996 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. 997 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0; 998 } 999 1000 1001 llvm::APInt LengthI(32, Length + 1); 1002 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 1003 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1004 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1005} 1006 1007Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1008 llvm::SmallString<16> CharBuffer; 1009 CharBuffer.resize(Tok.getLength()); 1010 const char *ThisTokBegin = &CharBuffer[0]; 1011 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1012 1013 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1014 Tok.getLocation(), PP); 1015 if (Literal.hadError()) 1016 return ExprError(); 1017 1018 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 1019 1020 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1021 Literal.isWide(), 1022 type, Tok.getLocation())); 1023} 1024 1025Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1026 // Fast path for a single digit (which is quite common). A single digit 1027 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1028 if (Tok.getLength() == 1) { 1029 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1030 unsigned IntSize = Context.Target.getIntWidth(); 1031 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1032 Context.IntTy, Tok.getLocation())); 1033 } 1034 1035 llvm::SmallString<512> IntegerBuffer; 1036 // Add padding so that NumericLiteralParser can overread by one character. 1037 IntegerBuffer.resize(Tok.getLength()+1); 1038 const char *ThisTokBegin = &IntegerBuffer[0]; 1039 1040 // Get the spelling of the token, which eliminates trigraphs, etc. 1041 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1042 1043 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1044 Tok.getLocation(), PP); 1045 if (Literal.hadError) 1046 return ExprError(); 1047 1048 Expr *Res; 1049 1050 if (Literal.isFloatingLiteral()) { 1051 QualType Ty; 1052 if (Literal.isFloat) 1053 Ty = Context.FloatTy; 1054 else if (!Literal.isLong) 1055 Ty = Context.DoubleTy; 1056 else 1057 Ty = Context.LongDoubleTy; 1058 1059 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1060 1061 // isExact will be set by GetFloatValue(). 1062 bool isExact = false; 1063 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact), 1064 &isExact, Ty, Tok.getLocation()); 1065 1066 } else if (!Literal.isIntegerLiteral()) { 1067 return ExprError(); 1068 } else { 1069 QualType Ty; 1070 1071 // long long is a C99 feature. 1072 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1073 Literal.isLongLong) 1074 Diag(Tok.getLocation(), diag::ext_longlong); 1075 1076 // Get the value in the widest-possible width. 1077 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1078 1079 if (Literal.GetIntegerValue(ResultVal)) { 1080 // If this value didn't fit into uintmax_t, warn and force to ull. 1081 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1082 Ty = Context.UnsignedLongLongTy; 1083 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1084 "long long is not intmax_t?"); 1085 } else { 1086 // If this value fits into a ULL, try to figure out what else it fits into 1087 // according to the rules of C99 6.4.4.1p5. 1088 1089 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1090 // be an unsigned int. 1091 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1092 1093 // Check from smallest to largest, picking the smallest type we can. 1094 unsigned Width = 0; 1095 if (!Literal.isLong && !Literal.isLongLong) { 1096 // Are int/unsigned possibilities? 1097 unsigned IntSize = Context.Target.getIntWidth(); 1098 1099 // Does it fit in a unsigned int? 1100 if (ResultVal.isIntN(IntSize)) { 1101 // Does it fit in a signed int? 1102 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1103 Ty = Context.IntTy; 1104 else if (AllowUnsigned) 1105 Ty = Context.UnsignedIntTy; 1106 Width = IntSize; 1107 } 1108 } 1109 1110 // Are long/unsigned long possibilities? 1111 if (Ty.isNull() && !Literal.isLongLong) { 1112 unsigned LongSize = Context.Target.getLongWidth(); 1113 1114 // Does it fit in a unsigned long? 1115 if (ResultVal.isIntN(LongSize)) { 1116 // Does it fit in a signed long? 1117 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1118 Ty = Context.LongTy; 1119 else if (AllowUnsigned) 1120 Ty = Context.UnsignedLongTy; 1121 Width = LongSize; 1122 } 1123 } 1124 1125 // Finally, check long long if needed. 1126 if (Ty.isNull()) { 1127 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1128 1129 // Does it fit in a unsigned long long? 1130 if (ResultVal.isIntN(LongLongSize)) { 1131 // Does it fit in a signed long long? 1132 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1133 Ty = Context.LongLongTy; 1134 else if (AllowUnsigned) 1135 Ty = Context.UnsignedLongLongTy; 1136 Width = LongLongSize; 1137 } 1138 } 1139 1140 // If we still couldn't decide a type, we probably have something that 1141 // does not fit in a signed long long, but has no U suffix. 1142 if (Ty.isNull()) { 1143 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1144 Ty = Context.UnsignedLongLongTy; 1145 Width = Context.Target.getLongLongWidth(); 1146 } 1147 1148 if (ResultVal.getBitWidth() != Width) 1149 ResultVal.trunc(Width); 1150 } 1151 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1152 } 1153 1154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1155 if (Literal.isImaginary) 1156 Res = new (Context) ImaginaryLiteral(Res, 1157 Context.getComplexType(Res->getType())); 1158 1159 return Owned(Res); 1160} 1161 1162Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1163 SourceLocation R, ExprArg Val) { 1164 Expr *E = (Expr *)Val.release(); 1165 assert((E != 0) && "ActOnParenExpr() missing expr"); 1166 return Owned(new (Context) ParenExpr(L, R, E)); 1167} 1168 1169/// The UsualUnaryConversions() function is *not* called by this routine. 1170/// See C99 6.3.2.1p[2-4] for more details. 1171bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1172 SourceLocation OpLoc, 1173 const SourceRange &ExprRange, 1174 bool isSizeof) { 1175 if (exprType->isDependentType()) 1176 return false; 1177 1178 // C99 6.5.3.4p1: 1179 if (isa<FunctionType>(exprType)) { 1180 // alignof(function) is allowed. 1181 if (isSizeof) 1182 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1183 return false; 1184 } 1185 1186 if (exprType->isVoidType()) { 1187 Diag(OpLoc, diag::ext_sizeof_void_type) 1188 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1189 return false; 1190 } 1191 1192 return DiagnoseIncompleteType(OpLoc, exprType, 1193 isSizeof ? diag::err_sizeof_incomplete_type : 1194 diag::err_alignof_incomplete_type, 1195 ExprRange); 1196} 1197 1198bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1199 const SourceRange &ExprRange) { 1200 E = E->IgnoreParens(); 1201 1202 // alignof decl is always ok. 1203 if (isa<DeclRefExpr>(E)) 1204 return false; 1205 1206 // Cannot know anything else if the expression is dependent. 1207 if (E->isTypeDependent()) 1208 return false; 1209 1210 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 1211 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 1212 if (FD->isBitField()) { 1213 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1214 return true; 1215 } 1216 // Other fields are ok. 1217 return false; 1218 } 1219 } 1220 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1221} 1222 1223/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1224/// the same for @c alignof and @c __alignof 1225/// Note that the ArgRange is invalid if isType is false. 1226Action::OwningExprResult 1227Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1228 void *TyOrEx, const SourceRange &ArgRange) { 1229 // If error parsing type, ignore. 1230 if (TyOrEx == 0) return ExprError(); 1231 1232 QualType ArgTy; 1233 SourceRange Range; 1234 if (isType) { 1235 ArgTy = QualType::getFromOpaquePtr(TyOrEx); 1236 Range = ArgRange; 1237 1238 // Verify that the operand is valid. 1239 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof)) 1240 return ExprError(); 1241 } else { 1242 // Get the end location. 1243 Expr *ArgEx = (Expr *)TyOrEx; 1244 Range = ArgEx->getSourceRange(); 1245 ArgTy = ArgEx->getType(); 1246 1247 // Verify that the operand is valid. 1248 bool isInvalid; 1249 if (!isSizeof) { 1250 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range); 1251 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1. 1252 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1253 isInvalid = true; 1254 } else { 1255 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true); 1256 } 1257 1258 if (isInvalid) { 1259 DeleteExpr(ArgEx); 1260 return ExprError(); 1261 } 1262 } 1263 1264 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1265 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, 1266 Context.getSizeType(), OpLoc, 1267 Range.getEnd())); 1268} 1269 1270QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1271 if (V->isTypeDependent()) 1272 return Context.DependentTy; 1273 1274 DefaultFunctionArrayConversion(V); 1275 1276 // These operators return the element type of a complex type. 1277 if (const ComplexType *CT = V->getType()->getAsComplexType()) 1278 return CT->getElementType(); 1279 1280 // Otherwise they pass through real integer and floating point types here. 1281 if (V->getType()->isArithmeticType()) 1282 return V->getType(); 1283 1284 // Reject anything else. 1285 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1286 << (isReal ? "__real" : "__imag"); 1287 return QualType(); 1288} 1289 1290 1291 1292Action::OwningExprResult 1293Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1294 tok::TokenKind Kind, ExprArg Input) { 1295 Expr *Arg = (Expr *)Input.get(); 1296 1297 UnaryOperator::Opcode Opc; 1298 switch (Kind) { 1299 default: assert(0 && "Unknown unary op!"); 1300 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1301 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1302 } 1303 1304 if (getLangOptions().CPlusPlus && 1305 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 1306 // Which overloaded operator? 1307 OverloadedOperatorKind OverOp = 1308 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 1309 1310 // C++ [over.inc]p1: 1311 // 1312 // [...] If the function is a member function with one 1313 // parameter (which shall be of type int) or a non-member 1314 // function with two parameters (the second of which shall be 1315 // of type int), it defines the postfix increment operator ++ 1316 // for objects of that type. When the postfix increment is 1317 // called as a result of using the ++ operator, the int 1318 // argument will have value zero. 1319 Expr *Args[2] = { 1320 Arg, 1321 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 1322 /*isSigned=*/true), Context.IntTy, SourceLocation()) 1323 }; 1324 1325 // Build the candidate set for overloading 1326 OverloadCandidateSet CandidateSet; 1327 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet)) 1328 return ExprError(); 1329 1330 // Perform overload resolution. 1331 OverloadCandidateSet::iterator Best; 1332 switch (BestViableFunction(CandidateSet, Best)) { 1333 case OR_Success: { 1334 // We found a built-in operator or an overloaded operator. 1335 FunctionDecl *FnDecl = Best->Function; 1336 1337 if (FnDecl) { 1338 // We matched an overloaded operator. Build a call to that 1339 // operator. 1340 1341 // Convert the arguments. 1342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1343 if (PerformObjectArgumentInitialization(Arg, Method)) 1344 return ExprError(); 1345 } else { 1346 // Convert the arguments. 1347 if (PerformCopyInitialization(Arg, 1348 FnDecl->getParamDecl(0)->getType(), 1349 "passing")) 1350 return ExprError(); 1351 } 1352 1353 // Determine the result type 1354 QualType ResultTy 1355 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1356 ResultTy = ResultTy.getNonReferenceType(); 1357 1358 // Build the actual expression node. 1359 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1360 SourceLocation()); 1361 UsualUnaryConversions(FnExpr); 1362 1363 Input.release(); 1364 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 1365 ResultTy, OpLoc)); 1366 } else { 1367 // We matched a built-in operator. Convert the arguments, then 1368 // break out so that we will build the appropriate built-in 1369 // operator node. 1370 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 1371 "passing")) 1372 return ExprError(); 1373 1374 break; 1375 } 1376 } 1377 1378 case OR_No_Viable_Function: 1379 // No viable function; fall through to handling this as a 1380 // built-in operator, which will produce an error message for us. 1381 break; 1382 1383 case OR_Ambiguous: 1384 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 1385 << UnaryOperator::getOpcodeStr(Opc) 1386 << Arg->getSourceRange(); 1387 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1388 return ExprError(); 1389 1390 case OR_Deleted: 1391 Diag(OpLoc, diag::err_ovl_deleted_oper) 1392 << Best->Function->isDeleted() 1393 << UnaryOperator::getOpcodeStr(Opc) 1394 << Arg->getSourceRange(); 1395 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1396 return ExprError(); 1397 } 1398 1399 // Either we found no viable overloaded operator or we matched a 1400 // built-in operator. In either case, fall through to trying to 1401 // build a built-in operation. 1402 } 1403 1404 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc, 1405 Opc == UnaryOperator::PostInc); 1406 if (result.isNull()) 1407 return ExprError(); 1408 Input.release(); 1409 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc)); 1410} 1411 1412Action::OwningExprResult 1413Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 1414 ExprArg Idx, SourceLocation RLoc) { 1415 Expr *LHSExp = static_cast<Expr*>(Base.get()), 1416 *RHSExp = static_cast<Expr*>(Idx.get()); 1417 1418 if (getLangOptions().CPlusPlus && 1419 (LHSExp->getType()->isRecordType() || 1420 LHSExp->getType()->isEnumeralType() || 1421 RHSExp->getType()->isRecordType() || 1422 RHSExp->getType()->isEnumeralType())) { 1423 // Add the appropriate overloaded operators (C++ [over.match.oper]) 1424 // to the candidate set. 1425 OverloadCandidateSet CandidateSet; 1426 Expr *Args[2] = { LHSExp, RHSExp }; 1427 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet, 1428 SourceRange(LLoc, RLoc))) 1429 return ExprError(); 1430 1431 // Perform overload resolution. 1432 OverloadCandidateSet::iterator Best; 1433 switch (BestViableFunction(CandidateSet, Best)) { 1434 case OR_Success: { 1435 // We found a built-in operator or an overloaded operator. 1436 FunctionDecl *FnDecl = Best->Function; 1437 1438 if (FnDecl) { 1439 // We matched an overloaded operator. Build a call to that 1440 // operator. 1441 1442 // Convert the arguments. 1443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 1444 if (PerformObjectArgumentInitialization(LHSExp, Method) || 1445 PerformCopyInitialization(RHSExp, 1446 FnDecl->getParamDecl(0)->getType(), 1447 "passing")) 1448 return ExprError(); 1449 } else { 1450 // Convert the arguments. 1451 if (PerformCopyInitialization(LHSExp, 1452 FnDecl->getParamDecl(0)->getType(), 1453 "passing") || 1454 PerformCopyInitialization(RHSExp, 1455 FnDecl->getParamDecl(1)->getType(), 1456 "passing")) 1457 return ExprError(); 1458 } 1459 1460 // Determine the result type 1461 QualType ResultTy 1462 = FnDecl->getType()->getAsFunctionType()->getResultType(); 1463 ResultTy = ResultTy.getNonReferenceType(); 1464 1465 // Build the actual expression node. 1466 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 1467 SourceLocation()); 1468 UsualUnaryConversions(FnExpr); 1469 1470 Base.release(); 1471 Idx.release(); 1472 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 1473 ResultTy, LLoc)); 1474 } else { 1475 // We matched a built-in operator. Convert the arguments, then 1476 // break out so that we will build the appropriate built-in 1477 // operator node. 1478 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 1479 "passing") || 1480 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 1481 "passing")) 1482 return ExprError(); 1483 1484 break; 1485 } 1486 } 1487 1488 case OR_No_Viable_Function: 1489 // No viable function; fall through to handling this as a 1490 // built-in operator, which will produce an error message for us. 1491 break; 1492 1493 case OR_Ambiguous: 1494 Diag(LLoc, diag::err_ovl_ambiguous_oper) 1495 << "[]" 1496 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1497 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1498 return ExprError(); 1499 1500 case OR_Deleted: 1501 Diag(LLoc, diag::err_ovl_deleted_oper) 1502 << Best->Function->isDeleted() 1503 << "[]" 1504 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 1505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1506 return ExprError(); 1507 } 1508 1509 // Either we found no viable overloaded operator or we matched a 1510 // built-in operator. In either case, fall through to trying to 1511 // build a built-in operation. 1512 } 1513 1514 // Perform default conversions. 1515 DefaultFunctionArrayConversion(LHSExp); 1516 DefaultFunctionArrayConversion(RHSExp); 1517 1518 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 1519 1520 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 1521 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 1522 // in the subscript position. As a result, we need to derive the array base 1523 // and index from the expression types. 1524 Expr *BaseExpr, *IndexExpr; 1525 QualType ResultType; 1526 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 1527 BaseExpr = LHSExp; 1528 IndexExpr = RHSExp; 1529 ResultType = Context.DependentTy; 1530 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) { 1531 BaseExpr = LHSExp; 1532 IndexExpr = RHSExp; 1533 // FIXME: need to deal with const... 1534 ResultType = PTy->getPointeeType(); 1535 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 1536 // Handle the uncommon case of "123[Ptr]". 1537 BaseExpr = RHSExp; 1538 IndexExpr = LHSExp; 1539 // FIXME: need to deal with const... 1540 ResultType = PTy->getPointeeType(); 1541 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 1542 BaseExpr = LHSExp; // vectors: V[123] 1543 IndexExpr = RHSExp; 1544 1545 // FIXME: need to deal with const... 1546 ResultType = VTy->getElementType(); 1547 } else { 1548 return ExprError(Diag(LHSExp->getLocStart(), 1549 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange()); 1550 } 1551 // C99 6.5.2.1p1 1552 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 1553 return ExprError(Diag(IndexExpr->getLocStart(), 1554 diag::err_typecheck_subscript) << IndexExpr->getSourceRange()); 1555 1556 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 1557 // the following check catches trying to index a pointer to a function (e.g. 1558 // void (*)(int)) and pointers to incomplete types. Functions are not 1559 // objects in C99. 1560 if (!ResultType->isObjectType() && !ResultType->isDependentType()) 1561 return ExprError(Diag(BaseExpr->getLocStart(), 1562 diag::err_typecheck_subscript_not_object) 1563 << BaseExpr->getType() << BaseExpr->getSourceRange()); 1564 1565 Base.release(); 1566 Idx.release(); 1567 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1568 ResultType, RLoc)); 1569} 1570 1571QualType Sema:: 1572CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1573 IdentifierInfo &CompName, SourceLocation CompLoc) { 1574 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1575 1576 // The vector accessor can't exceed the number of elements. 1577 const char *compStr = CompName.getName(); 1578 1579 // This flag determines whether or not the component is one of the four 1580 // special names that indicate a subset of exactly half the elements are 1581 // to be selected. 1582 bool HalvingSwizzle = false; 1583 1584 // This flag determines whether or not CompName has an 's' char prefix, 1585 // indicating that it is a string of hex values to be used as vector indices. 1586 bool HexSwizzle = *compStr == 's'; 1587 1588 // Check that we've found one of the special components, or that the component 1589 // names must come from the same set. 1590 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1591 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 1592 HalvingSwizzle = true; 1593 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1594 do 1595 compStr++; 1596 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1597 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 1598 do 1599 compStr++; 1600 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 1601 } 1602 1603 if (!HalvingSwizzle && *compStr) { 1604 // We didn't get to the end of the string. This means the component names 1605 // didn't come from the same set *or* we encountered an illegal name. 1606 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1607 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1608 return QualType(); 1609 } 1610 1611 // Ensure no component accessor exceeds the width of the vector type it 1612 // operates on. 1613 if (!HalvingSwizzle) { 1614 compStr = CompName.getName(); 1615 1616 if (HexSwizzle) 1617 compStr++; 1618 1619 while (*compStr) { 1620 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 1621 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1622 << baseType << SourceRange(CompLoc); 1623 return QualType(); 1624 } 1625 } 1626 } 1627 1628 // If this is a halving swizzle, verify that the base type has an even 1629 // number of elements. 1630 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { 1631 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1632 << baseType << SourceRange(CompLoc); 1633 return QualType(); 1634 } 1635 1636 // The component accessor looks fine - now we need to compute the actual type. 1637 // The vector type is implied by the component accessor. For example, 1638 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1639 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 1640 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1641 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 1642 : CompName.getLength(); 1643 if (HexSwizzle) 1644 CompSize--; 1645 1646 if (CompSize == 1) 1647 return vecType->getElementType(); 1648 1649 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1650 // Now look up the TypeDefDecl from the vector type. Without this, 1651 // diagostics look bad. We want extended vector types to appear built-in. 1652 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1653 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1654 return Context.getTypedefType(ExtVectorDecls[i]); 1655 } 1656 return VT; // should never get here (a typedef type should always be found). 1657} 1658 1659 1660/// constructSetterName - Return the setter name for the given 1661/// identifier, i.e. "set" + Name where the initial character of Name 1662/// has been capitalized. 1663// FIXME: Merge with same routine in Parser. But where should this 1664// live? 1665static IdentifierInfo *constructSetterName(IdentifierTable &Idents, 1666 const IdentifierInfo *Name) { 1667 llvm::SmallString<100> SelectorName; 1668 SelectorName = "set"; 1669 SelectorName.append(Name->getName(), Name->getName()+Name->getLength()); 1670 SelectorName[3] = toupper(SelectorName[3]); 1671 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]); 1672} 1673 1674Action::OwningExprResult 1675Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 1676 tok::TokenKind OpKind, SourceLocation MemberLoc, 1677 IdentifierInfo &Member, 1678 DeclTy *ObjCImpDecl) { 1679 Expr *BaseExpr = static_cast<Expr *>(Base.release()); 1680 assert(BaseExpr && "no record expression"); 1681 1682 // Perform default conversions. 1683 DefaultFunctionArrayConversion(BaseExpr); 1684 1685 QualType BaseType = BaseExpr->getType(); 1686 assert(!BaseType.isNull() && "no type for member expression"); 1687 1688 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 1689 // must have pointer type, and the accessed type is the pointee. 1690 if (OpKind == tok::arrow) { 1691 if (const PointerType *PT = BaseType->getAsPointerType()) 1692 BaseType = PT->getPointeeType(); 1693 else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) 1694 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, 1695 MemberLoc, Member)); 1696 else 1697 return ExprError(Diag(MemberLoc, 1698 diag::err_typecheck_member_reference_arrow) 1699 << BaseType << BaseExpr->getSourceRange()); 1700 } 1701 1702 // Handle field access to simple records. This also handles access to fields 1703 // of the ObjC 'id' struct. 1704 if (const RecordType *RTy = BaseType->getAsRecordType()) { 1705 RecordDecl *RDecl = RTy->getDecl(); 1706 if (DiagnoseIncompleteType(OpLoc, BaseType, 1707 diag::err_typecheck_incomplete_tag, 1708 BaseExpr->getSourceRange())) 1709 return ExprError(); 1710 1711 // The record definition is complete, now make sure the member is valid. 1712 // FIXME: Qualified name lookup for C++ is a bit more complicated 1713 // than this. 1714 LookupResult Result 1715 = LookupQualifiedName(RDecl, DeclarationName(&Member), 1716 LookupMemberName, false); 1717 1718 NamedDecl *MemberDecl = 0; 1719 if (!Result) 1720 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member) 1721 << &Member << BaseExpr->getSourceRange()); 1722 else if (Result.isAmbiguous()) { 1723 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member), 1724 MemberLoc, BaseExpr->getSourceRange()); 1725 return ExprError(); 1726 } else 1727 MemberDecl = Result; 1728 1729 // If the decl being referenced had an error, return an error for this 1730 // sub-expr without emitting another error, in order to avoid cascading 1731 // error cases. 1732 if (MemberDecl->isInvalidDecl()) 1733 return ExprError(); 1734 1735 // Check the use of this field 1736 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 1737 return ExprError(); 1738 1739 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 1740 // We may have found a field within an anonymous union or struct 1741 // (C++ [class.union]). 1742 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1743 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 1744 BaseExpr, OpLoc); 1745 1746 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 1747 // FIXME: Handle address space modifiers 1748 QualType MemberType = FD->getType(); 1749 if (const ReferenceType *Ref = MemberType->getAsReferenceType()) 1750 MemberType = Ref->getPointeeType(); 1751 else { 1752 unsigned combinedQualifiers = 1753 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 1754 if (FD->isMutable()) 1755 combinedQualifiers &= ~QualType::Const; 1756 MemberType = MemberType.getQualifiedType(combinedQualifiers); 1757 } 1758 1759 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD, 1760 MemberLoc, MemberType)); 1761 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl)) 1762 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1763 Var, MemberLoc, 1764 Var->getType().getNonReferenceType())); 1765 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) 1766 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1767 MemberFn, MemberLoc, MemberFn->getType())); 1768 else if (OverloadedFunctionDecl *Ovl 1769 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) 1770 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, 1771 MemberLoc, Context.OverloadTy)); 1772 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) 1773 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, 1774 Enum, MemberLoc, Enum->getType())); 1775 else if (isa<TypeDecl>(MemberDecl)) 1776 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 1777 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 1778 1779 // We found a declaration kind that we didn't expect. This is a 1780 // generic error message that tells the user that she can't refer 1781 // to this member with '.' or '->'. 1782 return ExprError(Diag(MemberLoc, 1783 diag::err_typecheck_member_reference_unknown) 1784 << DeclarationName(&Member) << int(OpKind == tok::arrow)); 1785 } 1786 1787 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 1788 // (*Obj).ivar. 1789 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 1790 ObjCInterfaceDecl *ClassDeclared; 1791 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member, 1792 ClassDeclared)) { 1793 // If the decl being referenced had an error, return an error for this 1794 // sub-expr without emitting another error, in order to avoid cascading 1795 // error cases. 1796 if (IV->isInvalidDecl()) 1797 return ExprError(); 1798 1799 // Check whether we can reference this field. 1800 if (DiagnoseUseOfDecl(IV, MemberLoc)) 1801 return ExprError(); 1802 if (IV->getAccessControl() != ObjCIvarDecl::Public) { 1803 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 1804 if (ObjCMethodDecl *MD = getCurMethodDecl()) 1805 ClassOfMethodDecl = MD->getClassInterface(); 1806 else if (ObjCImpDecl && getCurFunctionDecl()) { 1807 // Case of a c-function declared inside an objc implementation. 1808 // FIXME: For a c-style function nested inside an objc implementation 1809 // class, there is no implementation context available, so we pass down 1810 // the context as argument to this routine. Ideally, this context need 1811 // be passed down in the AST node and somehow calculated from the AST 1812 // for a function decl. 1813 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl); 1814 if (ObjCImplementationDecl *IMPD = 1815 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 1816 ClassOfMethodDecl = IMPD->getClassInterface(); 1817 else if (ObjCCategoryImplDecl* CatImplClass = 1818 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 1819 ClassOfMethodDecl = CatImplClass->getClassInterface(); 1820 } 1821 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 1822 if (ClassDeclared != IFTy->getDecl() || 1823 ClassOfMethodDecl != ClassDeclared) 1824 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName(); 1825 } 1826 // @protected 1827 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl)) 1828 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName(); 1829 } 1830 1831 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(), 1832 MemberLoc, BaseExpr, 1833 OpKind == tok::arrow); 1834 Context.setFieldDecl(IFTy->getDecl(), IV, MRef); 1835 return Owned(MRef); 1836 } 1837 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1838 << IFTy->getDecl()->getDeclName() << &Member 1839 << BaseExpr->getSourceRange()); 1840 } 1841 1842 // Handle Objective-C property access, which is "Obj.property" where Obj is a 1843 // pointer to a (potentially qualified) interface type. 1844 const PointerType *PTy; 1845 const ObjCInterfaceType *IFTy; 1846 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 1847 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 1848 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 1849 1850 // Search for a declared property first. 1851 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) { 1852 // Check whether we can reference this property. 1853 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1854 return ExprError(); 1855 1856 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1857 MemberLoc, BaseExpr)); 1858 } 1859 1860 // Check protocols on qualified interfaces. 1861 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 1862 E = IFTy->qual_end(); I != E; ++I) 1863 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 1864 // Check whether we can reference this property. 1865 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1866 return ExprError(); 1867 1868 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1869 MemberLoc, BaseExpr)); 1870 } 1871 1872 // If that failed, look for an "implicit" property by seeing if the nullary 1873 // selector is implemented. 1874 1875 // FIXME: The logic for looking up nullary and unary selectors should be 1876 // shared with the code in ActOnInstanceMessage. 1877 1878 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1879 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1880 1881 // If this reference is in an @implementation, check for 'private' methods. 1882 if (!Getter) 1883 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1884 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1885 if (ObjCImplementationDecl *ImpDecl = 1886 ObjCImplementations[ClassDecl->getIdentifier()]) 1887 Getter = ImpDecl->getInstanceMethod(Sel); 1888 1889 // Look through local category implementations associated with the class. 1890 if (!Getter) { 1891 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 1892 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1893 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 1894 } 1895 } 1896 if (Getter) { 1897 // Check if we can reference this property. 1898 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1899 return ExprError(); 1900 1901 // If we found a getter then this may be a valid dot-reference, we 1902 // will look for the matching setter, in case it is needed. 1903 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(), 1904 &Member); 1905 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName); 1906 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1907 if (!Setter) { 1908 // If this reference is in an @implementation, also check for 'private' 1909 // methods. 1910 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1911 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1912 if (ObjCImplementationDecl *ImpDecl = 1913 ObjCImplementations[ClassDecl->getIdentifier()]) 1914 Setter = ImpDecl->getInstanceMethod(SetterSel); 1915 } 1916 // Look through local category implementations associated with the class. 1917 if (!Setter) { 1918 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 1919 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1920 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel); 1921 } 1922 } 1923 1924 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1925 return ExprError(); 1926 1927 // FIXME: we must check that the setter has property type. 1928 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(), 1929 Setter, MemberLoc, BaseExpr)); 1930 } 1931 1932 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1933 << &Member << BaseType); 1934 } 1935 // Handle properties on qualified "id" protocols. 1936 const ObjCQualifiedIdType *QIdTy; 1937 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 1938 // Check protocols on qualified interfaces. 1939 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), 1940 E = QIdTy->qual_end(); I != E; ++I) { 1941 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) { 1942 // Check the use of this declaration 1943 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1944 return ExprError(); 1945 1946 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 1947 MemberLoc, BaseExpr)); 1948 } 1949 // Also must look for a getter name which uses property syntax. 1950 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1951 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 1952 // Check the use of this method. 1953 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1954 return ExprError(); 1955 1956 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 1957 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); 1958 } 1959 } 1960 1961 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1962 << &Member << BaseType); 1963 } 1964 // Handle properties on ObjC 'Class' types. 1965 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) { 1966 // Also must look for a getter name which uses property syntax. 1967 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1968 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1969 ObjCMethodDecl *OMD; 1970 // FIXME: need to also look locally in the implementation. 1971 if ((OMD = MD->getClassInterface()->lookupClassMethod(Sel))) { 1972 // Check the use of this method. 1973 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1974 return ExprError(); 1975 1976 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 1977 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); 1978 } 1979 } 1980 } 1981 1982 // Handle 'field access' to vectors, such as 'V.xx'. 1983 if (BaseType->isExtVectorType()) { 1984 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 1985 if (ret.isNull()) 1986 return ExprError(); 1987 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member, 1988 MemberLoc)); 1989 } 1990 1991 return ExprError(Diag(MemberLoc, 1992 diag::err_typecheck_member_reference_struct_union) 1993 << BaseType << BaseExpr->getSourceRange()); 1994} 1995 1996/// ConvertArgumentsForCall - Converts the arguments specified in 1997/// Args/NumArgs to the parameter types of the function FDecl with 1998/// function prototype Proto. Call is the call expression itself, and 1999/// Fn is the function expression. For a C++ member function, this 2000/// routine does not attempt to convert the object argument. Returns 2001/// true if the call is ill-formed. 2002bool 2003Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2004 FunctionDecl *FDecl, 2005 const FunctionProtoType *Proto, 2006 Expr **Args, unsigned NumArgs, 2007 SourceLocation RParenLoc) { 2008 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2009 // assignment, to the types of the corresponding parameter, ... 2010 unsigned NumArgsInProto = Proto->getNumArgs(); 2011 unsigned NumArgsToCheck = NumArgs; 2012 bool Invalid = false; 2013 2014 // If too few arguments are available (and we don't have default 2015 // arguments for the remaining parameters), don't make the call. 2016 if (NumArgs < NumArgsInProto) { 2017 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2018 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2019 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2020 // Use default arguments for missing arguments 2021 NumArgsToCheck = NumArgsInProto; 2022 Call->setNumArgs(Context, NumArgsInProto); 2023 } 2024 2025 // If too many are passed and not variadic, error on the extras and drop 2026 // them. 2027 if (NumArgs > NumArgsInProto) { 2028 if (!Proto->isVariadic()) { 2029 Diag(Args[NumArgsInProto]->getLocStart(), 2030 diag::err_typecheck_call_too_many_args) 2031 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2032 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2033 Args[NumArgs-1]->getLocEnd()); 2034 // This deletes the extra arguments. 2035 Call->setNumArgs(Context, NumArgsInProto); 2036 Invalid = true; 2037 } 2038 NumArgsToCheck = NumArgsInProto; 2039 } 2040 2041 // Continue to check argument types (even if we have too few/many args). 2042 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2043 QualType ProtoArgType = Proto->getArgType(i); 2044 2045 Expr *Arg; 2046 if (i < NumArgs) { 2047 Arg = Args[i]; 2048 2049 // Pass the argument. 2050 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2051 return true; 2052 } else 2053 // We already type-checked the argument, so we know it works. 2054 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i)); 2055 QualType ArgType = Arg->getType(); 2056 2057 Call->setArg(i, Arg); 2058 } 2059 2060 // If this is a variadic call, handle args passed through "...". 2061 if (Proto->isVariadic()) { 2062 VariadicCallType CallType = VariadicFunction; 2063 if (Fn->getType()->isBlockPointerType()) 2064 CallType = VariadicBlock; // Block 2065 else if (isa<MemberExpr>(Fn)) 2066 CallType = VariadicMethod; 2067 2068 // Promote the arguments (C99 6.5.2.2p7). 2069 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2070 Expr *Arg = Args[i]; 2071 DefaultVariadicArgumentPromotion(Arg, CallType); 2072 Call->setArg(i, Arg); 2073 } 2074 } 2075 2076 return Invalid; 2077} 2078 2079/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2080/// This provides the location of the left/right parens and a list of comma 2081/// locations. 2082Action::OwningExprResult 2083Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2084 MultiExprArg args, 2085 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2086 unsigned NumArgs = args.size(); 2087 Expr *Fn = static_cast<Expr *>(fn.release()); 2088 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2089 assert(Fn && "no function call expression"); 2090 FunctionDecl *FDecl = NULL; 2091 DeclarationName UnqualifiedName; 2092 2093 if (getLangOptions().CPlusPlus) { 2094 // Determine whether this is a dependent call inside a C++ template, 2095 // in which case we won't do any semantic analysis now. 2096 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn. 2097 bool Dependent = false; 2098 if (Fn->isTypeDependent()) 2099 Dependent = true; 2100 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2101 Dependent = true; 2102 2103 if (Dependent) 2104 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2105 Context.DependentTy, RParenLoc)); 2106 2107 // Determine whether this is a call to an object (C++ [over.call.object]). 2108 if (Fn->getType()->isRecordType()) 2109 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2110 CommaLocs, RParenLoc)); 2111 2112 // Determine whether this is a call to a member function. 2113 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) 2114 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || 2115 isa<CXXMethodDecl>(MemExpr->getMemberDecl())) 2116 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2117 CommaLocs, RParenLoc)); 2118 } 2119 2120 // If we're directly calling a function, get the appropriate declaration. 2121 DeclRefExpr *DRExpr = NULL; 2122 Expr *FnExpr = Fn; 2123 bool ADL = true; 2124 while (true) { 2125 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2126 FnExpr = IcExpr->getSubExpr(); 2127 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2128 // Parentheses around a function disable ADL 2129 // (C++0x [basic.lookup.argdep]p1). 2130 ADL = false; 2131 FnExpr = PExpr->getSubExpr(); 2132 } else if (isa<UnaryOperator>(FnExpr) && 2133 cast<UnaryOperator>(FnExpr)->getOpcode() 2134 == UnaryOperator::AddrOf) { 2135 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2136 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) { 2137 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). 2138 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); 2139 break; 2140 } else if (UnresolvedFunctionNameExpr *DepName 2141 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { 2142 UnqualifiedName = DepName->getName(); 2143 break; 2144 } else { 2145 // Any kind of name that does not refer to a declaration (or 2146 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). 2147 ADL = false; 2148 break; 2149 } 2150 } 2151 2152 OverloadedFunctionDecl *Ovl = 0; 2153 if (DRExpr) { 2154 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 2155 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); 2156 } 2157 2158 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { 2159 // We don't perform ADL for implicit declarations of builtins. 2160 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) 2161 ADL = false; 2162 2163 // We don't perform ADL in C. 2164 if (!getLangOptions().CPlusPlus) 2165 ADL = false; 2166 2167 if (Ovl || ADL) { 2168 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0, 2169 UnqualifiedName, LParenLoc, Args, 2170 NumArgs, CommaLocs, RParenLoc, ADL); 2171 if (!FDecl) 2172 return ExprError(); 2173 2174 // Update Fn to refer to the actual function selected. 2175 Expr *NewFn = 0; 2176 if (QualifiedDeclRefExpr *QDRExpr 2177 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr)) 2178 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), 2179 QDRExpr->getLocation(), 2180 false, false, 2181 QDRExpr->getSourceRange().getBegin()); 2182 else 2183 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), 2184 Fn->getSourceRange().getBegin()); 2185 Fn->Destroy(Context); 2186 Fn = NewFn; 2187 } 2188 } 2189 2190 // Promote the function operand. 2191 UsualUnaryConversions(Fn); 2192 2193 // Make the call expr early, before semantic checks. This guarantees cleanup 2194 // of arguments and function on error. 2195 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2196 Args, NumArgs, 2197 Context.BoolTy, 2198 RParenLoc)); 2199 2200 const FunctionType *FuncT; 2201 if (!Fn->getType()->isBlockPointerType()) { 2202 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2203 // have type pointer to function". 2204 const PointerType *PT = Fn->getType()->getAsPointerType(); 2205 if (PT == 0) 2206 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2207 << Fn->getType() << Fn->getSourceRange()); 2208 FuncT = PT->getPointeeType()->getAsFunctionType(); 2209 } else { // This is a block call. 2210 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 2211 getAsFunctionType(); 2212 } 2213 if (FuncT == 0) 2214 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2215 << Fn->getType() << Fn->getSourceRange()); 2216 2217 // We know the result type of the call, set it. 2218 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2219 2220 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2221 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2222 RParenLoc)) 2223 return ExprError(); 2224 } else { 2225 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2226 2227 // Promote the arguments (C99 6.5.2.2p6). 2228 for (unsigned i = 0; i != NumArgs; i++) { 2229 Expr *Arg = Args[i]; 2230 DefaultArgumentPromotion(Arg); 2231 TheCall->setArg(i, Arg); 2232 } 2233 } 2234 2235 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2236 if (!Method->isStatic()) 2237 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2238 << Fn->getSourceRange()); 2239 2240 // Do special checking on direct calls to functions. 2241 if (FDecl) 2242 return CheckFunctionCall(FDecl, TheCall.take()); 2243 2244 return Owned(TheCall.take()); 2245} 2246 2247Action::OwningExprResult 2248Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 2249 SourceLocation RParenLoc, ExprArg InitExpr) { 2250 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 2251 QualType literalType = QualType::getFromOpaquePtr(Ty); 2252 // FIXME: put back this assert when initializers are worked out. 2253 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 2254 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 2255 2256 if (literalType->isArrayType()) { 2257 if (literalType->isVariableArrayType()) 2258 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 2259 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 2260 } else if (DiagnoseIncompleteType(LParenLoc, literalType, 2261 diag::err_typecheck_decl_incomplete_type, 2262 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()))) 2263 return ExprError(); 2264 2265 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 2266 DeclarationName(), /*FIXME:DirectInit=*/false)) 2267 return ExprError(); 2268 2269 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 2270 if (isFileScope) { // 6.5.2.5p3 2271 if (CheckForConstantInitializer(literalExpr, literalType)) 2272 return ExprError(); 2273 } 2274 InitExpr.release(); 2275 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 2276 literalExpr, isFileScope)); 2277} 2278 2279Action::OwningExprResult 2280Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 2281 InitListDesignations &Designators, 2282 SourceLocation RBraceLoc) { 2283 unsigned NumInit = initlist.size(); 2284 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 2285 2286 // Semantic analysis for initializers is done by ActOnDeclarator() and 2287 // CheckInitializer() - it requires knowledge of the object being intialized. 2288 2289 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 2290 RBraceLoc); 2291 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 2292 return Owned(E); 2293} 2294 2295/// CheckCastTypes - Check type constraints for casting between types. 2296bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 2297 UsualUnaryConversions(castExpr); 2298 2299 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2300 // type needs to be scalar. 2301 if (castType->isVoidType()) { 2302 // Cast to void allows any expr type. 2303 } else if (castType->isDependentType() || castExpr->isTypeDependent()) { 2304 // We can't check any more until template instantiation time. 2305 } else if (!castType->isScalarType() && !castType->isVectorType()) { 2306 if (Context.getCanonicalType(castType).getUnqualifiedType() == 2307 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && 2308 (castType->isStructureType() || castType->isUnionType())) { 2309 // GCC struct/union extension: allow cast to self. 2310 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 2311 << castType << castExpr->getSourceRange(); 2312 } else if (castType->isUnionType()) { 2313 // GCC cast to union extension 2314 RecordDecl *RD = castType->getAsRecordType()->getDecl(); 2315 RecordDecl::field_iterator Field, FieldEnd; 2316 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2317 Field != FieldEnd; ++Field) { 2318 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == 2319 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { 2320 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 2321 << castExpr->getSourceRange(); 2322 break; 2323 } 2324 } 2325 if (Field == FieldEnd) 2326 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2327 << castExpr->getType() << castExpr->getSourceRange(); 2328 } else { 2329 // Reject any other conversions to non-scalar types. 2330 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 2331 << castType << castExpr->getSourceRange(); 2332 } 2333 } else if (!castExpr->getType()->isScalarType() && 2334 !castExpr->getType()->isVectorType()) { 2335 return Diag(castExpr->getLocStart(), 2336 diag::err_typecheck_expect_scalar_operand) 2337 << castExpr->getType() << castExpr->getSourceRange(); 2338 } else if (castExpr->getType()->isVectorType()) { 2339 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 2340 return true; 2341 } else if (castType->isVectorType()) { 2342 if (CheckVectorCast(TyR, castType, castExpr->getType())) 2343 return true; 2344 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { 2345 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 2346 } 2347 return false; 2348} 2349 2350bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 2351 assert(VectorTy->isVectorType() && "Not a vector type!"); 2352 2353 if (Ty->isVectorType() || Ty->isIntegerType()) { 2354 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 2355 return Diag(R.getBegin(), 2356 Ty->isVectorType() ? 2357 diag::err_invalid_conversion_between_vectors : 2358 diag::err_invalid_conversion_between_vector_and_integer) 2359 << VectorTy << Ty << R; 2360 } else 2361 return Diag(R.getBegin(), 2362 diag::err_invalid_conversion_between_vector_and_scalar) 2363 << VectorTy << Ty << R; 2364 2365 return false; 2366} 2367 2368Action::OwningExprResult 2369Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 2370 SourceLocation RParenLoc, ExprArg Op) { 2371 assert((Ty != 0) && (Op.get() != 0) && 2372 "ActOnCastExpr(): missing type or expr"); 2373 2374 Expr *castExpr = static_cast<Expr*>(Op.release()); 2375 QualType castType = QualType::getFromOpaquePtr(Ty); 2376 2377 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 2378 return ExprError(); 2379 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType, 2380 LParenLoc, RParenLoc)); 2381} 2382 2383/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 2384/// In that case, lhs = cond. 2385/// C99 6.5.15 2386QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2387 SourceLocation QuestionLoc) { 2388 UsualUnaryConversions(Cond); 2389 UsualUnaryConversions(LHS); 2390 UsualUnaryConversions(RHS); 2391 QualType CondTy = Cond->getType(); 2392 QualType LHSTy = LHS->getType(); 2393 QualType RHSTy = RHS->getType(); 2394 2395 // first, check the condition. 2396 if (!Cond->isTypeDependent()) { 2397 if (!CondTy->isScalarType()) { // C99 6.5.15p2 2398 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 2399 << CondTy; 2400 return QualType(); 2401 } 2402 } 2403 2404 // Now check the two expressions. 2405 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent())) 2406 return Context.DependentTy; 2407 2408 // If both operands have arithmetic type, do the usual arithmetic conversions 2409 // to find a common type: C99 6.5.15p3,5. 2410 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 2411 UsualArithmeticConversions(LHS, RHS); 2412 return LHS->getType(); 2413 } 2414 2415 // If both operands are the same structure or union type, the result is that 2416 // type. 2417 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3 2418 if (const RecordType *RHSRT = RHSTy->getAsRecordType()) 2419 if (LHSRT->getDecl() == RHSRT->getDecl()) 2420 // "If both the operands have structure or union type, the result has 2421 // that type." This implies that CV qualifiers are dropped. 2422 return LHSTy.getUnqualifiedType(); 2423 } 2424 2425 // C99 6.5.15p5: "If both operands have void type, the result has void type." 2426 // The following || allows only one side to be void (a GCC-ism). 2427 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 2428 if (!LHSTy->isVoidType()) 2429 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2430 << RHS->getSourceRange(); 2431 if (!RHSTy->isVoidType()) 2432 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 2433 << LHS->getSourceRange(); 2434 ImpCastExprToType(LHS, Context.VoidTy); 2435 ImpCastExprToType(RHS, Context.VoidTy); 2436 return Context.VoidTy; 2437 } 2438 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 2439 // the type of the other operand." 2440 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() || 2441 Context.isObjCObjectPointerType(LHSTy)) && 2442 RHS->isNullPointerConstant(Context)) { 2443 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. 2444 return LHSTy; 2445 } 2446 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() || 2447 Context.isObjCObjectPointerType(RHSTy)) && 2448 LHS->isNullPointerConstant(Context)) { 2449 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. 2450 return RHSTy; 2451 } 2452 2453 // Handle the case where both operands are pointers before we handle null 2454 // pointer constants in case both operands are null pointer constants. 2455 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6 2456 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) { 2457 // get the "pointed to" types 2458 QualType lhptee = LHSPT->getPointeeType(); 2459 QualType rhptee = RHSPT->getPointeeType(); 2460 2461 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 2462 if (lhptee->isVoidType() && 2463 rhptee->isIncompleteOrObjectType()) { 2464 // Figure out necessary qualifiers (C99 6.5.15p6) 2465 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 2466 QualType destType = Context.getPointerType(destPointee); 2467 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2468 ImpCastExprToType(RHS, destType); // promote to void* 2469 return destType; 2470 } 2471 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 2472 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 2473 QualType destType = Context.getPointerType(destPointee); 2474 ImpCastExprToType(LHS, destType); // add qualifiers if necessary 2475 ImpCastExprToType(RHS, destType); // promote to void* 2476 return destType; 2477 } 2478 2479 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 2480 // Two identical pointer types are always compatible. 2481 return LHSTy; 2482 } 2483 2484 QualType compositeType = LHSTy; 2485 2486 // If either type is an Objective-C object type then check 2487 // compatibility according to Objective-C. 2488 if (Context.isObjCObjectPointerType(LHSTy) || 2489 Context.isObjCObjectPointerType(RHSTy)) { 2490 // If both operands are interfaces and either operand can be 2491 // assigned to the other, use that type as the composite 2492 // type. This allows 2493 // xxx ? (A*) a : (B*) b 2494 // where B is a subclass of A. 2495 // 2496 // Additionally, as for assignment, if either type is 'id' 2497 // allow silent coercion. Finally, if the types are 2498 // incompatible then make sure to use 'id' as the composite 2499 // type so the result is acceptable for sending messages to. 2500 2501 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 2502 // It could return the composite type. 2503 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 2504 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 2505 if (LHSIface && RHSIface && 2506 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 2507 compositeType = LHSTy; 2508 } else if (LHSIface && RHSIface && 2509 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) { 2510 compositeType = RHSTy; 2511 } else if (Context.isObjCIdStructType(lhptee) || 2512 Context.isObjCIdStructType(rhptee)) { 2513 compositeType = Context.getObjCIdType(); 2514 } else { 2515 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers) 2516 << LHSTy << RHSTy 2517 << LHS->getSourceRange() << RHS->getSourceRange(); 2518 QualType incompatTy = Context.getObjCIdType(); 2519 ImpCastExprToType(LHS, incompatTy); 2520 ImpCastExprToType(RHS, incompatTy); 2521 return incompatTy; 2522 } 2523 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2524 rhptee.getUnqualifiedType())) { 2525 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 2526 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2527 // In this situation, we assume void* type. No especially good 2528 // reason, but this is what gcc does, and we do have to pick 2529 // to get a consistent AST. 2530 QualType incompatTy = Context.getPointerType(Context.VoidTy); 2531 ImpCastExprToType(LHS, incompatTy); 2532 ImpCastExprToType(RHS, incompatTy); 2533 return incompatTy; 2534 } 2535 // The pointer types are compatible. 2536 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 2537 // differently qualified versions of compatible types, the result type is 2538 // a pointer to an appropriately qualified version of the *composite* 2539 // type. 2540 // FIXME: Need to calculate the composite type. 2541 // FIXME: Need to add qualifiers 2542 ImpCastExprToType(LHS, compositeType); 2543 ImpCastExprToType(RHS, compositeType); 2544 return compositeType; 2545 } 2546 } 2547 2548 // Selection between block pointer types is ok as long as they are the same. 2549 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() && 2550 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) 2551 return LHSTy; 2552 2553 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 2554 // evaluates to "struct objc_object *" (and is handled above when comparing 2555 // id with statically typed objects). 2556 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) { 2557 // GCC allows qualified id and any Objective-C type to devolve to 2558 // id. Currently localizing to here until clear this should be 2559 // part of ObjCQualifiedIdTypesAreCompatible. 2560 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) || 2561 (LHSTy->isObjCQualifiedIdType() && 2562 Context.isObjCObjectPointerType(RHSTy)) || 2563 (RHSTy->isObjCQualifiedIdType() && 2564 Context.isObjCObjectPointerType(LHSTy))) { 2565 // FIXME: This is not the correct composite type. This only 2566 // happens to work because id can more or less be used anywhere, 2567 // however this may change the type of method sends. 2568 // FIXME: gcc adds some type-checking of the arguments and emits 2569 // (confusing) incompatible comparison warnings in some 2570 // cases. Investigate. 2571 QualType compositeType = Context.getObjCIdType(); 2572 ImpCastExprToType(LHS, compositeType); 2573 ImpCastExprToType(RHS, compositeType); 2574 return compositeType; 2575 } 2576 } 2577 2578 // Otherwise, the operands are not compatible. 2579 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2580 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 2581 return QualType(); 2582} 2583 2584/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2585/// in the case of a the GNU conditional expr extension. 2586Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 2587 SourceLocation ColonLoc, 2588 ExprArg Cond, ExprArg LHS, 2589 ExprArg RHS) { 2590 Expr *CondExpr = (Expr *) Cond.get(); 2591 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 2592 2593 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 2594 // was the condition. 2595 bool isLHSNull = LHSExpr == 0; 2596 if (isLHSNull) 2597 LHSExpr = CondExpr; 2598 2599 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 2600 RHSExpr, QuestionLoc); 2601 if (result.isNull()) 2602 return ExprError(); 2603 2604 Cond.release(); 2605 LHS.release(); 2606 RHS.release(); 2607 return Owned(new (Context) ConditionalOperator(CondExpr, 2608 isLHSNull ? 0 : LHSExpr, 2609 RHSExpr, result)); 2610} 2611 2612 2613// CheckPointerTypesForAssignment - This is a very tricky routine (despite 2614// being closely modeled after the C99 spec:-). The odd characteristic of this 2615// routine is it effectively iqnores the qualifiers on the top level pointee. 2616// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 2617// FIXME: add a couple examples in this comment. 2618Sema::AssignConvertType 2619Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 2620 QualType lhptee, rhptee; 2621 2622 // get the "pointed to" type (ignoring qualifiers at the top level) 2623 lhptee = lhsType->getAsPointerType()->getPointeeType(); 2624 rhptee = rhsType->getAsPointerType()->getPointeeType(); 2625 2626 // make sure we operate on the canonical type 2627 lhptee = Context.getCanonicalType(lhptee); 2628 rhptee = Context.getCanonicalType(rhptee); 2629 2630 AssignConvertType ConvTy = Compatible; 2631 2632 // C99 6.5.16.1p1: This following citation is common to constraints 2633 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 2634 // qualifiers of the type *pointed to* by the right; 2635 // FIXME: Handle ExtQualType 2636 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 2637 ConvTy = CompatiblePointerDiscardsQualifiers; 2638 2639 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 2640 // incomplete type and the other is a pointer to a qualified or unqualified 2641 // version of void... 2642 if (lhptee->isVoidType()) { 2643 if (rhptee->isIncompleteOrObjectType()) 2644 return ConvTy; 2645 2646 // As an extension, we allow cast to/from void* to function pointer. 2647 assert(rhptee->isFunctionType()); 2648 return FunctionVoidPointer; 2649 } 2650 2651 if (rhptee->isVoidType()) { 2652 if (lhptee->isIncompleteOrObjectType()) 2653 return ConvTy; 2654 2655 // As an extension, we allow cast to/from void* to function pointer. 2656 assert(lhptee->isFunctionType()); 2657 return FunctionVoidPointer; 2658 } 2659 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 2660 // unqualified versions of compatible types, ... 2661 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 2662 rhptee.getUnqualifiedType())) 2663 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 2664 return ConvTy; 2665} 2666 2667/// CheckBlockPointerTypesForAssignment - This routine determines whether two 2668/// block pointer types are compatible or whether a block and normal pointer 2669/// are compatible. It is more restrict than comparing two function pointer 2670// types. 2671Sema::AssignConvertType 2672Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 2673 QualType rhsType) { 2674 QualType lhptee, rhptee; 2675 2676 // get the "pointed to" type (ignoring qualifiers at the top level) 2677 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 2678 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 2679 2680 // make sure we operate on the canonical type 2681 lhptee = Context.getCanonicalType(lhptee); 2682 rhptee = Context.getCanonicalType(rhptee); 2683 2684 AssignConvertType ConvTy = Compatible; 2685 2686 // For blocks we enforce that qualifiers are identical. 2687 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 2688 ConvTy = CompatiblePointerDiscardsQualifiers; 2689 2690 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 2691 return IncompatibleBlockPointer; 2692 return ConvTy; 2693} 2694 2695/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 2696/// has code to accommodate several GCC extensions when type checking 2697/// pointers. Here are some objectionable examples that GCC considers warnings: 2698/// 2699/// int a, *pint; 2700/// short *pshort; 2701/// struct foo *pfoo; 2702/// 2703/// pint = pshort; // warning: assignment from incompatible pointer type 2704/// a = pint; // warning: assignment makes integer from pointer without a cast 2705/// pint = a; // warning: assignment makes pointer from integer without a cast 2706/// pint = pfoo; // warning: assignment from incompatible pointer type 2707/// 2708/// As a result, the code for dealing with pointers is more complex than the 2709/// C99 spec dictates. 2710/// 2711Sema::AssignConvertType 2712Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 2713 // Get canonical types. We're not formatting these types, just comparing 2714 // them. 2715 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 2716 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 2717 2718 if (lhsType == rhsType) 2719 return Compatible; // Common case: fast path an exact match. 2720 2721 // If the left-hand side is a reference type, then we are in a 2722 // (rare!) case where we've allowed the use of references in C, 2723 // e.g., as a parameter type in a built-in function. In this case, 2724 // just make sure that the type referenced is compatible with the 2725 // right-hand side type. The caller is responsible for adjusting 2726 // lhsType so that the resulting expression does not have reference 2727 // type. 2728 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 2729 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 2730 return Compatible; 2731 return Incompatible; 2732 } 2733 2734 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 2735 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 2736 return Compatible; 2737 // Relax integer conversions like we do for pointers below. 2738 if (rhsType->isIntegerType()) 2739 return IntToPointer; 2740 if (lhsType->isIntegerType()) 2741 return PointerToInt; 2742 return IncompatibleObjCQualifiedId; 2743 } 2744 2745 if (lhsType->isVectorType() || rhsType->isVectorType()) { 2746 // For ExtVector, allow vector splats; float -> <n x float> 2747 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 2748 if (LV->getElementType() == rhsType) 2749 return Compatible; 2750 2751 // If we are allowing lax vector conversions, and LHS and RHS are both 2752 // vectors, the total size only needs to be the same. This is a bitcast; 2753 // no bits are changed but the result type is different. 2754 if (getLangOptions().LaxVectorConversions && 2755 lhsType->isVectorType() && rhsType->isVectorType()) { 2756 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 2757 return IncompatibleVectors; 2758 } 2759 return Incompatible; 2760 } 2761 2762 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 2763 return Compatible; 2764 2765 if (isa<PointerType>(lhsType)) { 2766 if (rhsType->isIntegerType()) 2767 return IntToPointer; 2768 2769 if (isa<PointerType>(rhsType)) 2770 return CheckPointerTypesForAssignment(lhsType, rhsType); 2771 2772 if (rhsType->getAsBlockPointerType()) { 2773 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2774 return Compatible; 2775 2776 // Treat block pointers as objects. 2777 if (getLangOptions().ObjC1 && 2778 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 2779 return Compatible; 2780 } 2781 return Incompatible; 2782 } 2783 2784 if (isa<BlockPointerType>(lhsType)) { 2785 if (rhsType->isIntegerType()) 2786 return IntToBlockPointer; 2787 2788 // Treat block pointers as objects. 2789 if (getLangOptions().ObjC1 && 2790 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 2791 return Compatible; 2792 2793 if (rhsType->isBlockPointerType()) 2794 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 2795 2796 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 2797 if (RHSPT->getPointeeType()->isVoidType()) 2798 return Compatible; 2799 } 2800 return Incompatible; 2801 } 2802 2803 if (isa<PointerType>(rhsType)) { 2804 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 2805 if (lhsType == Context.BoolTy) 2806 return Compatible; 2807 2808 if (lhsType->isIntegerType()) 2809 return PointerToInt; 2810 2811 if (isa<PointerType>(lhsType)) 2812 return CheckPointerTypesForAssignment(lhsType, rhsType); 2813 2814 if (isa<BlockPointerType>(lhsType) && 2815 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 2816 return Compatible; 2817 return Incompatible; 2818 } 2819 2820 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 2821 if (Context.typesAreCompatible(lhsType, rhsType)) 2822 return Compatible; 2823 } 2824 return Incompatible; 2825} 2826 2827Sema::AssignConvertType 2828Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 2829 if (getLangOptions().CPlusPlus) { 2830 if (!lhsType->isRecordType()) { 2831 // C++ 5.17p3: If the left operand is not of class type, the 2832 // expression is implicitly converted (C++ 4) to the 2833 // cv-unqualified type of the left operand. 2834 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 2835 "assigning")) 2836 return Incompatible; 2837 else 2838 return Compatible; 2839 } 2840 2841 // FIXME: Currently, we fall through and treat C++ classes like C 2842 // structures. 2843 } 2844 2845 // C99 6.5.16.1p1: the left operand is a pointer and the right is 2846 // a null pointer constant. 2847 if ((lhsType->isPointerType() || 2848 lhsType->isObjCQualifiedIdType() || 2849 lhsType->isBlockPointerType()) 2850 && rExpr->isNullPointerConstant(Context)) { 2851 ImpCastExprToType(rExpr, lhsType); 2852 return Compatible; 2853 } 2854 2855 // This check seems unnatural, however it is necessary to ensure the proper 2856 // conversion of functions/arrays. If the conversion were done for all 2857 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 2858 // expressions that surpress this implicit conversion (&, sizeof). 2859 // 2860 // Suppress this for references: C++ 8.5.3p5. 2861 if (!lhsType->isReferenceType()) 2862 DefaultFunctionArrayConversion(rExpr); 2863 2864 Sema::AssignConvertType result = 2865 CheckAssignmentConstraints(lhsType, rExpr->getType()); 2866 2867 // C99 6.5.16.1p2: The value of the right operand is converted to the 2868 // type of the assignment expression. 2869 // CheckAssignmentConstraints allows the left-hand side to be a reference, 2870 // so that we can use references in built-in functions even in C. 2871 // The getNonReferenceType() call makes sure that the resulting expression 2872 // does not have reference type. 2873 if (rExpr->getType() != lhsType) 2874 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 2875 return result; 2876} 2877 2878Sema::AssignConvertType 2879Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 2880 return CheckAssignmentConstraints(lhsType, rhsType); 2881} 2882 2883QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 2884 Diag(Loc, diag::err_typecheck_invalid_operands) 2885 << lex->getType() << rex->getType() 2886 << lex->getSourceRange() << rex->getSourceRange(); 2887 return QualType(); 2888} 2889 2890inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 2891 Expr *&rex) { 2892 // For conversion purposes, we ignore any qualifiers. 2893 // For example, "const float" and "float" are equivalent. 2894 QualType lhsType = 2895 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 2896 QualType rhsType = 2897 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 2898 2899 // If the vector types are identical, return. 2900 if (lhsType == rhsType) 2901 return lhsType; 2902 2903 // Handle the case of a vector & extvector type of the same size and element 2904 // type. It would be nice if we only had one vector type someday. 2905 if (getLangOptions().LaxVectorConversions) { 2906 // FIXME: Should we warn here? 2907 if (const VectorType *LV = lhsType->getAsVectorType()) { 2908 if (const VectorType *RV = rhsType->getAsVectorType()) 2909 if (LV->getElementType() == RV->getElementType() && 2910 LV->getNumElements() == RV->getNumElements()) { 2911 return lhsType->isExtVectorType() ? lhsType : rhsType; 2912 } 2913 } 2914 } 2915 2916 // If the lhs is an extended vector and the rhs is a scalar of the same type 2917 // or a literal, promote the rhs to the vector type. 2918 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 2919 QualType eltType = V->getElementType(); 2920 2921 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 2922 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 2923 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 2924 ImpCastExprToType(rex, lhsType); 2925 return lhsType; 2926 } 2927 } 2928 2929 // If the rhs is an extended vector and the lhs is a scalar of the same type, 2930 // promote the lhs to the vector type. 2931 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 2932 QualType eltType = V->getElementType(); 2933 2934 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 2935 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 2936 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 2937 ImpCastExprToType(lex, rhsType); 2938 return rhsType; 2939 } 2940 } 2941 2942 // You cannot convert between vector values of different size. 2943 Diag(Loc, diag::err_typecheck_vector_not_convertable) 2944 << lex->getType() << rex->getType() 2945 << lex->getSourceRange() << rex->getSourceRange(); 2946 return QualType(); 2947} 2948 2949inline QualType Sema::CheckMultiplyDivideOperands( 2950 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2951{ 2952 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2953 return CheckVectorOperands(Loc, lex, rex); 2954 2955 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2956 2957 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2958 return compType; 2959 return InvalidOperands(Loc, lex, rex); 2960} 2961 2962inline QualType Sema::CheckRemainderOperands( 2963 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2964{ 2965 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 2966 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2967 return CheckVectorOperands(Loc, lex, rex); 2968 return InvalidOperands(Loc, lex, rex); 2969 } 2970 2971 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2972 2973 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2974 return compType; 2975 return InvalidOperands(Loc, lex, rex); 2976} 2977 2978inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 2979 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2980{ 2981 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2982 return CheckVectorOperands(Loc, lex, rex); 2983 2984 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2985 2986 // handle the common case first (both operands are arithmetic). 2987 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2988 return compType; 2989 2990 // Put any potential pointer into PExp 2991 Expr* PExp = lex, *IExp = rex; 2992 if (IExp->getType()->isPointerType()) 2993 std::swap(PExp, IExp); 2994 2995 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 2996 if (IExp->getType()->isIntegerType()) { 2997 // Check for arithmetic on pointers to incomplete types 2998 if (!PTy->getPointeeType()->isObjectType()) { 2999 if (PTy->getPointeeType()->isVoidType()) { 3000 if (getLangOptions().CPlusPlus) { 3001 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 3002 << lex->getSourceRange() << rex->getSourceRange(); 3003 return QualType(); 3004 } 3005 3006 // GNU extension: arithmetic on pointer to void 3007 Diag(Loc, diag::ext_gnu_void_ptr) 3008 << lex->getSourceRange() << rex->getSourceRange(); 3009 } else if (PTy->getPointeeType()->isFunctionType()) { 3010 if (getLangOptions().CPlusPlus) { 3011 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3012 << lex->getType() << lex->getSourceRange(); 3013 return QualType(); 3014 } 3015 3016 // GNU extension: arithmetic on pointer to function 3017 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3018 << lex->getType() << lex->getSourceRange(); 3019 } else { 3020 DiagnoseIncompleteType(Loc, PTy->getPointeeType(), 3021 diag::err_typecheck_arithmetic_incomplete_type, 3022 lex->getSourceRange(), SourceRange(), 3023 lex->getType()); 3024 return QualType(); 3025 } 3026 } 3027 return PExp->getType(); 3028 } 3029 } 3030 3031 return InvalidOperands(Loc, lex, rex); 3032} 3033 3034// C99 6.5.6 3035QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 3036 SourceLocation Loc, bool isCompAssign) { 3037 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3038 return CheckVectorOperands(Loc, lex, rex); 3039 3040 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3041 3042 // Enforce type constraints: C99 6.5.6p3. 3043 3044 // Handle the common case first (both operands are arithmetic). 3045 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3046 return compType; 3047 3048 // Either ptr - int or ptr - ptr. 3049 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 3050 QualType lpointee = LHSPTy->getPointeeType(); 3051 3052 // The LHS must be an object type, not incomplete, function, etc. 3053 if (!lpointee->isObjectType()) { 3054 // Handle the GNU void* extension. 3055 if (lpointee->isVoidType()) { 3056 Diag(Loc, diag::ext_gnu_void_ptr) 3057 << lex->getSourceRange() << rex->getSourceRange(); 3058 } else if (lpointee->isFunctionType()) { 3059 if (getLangOptions().CPlusPlus) { 3060 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3061 << lex->getType() << lex->getSourceRange(); 3062 return QualType(); 3063 } 3064 3065 // GNU extension: arithmetic on pointer to function 3066 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3067 << lex->getType() << lex->getSourceRange(); 3068 } else { 3069 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3070 << lex->getType() << lex->getSourceRange(); 3071 return QualType(); 3072 } 3073 } 3074 3075 // The result type of a pointer-int computation is the pointer type. 3076 if (rex->getType()->isIntegerType()) 3077 return lex->getType(); 3078 3079 // Handle pointer-pointer subtractions. 3080 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 3081 QualType rpointee = RHSPTy->getPointeeType(); 3082 3083 // RHS must be an object type, unless void (GNU). 3084 if (!rpointee->isObjectType()) { 3085 // Handle the GNU void* extension. 3086 if (rpointee->isVoidType()) { 3087 if (!lpointee->isVoidType()) 3088 Diag(Loc, diag::ext_gnu_void_ptr) 3089 << lex->getSourceRange() << rex->getSourceRange(); 3090 } else if (rpointee->isFunctionType()) { 3091 if (getLangOptions().CPlusPlus) { 3092 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 3093 << rex->getType() << rex->getSourceRange(); 3094 return QualType(); 3095 } 3096 3097 // GNU extension: arithmetic on pointer to function 3098 if (!lpointee->isFunctionType()) 3099 Diag(Loc, diag::ext_gnu_ptr_func_arith) 3100 << lex->getType() << lex->getSourceRange(); 3101 } else { 3102 Diag(Loc, diag::err_typecheck_sub_ptr_object) 3103 << rex->getType() << rex->getSourceRange(); 3104 return QualType(); 3105 } 3106 } 3107 3108 // Pointee types must be compatible. 3109 if (!Context.typesAreCompatible( 3110 Context.getCanonicalType(lpointee).getUnqualifiedType(), 3111 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 3112 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 3113 << lex->getType() << rex->getType() 3114 << lex->getSourceRange() << rex->getSourceRange(); 3115 return QualType(); 3116 } 3117 3118 return Context.getPointerDiffType(); 3119 } 3120 } 3121 3122 return InvalidOperands(Loc, lex, rex); 3123} 3124 3125// C99 6.5.7 3126QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3127 bool isCompAssign) { 3128 // C99 6.5.7p2: Each of the operands shall have integer type. 3129 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 3130 return InvalidOperands(Loc, lex, rex); 3131 3132 // Shifts don't perform usual arithmetic conversions, they just do integer 3133 // promotions on each operand. C99 6.5.7p3 3134 if (!isCompAssign) 3135 UsualUnaryConversions(lex); 3136 UsualUnaryConversions(rex); 3137 3138 // "The type of the result is that of the promoted left operand." 3139 return lex->getType(); 3140} 3141 3142// C99 6.5.8 3143QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 3144 bool isRelational) { 3145 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3146 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 3147 3148 // C99 6.5.8p3 / C99 6.5.9p4 3149 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 3150 UsualArithmeticConversions(lex, rex); 3151 else { 3152 UsualUnaryConversions(lex); 3153 UsualUnaryConversions(rex); 3154 } 3155 QualType lType = lex->getType(); 3156 QualType rType = rex->getType(); 3157 3158 // For non-floating point types, check for self-comparisons of the form 3159 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3160 // often indicate logic errors in the program. 3161 if (!lType->isFloatingType()) { 3162 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 3163 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 3164 if (DRL->getDecl() == DRR->getDecl()) 3165 Diag(Loc, diag::warn_selfcomparison); 3166 } 3167 3168 // The result of comparisons is 'bool' in C++, 'int' in C. 3169 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy; 3170 3171 if (isRelational) { 3172 if (lType->isRealType() && rType->isRealType()) 3173 return ResultTy; 3174 } else { 3175 // Check for comparisons of floating point operands using != and ==. 3176 if (lType->isFloatingType()) { 3177 assert (rType->isFloatingType()); 3178 CheckFloatComparison(Loc,lex,rex); 3179 } 3180 3181 if (lType->isArithmeticType() && rType->isArithmeticType()) 3182 return ResultTy; 3183 } 3184 3185 bool LHSIsNull = lex->isNullPointerConstant(Context); 3186 bool RHSIsNull = rex->isNullPointerConstant(Context); 3187 3188 // All of the following pointer related warnings are GCC extensions, except 3189 // when handling null pointer constants. One day, we can consider making them 3190 // errors (when -pedantic-errors is enabled). 3191 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 3192 QualType LCanPointeeTy = 3193 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 3194 QualType RCanPointeeTy = 3195 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 3196 3197 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 3198 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 3199 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 3200 RCanPointeeTy.getUnqualifiedType()) && 3201 !Context.areComparableObjCPointerTypes(lType, rType)) { 3202 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3203 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3204 } 3205 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3206 return ResultTy; 3207 } 3208 // Handle block pointer types. 3209 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 3210 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 3211 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 3212 3213 if (!LHSIsNull && !RHSIsNull && 3214 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 3215 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3216 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3217 } 3218 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3219 return ResultTy; 3220 } 3221 // Allow block pointers to be compared with null pointer constants. 3222 if ((lType->isBlockPointerType() && rType->isPointerType()) || 3223 (lType->isPointerType() && rType->isBlockPointerType())) { 3224 if (!LHSIsNull && !RHSIsNull) { 3225 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 3226 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3227 } 3228 ImpCastExprToType(rex, lType); // promote the pointer to pointer 3229 return ResultTy; 3230 } 3231 3232 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 3233 if (lType->isPointerType() || rType->isPointerType()) { 3234 const PointerType *LPT = lType->getAsPointerType(); 3235 const PointerType *RPT = rType->getAsPointerType(); 3236 bool LPtrToVoid = LPT ? 3237 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 3238 bool RPtrToVoid = RPT ? 3239 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 3240 3241 if (!LPtrToVoid && !RPtrToVoid && 3242 !Context.typesAreCompatible(lType, rType)) { 3243 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 3244 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3245 ImpCastExprToType(rex, lType); 3246 return ResultTy; 3247 } 3248 ImpCastExprToType(rex, lType); 3249 return ResultTy; 3250 } 3251 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 3252 ImpCastExprToType(rex, lType); 3253 return ResultTy; 3254 } else { 3255 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 3256 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 3257 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3258 ImpCastExprToType(rex, lType); 3259 return ResultTy; 3260 } 3261 } 3262 } 3263 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 3264 rType->isIntegerType()) { 3265 if (!RHSIsNull) 3266 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3267 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3268 ImpCastExprToType(rex, lType); // promote the integer to pointer 3269 return ResultTy; 3270 } 3271 if (lType->isIntegerType() && 3272 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 3273 if (!LHSIsNull) 3274 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3275 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3276 ImpCastExprToType(lex, rType); // promote the integer to pointer 3277 return ResultTy; 3278 } 3279 // Handle block pointers. 3280 if (lType->isBlockPointerType() && rType->isIntegerType()) { 3281 if (!RHSIsNull) 3282 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3283 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3284 ImpCastExprToType(rex, lType); // promote the integer to pointer 3285 return ResultTy; 3286 } 3287 if (lType->isIntegerType() && rType->isBlockPointerType()) { 3288 if (!LHSIsNull) 3289 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 3290 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 3291 ImpCastExprToType(lex, rType); // promote the integer to pointer 3292 return ResultTy; 3293 } 3294 return InvalidOperands(Loc, lex, rex); 3295} 3296 3297/// CheckVectorCompareOperands - vector comparisons are a clang extension that 3298/// operates on extended vector types. Instead of producing an IntTy result, 3299/// like a scalar comparison, a vector comparison produces a vector of integer 3300/// types. 3301QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 3302 SourceLocation Loc, 3303 bool isRelational) { 3304 // Check to make sure we're operating on vectors of the same type and width, 3305 // Allowing one side to be a scalar of element type. 3306 QualType vType = CheckVectorOperands(Loc, lex, rex); 3307 if (vType.isNull()) 3308 return vType; 3309 3310 QualType lType = lex->getType(); 3311 QualType rType = rex->getType(); 3312 3313 // For non-floating point types, check for self-comparisons of the form 3314 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 3315 // often indicate logic errors in the program. 3316 if (!lType->isFloatingType()) { 3317 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 3318 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 3319 if (DRL->getDecl() == DRR->getDecl()) 3320 Diag(Loc, diag::warn_selfcomparison); 3321 } 3322 3323 // Check for comparisons of floating point operands using != and ==. 3324 if (!isRelational && lType->isFloatingType()) { 3325 assert (rType->isFloatingType()); 3326 CheckFloatComparison(Loc,lex,rex); 3327 } 3328 3329 // Return the type for the comparison, which is the same as vector type for 3330 // integer vectors, or an integer type of identical size and number of 3331 // elements for floating point vectors. 3332 if (lType->isIntegerType()) 3333 return lType; 3334 3335 const VectorType *VTy = lType->getAsVectorType(); 3336 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 3337 if (TypeSize == Context.getTypeSize(Context.IntTy)) 3338 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 3339 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 3340 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 3341 3342 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 3343 "Unhandled vector element size in vector compare"); 3344 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 3345} 3346 3347inline QualType Sema::CheckBitwiseOperands( 3348 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 3349{ 3350 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 3351 return CheckVectorOperands(Loc, lex, rex); 3352 3353 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 3354 3355 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 3356 return compType; 3357 return InvalidOperands(Loc, lex, rex); 3358} 3359 3360inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 3361 Expr *&lex, Expr *&rex, SourceLocation Loc) 3362{ 3363 UsualUnaryConversions(lex); 3364 UsualUnaryConversions(rex); 3365 3366 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 3367 return Context.IntTy; 3368 return InvalidOperands(Loc, lex, rex); 3369} 3370 3371/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 3372/// is a read-only property; return true if so. A readonly property expression 3373/// depends on various declarations and thus must be treated specially. 3374/// 3375static bool IsReadonlyProperty(Expr *E, Sema &S) 3376{ 3377 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 3378 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 3379 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 3380 QualType BaseType = PropExpr->getBase()->getType(); 3381 if (const PointerType *PTy = BaseType->getAsPointerType()) 3382 if (const ObjCInterfaceType *IFTy = 3383 PTy->getPointeeType()->getAsObjCInterfaceType()) 3384 if (ObjCInterfaceDecl *IFace = IFTy->getDecl()) 3385 if (S.isPropertyReadonly(PDecl, IFace)) 3386 return true; 3387 } 3388 } 3389 return false; 3390} 3391 3392/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 3393/// emit an error and return true. If so, return false. 3394static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 3395 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context); 3396 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 3397 IsLV = Expr::MLV_ReadonlyProperty; 3398 if (IsLV == Expr::MLV_Valid) 3399 return false; 3400 3401 unsigned Diag = 0; 3402 bool NeedType = false; 3403 switch (IsLV) { // C99 6.5.16p2 3404 default: assert(0 && "Unknown result from isModifiableLvalue!"); 3405 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 3406 case Expr::MLV_ArrayType: 3407 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 3408 NeedType = true; 3409 break; 3410 case Expr::MLV_NotObjectType: 3411 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 3412 NeedType = true; 3413 break; 3414 case Expr::MLV_LValueCast: 3415 Diag = diag::err_typecheck_lvalue_casts_not_supported; 3416 break; 3417 case Expr::MLV_InvalidExpression: 3418 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 3419 break; 3420 case Expr::MLV_IncompleteType: 3421 case Expr::MLV_IncompleteVoidType: 3422 return S.DiagnoseIncompleteType(Loc, E->getType(), 3423 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 3424 E->getSourceRange()); 3425 case Expr::MLV_DuplicateVectorComponents: 3426 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 3427 break; 3428 case Expr::MLV_NotBlockQualified: 3429 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 3430 break; 3431 case Expr::MLV_ReadonlyProperty: 3432 Diag = diag::error_readonly_property_assignment; 3433 break; 3434 case Expr::MLV_NoSetterProperty: 3435 Diag = diag::error_nosetter_property_assignment; 3436 break; 3437 } 3438 3439 if (NeedType) 3440 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange(); 3441 else 3442 S.Diag(Loc, Diag) << E->getSourceRange(); 3443 return true; 3444} 3445 3446 3447 3448// C99 6.5.16.1 3449QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 3450 SourceLocation Loc, 3451 QualType CompoundType) { 3452 // Verify that LHS is a modifiable lvalue, and emit error if not. 3453 if (CheckForModifiableLvalue(LHS, Loc, *this)) 3454 return QualType(); 3455 3456 QualType LHSType = LHS->getType(); 3457 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 3458 3459 AssignConvertType ConvTy; 3460 if (CompoundType.isNull()) { 3461 // Simple assignment "x = y". 3462 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 3463 // Special case of NSObject attributes on c-style pointer types. 3464 if (ConvTy == IncompatiblePointer && 3465 ((Context.isObjCNSObjectType(LHSType) && 3466 Context.isObjCObjectPointerType(RHSType)) || 3467 (Context.isObjCNSObjectType(RHSType) && 3468 Context.isObjCObjectPointerType(LHSType)))) 3469 ConvTy = Compatible; 3470 3471 // If the RHS is a unary plus or minus, check to see if they = and + are 3472 // right next to each other. If so, the user may have typo'd "x =+ 4" 3473 // instead of "x += 4". 3474 Expr *RHSCheck = RHS; 3475 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 3476 RHSCheck = ICE->getSubExpr(); 3477 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 3478 if ((UO->getOpcode() == UnaryOperator::Plus || 3479 UO->getOpcode() == UnaryOperator::Minus) && 3480 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 3481 // Only if the two operators are exactly adjacent. 3482 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc()) 3483 Diag(Loc, diag::warn_not_compound_assign) 3484 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 3485 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 3486 } 3487 } else { 3488 // Compound assignment "x += y" 3489 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); 3490 } 3491 3492 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 3493 RHS, "assigning")) 3494 return QualType(); 3495 3496 // C99 6.5.16p3: The type of an assignment expression is the type of the 3497 // left operand unless the left operand has qualified type, in which case 3498 // it is the unqualified version of the type of the left operand. 3499 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 3500 // is converted to the type of the assignment expression (above). 3501 // C++ 5.17p1: the type of the assignment expression is that of its left 3502 // oprdu. 3503 return LHSType.getUnqualifiedType(); 3504} 3505 3506// C99 6.5.17 3507QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 3508 // FIXME: what is required for LHS? 3509 3510 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 3511 DefaultFunctionArrayConversion(RHS); 3512 return RHS->getType(); 3513} 3514 3515/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 3516/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 3517QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 3518 bool isInc) { 3519 if (Op->isTypeDependent()) 3520 return Context.DependentTy; 3521 3522 QualType ResType = Op->getType(); 3523 assert(!ResType.isNull() && "no type for increment/decrement expression"); 3524 3525 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 3526 // Decrement of bool is not allowed. 3527 if (!isInc) { 3528 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 3529 return QualType(); 3530 } 3531 // Increment of bool sets it to true, but is deprecated. 3532 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 3533 } else if (ResType->isRealType()) { 3534 // OK! 3535 } else if (const PointerType *PT = ResType->getAsPointerType()) { 3536 // C99 6.5.2.4p2, 6.5.6p2 3537 if (PT->getPointeeType()->isObjectType()) { 3538 // Pointer to object is ok! 3539 } else if (PT->getPointeeType()->isVoidType()) { 3540 if (getLangOptions().CPlusPlus) { 3541 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 3542 << Op->getSourceRange(); 3543 return QualType(); 3544 } 3545 3546 // Pointer to void is a GNU extension in C. 3547 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 3548 } else if (PT->getPointeeType()->isFunctionType()) { 3549 if (getLangOptions().CPlusPlus) { 3550 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 3551 << Op->getType() << Op->getSourceRange(); 3552 return QualType(); 3553 } 3554 3555 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 3556 << ResType << Op->getSourceRange(); 3557 return QualType(); 3558 } else { 3559 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(), 3560 diag::err_typecheck_arithmetic_incomplete_type, 3561 Op->getSourceRange(), SourceRange(), 3562 ResType); 3563 return QualType(); 3564 } 3565 } else if (ResType->isComplexType()) { 3566 // C99 does not support ++/-- on complex types, we allow as an extension. 3567 Diag(OpLoc, diag::ext_integer_increment_complex) 3568 << ResType << Op->getSourceRange(); 3569 } else { 3570 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 3571 << ResType << Op->getSourceRange(); 3572 return QualType(); 3573 } 3574 // At this point, we know we have a real, complex or pointer type. 3575 // Now make sure the operand is a modifiable lvalue. 3576 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 3577 return QualType(); 3578 return ResType; 3579} 3580 3581/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 3582/// This routine allows us to typecheck complex/recursive expressions 3583/// where the declaration is needed for type checking. We only need to 3584/// handle cases when the expression references a function designator 3585/// or is an lvalue. Here are some examples: 3586/// - &(x) => x 3587/// - &*****f => f for f a function designator. 3588/// - &s.xx => s 3589/// - &s.zz[1].yy -> s, if zz is an array 3590/// - *(x + 1) -> x, if x is an array 3591/// - &"123"[2] -> 0 3592/// - & __real__ x -> x 3593static NamedDecl *getPrimaryDecl(Expr *E) { 3594 switch (E->getStmtClass()) { 3595 case Stmt::DeclRefExprClass: 3596 case Stmt::QualifiedDeclRefExprClass: 3597 return cast<DeclRefExpr>(E)->getDecl(); 3598 case Stmt::MemberExprClass: 3599 // Fields cannot be declared with a 'register' storage class. 3600 // &X->f is always ok, even if X is declared register. 3601 if (cast<MemberExpr>(E)->isArrow()) 3602 return 0; 3603 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 3604 case Stmt::ArraySubscriptExprClass: { 3605 // &X[4] and &4[X] refers to X if X is not a pointer. 3606 3607 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 3608 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 3609 if (!VD || VD->getType()->isPointerType()) 3610 return 0; 3611 else 3612 return VD; 3613 } 3614 case Stmt::UnaryOperatorClass: { 3615 UnaryOperator *UO = cast<UnaryOperator>(E); 3616 3617 switch(UO->getOpcode()) { 3618 case UnaryOperator::Deref: { 3619 // *(X + 1) refers to X if X is not a pointer. 3620 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { 3621 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3622 if (!VD || VD->getType()->isPointerType()) 3623 return 0; 3624 return VD; 3625 } 3626 return 0; 3627 } 3628 case UnaryOperator::Real: 3629 case UnaryOperator::Imag: 3630 case UnaryOperator::Extension: 3631 return getPrimaryDecl(UO->getSubExpr()); 3632 default: 3633 return 0; 3634 } 3635 } 3636 case Stmt::BinaryOperatorClass: { 3637 BinaryOperator *BO = cast<BinaryOperator>(E); 3638 3639 // Handle cases involving pointer arithmetic. The result of an 3640 // Assign or AddAssign is not an lvalue so they can be ignored. 3641 3642 // (x + n) or (n + x) => x 3643 if (BO->getOpcode() == BinaryOperator::Add) { 3644 if (BO->getLHS()->getType()->isPointerType()) { 3645 return getPrimaryDecl(BO->getLHS()); 3646 } else if (BO->getRHS()->getType()->isPointerType()) { 3647 return getPrimaryDecl(BO->getRHS()); 3648 } 3649 } 3650 3651 return 0; 3652 } 3653 case Stmt::ParenExprClass: 3654 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 3655 case Stmt::ImplicitCastExprClass: 3656 // &X[4] when X is an array, has an implicit cast from array to pointer. 3657 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 3658 default: 3659 return 0; 3660 } 3661} 3662 3663/// CheckAddressOfOperand - The operand of & must be either a function 3664/// designator or an lvalue designating an object. If it is an lvalue, the 3665/// object cannot be declared with storage class register or be a bit field. 3666/// Note: The usual conversions are *not* applied to the operand of the & 3667/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 3668/// In C++, the operand might be an overloaded function name, in which case 3669/// we allow the '&' but retain the overloaded-function type. 3670QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 3671 if (op->isTypeDependent()) 3672 return Context.DependentTy; 3673 3674 if (getLangOptions().C99) { 3675 // Implement C99-only parts of addressof rules. 3676 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 3677 if (uOp->getOpcode() == UnaryOperator::Deref) 3678 // Per C99 6.5.3.2, the address of a deref always returns a valid result 3679 // (assuming the deref expression is valid). 3680 return uOp->getSubExpr()->getType(); 3681 } 3682 // Technically, there should be a check for array subscript 3683 // expressions here, but the result of one is always an lvalue anyway. 3684 } 3685 NamedDecl *dcl = getPrimaryDecl(op); 3686 Expr::isLvalueResult lval = op->isLvalue(Context); 3687 3688 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 3689 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 3690 // FIXME: emit more specific diag... 3691 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 3692 << op->getSourceRange(); 3693 return QualType(); 3694 } 3695 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 3696 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) { 3697 if (Field->isBitField()) { 3698 Diag(OpLoc, diag::err_typecheck_address_of) 3699 << "bit-field" << op->getSourceRange(); 3700 return QualType(); 3701 } 3702 } 3703 // Check for Apple extension for accessing vector components. 3704 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 3705 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 3706 Diag(OpLoc, diag::err_typecheck_address_of) 3707 << "vector element" << op->getSourceRange(); 3708 return QualType(); 3709 } else if (dcl) { // C99 6.5.3.2p1 3710 // We have an lvalue with a decl. Make sure the decl is not declared 3711 // with the register storage-class specifier. 3712 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 3713 if (vd->getStorageClass() == VarDecl::Register) { 3714 Diag(OpLoc, diag::err_typecheck_address_of) 3715 << "register variable" << op->getSourceRange(); 3716 return QualType(); 3717 } 3718 } else if (isa<OverloadedFunctionDecl>(dcl)) { 3719 return Context.OverloadTy; 3720 } else if (isa<FieldDecl>(dcl)) { 3721 // Okay: we can take the address of a field. 3722 // Could be a pointer to member, though, if there is an explicit 3723 // scope qualifier for the class. 3724 if (isa<QualifiedDeclRefExpr>(op)) { 3725 DeclContext *Ctx = dcl->getDeclContext(); 3726 if (Ctx && Ctx->isRecord()) 3727 return Context.getMemberPointerType(op->getType(), 3728 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3729 } 3730 } else if (isa<FunctionDecl>(dcl)) { 3731 // Okay: we can take the address of a function. 3732 // As above. 3733 if (isa<QualifiedDeclRefExpr>(op)) { 3734 DeclContext *Ctx = dcl->getDeclContext(); 3735 if (Ctx && Ctx->isRecord()) 3736 return Context.getMemberPointerType(op->getType(), 3737 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 3738 } 3739 } 3740 else 3741 assert(0 && "Unknown/unexpected decl type"); 3742 } 3743 3744 // If the operand has type "type", the result has type "pointer to type". 3745 return Context.getPointerType(op->getType()); 3746} 3747 3748QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 3749 if (Op->isTypeDependent()) 3750 return Context.DependentTy; 3751 3752 UsualUnaryConversions(Op); 3753 QualType Ty = Op->getType(); 3754 3755 // Note that per both C89 and C99, this is always legal, even if ptype is an 3756 // incomplete type or void. It would be possible to warn about dereferencing 3757 // a void pointer, but it's completely well-defined, and such a warning is 3758 // unlikely to catch any mistakes. 3759 if (const PointerType *PT = Ty->getAsPointerType()) 3760 return PT->getPointeeType(); 3761 3762 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 3763 << Ty << Op->getSourceRange(); 3764 return QualType(); 3765} 3766 3767static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 3768 tok::TokenKind Kind) { 3769 BinaryOperator::Opcode Opc; 3770 switch (Kind) { 3771 default: assert(0 && "Unknown binop!"); 3772 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 3773 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 3774 case tok::star: Opc = BinaryOperator::Mul; break; 3775 case tok::slash: Opc = BinaryOperator::Div; break; 3776 case tok::percent: Opc = BinaryOperator::Rem; break; 3777 case tok::plus: Opc = BinaryOperator::Add; break; 3778 case tok::minus: Opc = BinaryOperator::Sub; break; 3779 case tok::lessless: Opc = BinaryOperator::Shl; break; 3780 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 3781 case tok::lessequal: Opc = BinaryOperator::LE; break; 3782 case tok::less: Opc = BinaryOperator::LT; break; 3783 case tok::greaterequal: Opc = BinaryOperator::GE; break; 3784 case tok::greater: Opc = BinaryOperator::GT; break; 3785 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 3786 case tok::equalequal: Opc = BinaryOperator::EQ; break; 3787 case tok::amp: Opc = BinaryOperator::And; break; 3788 case tok::caret: Opc = BinaryOperator::Xor; break; 3789 case tok::pipe: Opc = BinaryOperator::Or; break; 3790 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 3791 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 3792 case tok::equal: Opc = BinaryOperator::Assign; break; 3793 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 3794 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 3795 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 3796 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 3797 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 3798 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 3799 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 3800 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 3801 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 3802 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 3803 case tok::comma: Opc = BinaryOperator::Comma; break; 3804 } 3805 return Opc; 3806} 3807 3808static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 3809 tok::TokenKind Kind) { 3810 UnaryOperator::Opcode Opc; 3811 switch (Kind) { 3812 default: assert(0 && "Unknown unary op!"); 3813 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 3814 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 3815 case tok::amp: Opc = UnaryOperator::AddrOf; break; 3816 case tok::star: Opc = UnaryOperator::Deref; break; 3817 case tok::plus: Opc = UnaryOperator::Plus; break; 3818 case tok::minus: Opc = UnaryOperator::Minus; break; 3819 case tok::tilde: Opc = UnaryOperator::Not; break; 3820 case tok::exclaim: Opc = UnaryOperator::LNot; break; 3821 case tok::kw___real: Opc = UnaryOperator::Real; break; 3822 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 3823 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 3824 } 3825 return Opc; 3826} 3827 3828/// CreateBuiltinBinOp - Creates a new built-in binary operation with 3829/// operator @p Opc at location @c TokLoc. This routine only supports 3830/// built-in operations; ActOnBinOp handles overloaded operators. 3831Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 3832 unsigned Op, 3833 Expr *lhs, Expr *rhs) { 3834 QualType ResultTy; // Result type of the binary operator. 3835 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 3836 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 3837 3838 switch (Opc) { 3839 default: 3840 assert(0 && "Unknown binary expr!"); 3841 case BinaryOperator::Assign: 3842 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 3843 break; 3844 case BinaryOperator::PtrMemD: 3845 case BinaryOperator::PtrMemI: 3846 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 3847 Opc == BinaryOperator::PtrMemI); 3848 break; 3849 case BinaryOperator::Mul: 3850 case BinaryOperator::Div: 3851 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 3852 break; 3853 case BinaryOperator::Rem: 3854 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 3855 break; 3856 case BinaryOperator::Add: 3857 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 3858 break; 3859 case BinaryOperator::Sub: 3860 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 3861 break; 3862 case BinaryOperator::Shl: 3863 case BinaryOperator::Shr: 3864 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 3865 break; 3866 case BinaryOperator::LE: 3867 case BinaryOperator::LT: 3868 case BinaryOperator::GE: 3869 case BinaryOperator::GT: 3870 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true); 3871 break; 3872 case BinaryOperator::EQ: 3873 case BinaryOperator::NE: 3874 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false); 3875 break; 3876 case BinaryOperator::And: 3877 case BinaryOperator::Xor: 3878 case BinaryOperator::Or: 3879 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 3880 break; 3881 case BinaryOperator::LAnd: 3882 case BinaryOperator::LOr: 3883 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 3884 break; 3885 case BinaryOperator::MulAssign: 3886 case BinaryOperator::DivAssign: 3887 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 3888 if (!CompTy.isNull()) 3889 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3890 break; 3891 case BinaryOperator::RemAssign: 3892 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 3893 if (!CompTy.isNull()) 3894 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3895 break; 3896 case BinaryOperator::AddAssign: 3897 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true); 3898 if (!CompTy.isNull()) 3899 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3900 break; 3901 case BinaryOperator::SubAssign: 3902 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true); 3903 if (!CompTy.isNull()) 3904 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3905 break; 3906 case BinaryOperator::ShlAssign: 3907 case BinaryOperator::ShrAssign: 3908 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 3909 if (!CompTy.isNull()) 3910 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3911 break; 3912 case BinaryOperator::AndAssign: 3913 case BinaryOperator::XorAssign: 3914 case BinaryOperator::OrAssign: 3915 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 3916 if (!CompTy.isNull()) 3917 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 3918 break; 3919 case BinaryOperator::Comma: 3920 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 3921 break; 3922 } 3923 if (ResultTy.isNull()) 3924 return ExprError(); 3925 if (CompTy.isNull()) 3926 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 3927 else 3928 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 3929 CompTy, OpLoc)); 3930} 3931 3932// Binary Operators. 'Tok' is the token for the operator. 3933Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 3934 tok::TokenKind Kind, 3935 ExprArg LHS, ExprArg RHS) { 3936 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 3937 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release(); 3938 3939 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 3940 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 3941 3942 // If either expression is type-dependent, just build the AST. 3943 // FIXME: We'll need to perform some caching of the result of name 3944 // lookup for operator+. 3945 if (lhs->isTypeDependent() || rhs->isTypeDependent()) { 3946 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) 3947 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, 3948 Context.DependentTy, 3949 Context.DependentTy, TokLoc)); 3950 else 3951 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, 3952 Context.DependentTy, TokLoc)); 3953 } 3954 3955 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD && 3956 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() || 3957 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) { 3958 // If this is one of the assignment operators, we only perform 3959 // overload resolution if the left-hand side is a class or 3960 // enumeration type (C++ [expr.ass]p3). 3961 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign && 3962 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) { 3963 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 3964 } 3965 3966 // Determine which overloaded operator we're dealing with. 3967 static const OverloadedOperatorKind OverOps[] = { 3968 // Overloading .* is not possible. 3969 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar, 3970 OO_Star, OO_Slash, OO_Percent, 3971 OO_Plus, OO_Minus, 3972 OO_LessLess, OO_GreaterGreater, 3973 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 3974 OO_EqualEqual, OO_ExclaimEqual, 3975 OO_Amp, 3976 OO_Caret, 3977 OO_Pipe, 3978 OO_AmpAmp, 3979 OO_PipePipe, 3980 OO_Equal, OO_StarEqual, 3981 OO_SlashEqual, OO_PercentEqual, 3982 OO_PlusEqual, OO_MinusEqual, 3983 OO_LessLessEqual, OO_GreaterGreaterEqual, 3984 OO_AmpEqual, OO_CaretEqual, 3985 OO_PipeEqual, 3986 OO_Comma 3987 }; 3988 OverloadedOperatorKind OverOp = OverOps[Opc]; 3989 3990 // Add the appropriate overloaded operators (C++ [over.match.oper]) 3991 // to the candidate set. 3992 OverloadCandidateSet CandidateSet; 3993 Expr *Args[2] = { lhs, rhs }; 3994 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet)) 3995 return ExprError(); 3996 3997 // Perform overload resolution. 3998 OverloadCandidateSet::iterator Best; 3999 switch (BestViableFunction(CandidateSet, Best)) { 4000 case OR_Success: { 4001 // We found a built-in operator or an overloaded operator. 4002 FunctionDecl *FnDecl = Best->Function; 4003 4004 if (FnDecl) { 4005 // We matched an overloaded operator. Build a call to that 4006 // operator. 4007 4008 // Convert the arguments. 4009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4010 if (PerformObjectArgumentInitialization(lhs, Method) || 4011 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(), 4012 "passing")) 4013 return ExprError(); 4014 } else { 4015 // Convert the arguments. 4016 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(), 4017 "passing") || 4018 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(), 4019 "passing")) 4020 return ExprError(); 4021 } 4022 4023 // Determine the result type 4024 QualType ResultTy 4025 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4026 ResultTy = ResultTy.getNonReferenceType(); 4027 4028 // Build the actual expression node. 4029 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4030 SourceLocation()); 4031 UsualUnaryConversions(FnExpr); 4032 4033 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2, 4034 ResultTy, TokLoc)); 4035 } else { 4036 // We matched a built-in operator. Convert the arguments, then 4037 // break out so that we will build the appropriate built-in 4038 // operator node. 4039 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0], 4040 Best->Conversions[0], "passing") || 4041 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1], 4042 Best->Conversions[1], "passing")) 4043 return ExprError(); 4044 4045 break; 4046 } 4047 } 4048 4049 case OR_No_Viable_Function: 4050 // No viable function; fall through to handling this as a 4051 // built-in operator, which will produce an error message for us. 4052 break; 4053 4054 case OR_Ambiguous: 4055 Diag(TokLoc, diag::err_ovl_ambiguous_oper) 4056 << BinaryOperator::getOpcodeStr(Opc) 4057 << lhs->getSourceRange() << rhs->getSourceRange(); 4058 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4059 return ExprError(); 4060 4061 case OR_Deleted: 4062 Diag(TokLoc, diag::err_ovl_deleted_oper) 4063 << Best->Function->isDeleted() 4064 << BinaryOperator::getOpcodeStr(Opc) 4065 << lhs->getSourceRange() << rhs->getSourceRange(); 4066 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4067 return ExprError(); 4068 } 4069 4070 // Either we found no viable overloaded operator or we matched a 4071 // built-in operator. In either case, fall through to trying to 4072 // build a built-in operation. 4073 } 4074 4075 // Build a built-in binary operation. 4076 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 4077} 4078 4079// Unary Operators. 'Tok' is the token for the operator. 4080Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 4081 tok::TokenKind Op, ExprArg input) { 4082 // FIXME: Input is modified later, but smart pointer not reassigned. 4083 Expr *Input = (Expr*)input.get(); 4084 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 4085 4086 if (getLangOptions().CPlusPlus && 4087 (Input->getType()->isRecordType() 4088 || Input->getType()->isEnumeralType())) { 4089 // Determine which overloaded operator we're dealing with. 4090 static const OverloadedOperatorKind OverOps[] = { 4091 OO_None, OO_None, 4092 OO_PlusPlus, OO_MinusMinus, 4093 OO_Amp, OO_Star, 4094 OO_Plus, OO_Minus, 4095 OO_Tilde, OO_Exclaim, 4096 OO_None, OO_None, 4097 OO_None, 4098 OO_None 4099 }; 4100 OverloadedOperatorKind OverOp = OverOps[Opc]; 4101 4102 // Add the appropriate overloaded operators (C++ [over.match.oper]) 4103 // to the candidate set. 4104 OverloadCandidateSet CandidateSet; 4105 if (OverOp != OO_None && 4106 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet)) 4107 return ExprError(); 4108 4109 // Perform overload resolution. 4110 OverloadCandidateSet::iterator Best; 4111 switch (BestViableFunction(CandidateSet, Best)) { 4112 case OR_Success: { 4113 // We found a built-in operator or an overloaded operator. 4114 FunctionDecl *FnDecl = Best->Function; 4115 4116 if (FnDecl) { 4117 // We matched an overloaded operator. Build a call to that 4118 // operator. 4119 4120 // Convert the arguments. 4121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4122 if (PerformObjectArgumentInitialization(Input, Method)) 4123 return ExprError(); 4124 } else { 4125 // Convert the arguments. 4126 if (PerformCopyInitialization(Input, 4127 FnDecl->getParamDecl(0)->getType(), 4128 "passing")) 4129 return ExprError(); 4130 } 4131 4132 // Determine the result type 4133 QualType ResultTy 4134 = FnDecl->getType()->getAsFunctionType()->getResultType(); 4135 ResultTy = ResultTy.getNonReferenceType(); 4136 4137 // Build the actual expression node. 4138 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4139 SourceLocation()); 4140 UsualUnaryConversions(FnExpr); 4141 4142 input.release(); 4143 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 4144 1, ResultTy, OpLoc)); 4145 } else { 4146 // We matched a built-in operator. Convert the arguments, then 4147 // break out so that we will build the appropriate built-in 4148 // operator node. 4149 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 4150 Best->Conversions[0], "passing")) 4151 return ExprError(); 4152 4153 break; 4154 } 4155 } 4156 4157 case OR_No_Viable_Function: 4158 // No viable function; fall through to handling this as a 4159 // built-in operator, which will produce an error message for us. 4160 break; 4161 4162 case OR_Ambiguous: 4163 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 4164 << UnaryOperator::getOpcodeStr(Opc) 4165 << Input->getSourceRange(); 4166 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4167 return ExprError(); 4168 4169 case OR_Deleted: 4170 Diag(OpLoc, diag::err_ovl_deleted_oper) 4171 << Best->Function->isDeleted() 4172 << UnaryOperator::getOpcodeStr(Opc) 4173 << Input->getSourceRange(); 4174 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4175 return ExprError(); 4176 } 4177 4178 // Either we found no viable overloaded operator or we matched a 4179 // built-in operator. In either case, fall through to trying to 4180 // build a built-in operation. 4181 } 4182 4183 QualType resultType; 4184 switch (Opc) { 4185 default: 4186 assert(0 && "Unimplemented unary expr!"); 4187 case UnaryOperator::PreInc: 4188 case UnaryOperator::PreDec: 4189 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 4190 Opc == UnaryOperator::PreInc); 4191 break; 4192 case UnaryOperator::AddrOf: 4193 resultType = CheckAddressOfOperand(Input, OpLoc); 4194 break; 4195 case UnaryOperator::Deref: 4196 DefaultFunctionArrayConversion(Input); 4197 resultType = CheckIndirectionOperand(Input, OpLoc); 4198 break; 4199 case UnaryOperator::Plus: 4200 case UnaryOperator::Minus: 4201 UsualUnaryConversions(Input); 4202 resultType = Input->getType(); 4203 if (resultType->isDependentType()) 4204 break; 4205 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 4206 break; 4207 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 4208 resultType->isEnumeralType()) 4209 break; 4210 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 4211 Opc == UnaryOperator::Plus && 4212 resultType->isPointerType()) 4213 break; 4214 4215 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4216 << resultType << Input->getSourceRange()); 4217 case UnaryOperator::Not: // bitwise complement 4218 UsualUnaryConversions(Input); 4219 resultType = Input->getType(); 4220 if (resultType->isDependentType()) 4221 break; 4222 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 4223 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 4224 // C99 does not support '~' for complex conjugation. 4225 Diag(OpLoc, diag::ext_integer_complement_complex) 4226 << resultType << Input->getSourceRange(); 4227 else if (!resultType->isIntegerType()) 4228 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4229 << resultType << Input->getSourceRange()); 4230 break; 4231 case UnaryOperator::LNot: // logical negation 4232 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 4233 DefaultFunctionArrayConversion(Input); 4234 resultType = Input->getType(); 4235 if (resultType->isDependentType()) 4236 break; 4237 if (!resultType->isScalarType()) // C99 6.5.3.3p1 4238 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 4239 << resultType << Input->getSourceRange()); 4240 // LNot always has type int. C99 6.5.3.3p5. 4241 // In C++, it's bool. C++ 5.3.1p8 4242 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 4243 break; 4244 case UnaryOperator::Real: 4245 case UnaryOperator::Imag: 4246 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 4247 break; 4248 case UnaryOperator::Extension: 4249 resultType = Input->getType(); 4250 break; 4251 } 4252 if (resultType.isNull()) 4253 return ExprError(); 4254 input.release(); 4255 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 4256} 4257 4258/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 4259Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 4260 SourceLocation LabLoc, 4261 IdentifierInfo *LabelII) { 4262 // Look up the record for this label identifier. 4263 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I = 4264 ActiveScope->LabelMap.find(LabelII); 4265 4266 LabelStmt *LabelDecl; 4267 4268 // If we haven't seen this label yet, create a forward reference. It 4269 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 4270 if (I == ActiveScope->LabelMap.end()) { 4271 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 4272 4273 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl)); 4274 } else 4275 LabelDecl = static_cast<LabelStmt *>(I->second); 4276 4277 // Create the AST node. The address of a label always has type 'void*'. 4278 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 4279 Context.getPointerType(Context.VoidTy)); 4280} 4281 4282Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 4283 SourceLocation RPLoc) { // "({..})" 4284 Stmt *SubStmt = static_cast<Stmt*>(substmt); 4285 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 4286 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 4287 4288 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4289 if (isFileScope) { 4290 return Diag(LPLoc, diag::err_stmtexpr_file_scope); 4291 } 4292 4293 // FIXME: there are a variety of strange constraints to enforce here, for 4294 // example, it is not possible to goto into a stmt expression apparently. 4295 // More semantic analysis is needed. 4296 4297 // FIXME: the last statement in the compount stmt has its value used. We 4298 // should not warn about it being unused. 4299 4300 // If there are sub stmts in the compound stmt, take the type of the last one 4301 // as the type of the stmtexpr. 4302 QualType Ty = Context.VoidTy; 4303 4304 if (!Compound->body_empty()) { 4305 Stmt *LastStmt = Compound->body_back(); 4306 // If LastStmt is a label, skip down through into the body. 4307 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 4308 LastStmt = Label->getSubStmt(); 4309 4310 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 4311 Ty = LastExpr->getType(); 4312 } 4313 4314 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 4315} 4316 4317Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 4318 SourceLocation BuiltinLoc, 4319 SourceLocation TypeLoc, 4320 TypeTy *argty, 4321 OffsetOfComponent *CompPtr, 4322 unsigned NumComponents, 4323 SourceLocation RPLoc) { 4324 QualType ArgTy = QualType::getFromOpaquePtr(argty); 4325 assert(!ArgTy.isNull() && "Missing type argument!"); 4326 4327 bool Dependent = ArgTy->isDependentType(); 4328 4329 // We must have at least one component that refers to the type, and the first 4330 // one is known to be a field designator. Verify that the ArgTy represents 4331 // a struct/union/class. 4332 if (!Dependent && !ArgTy->isRecordType()) 4333 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy; 4334 4335 // Otherwise, create a null pointer as the base, and iteratively process 4336 // the offsetof designators. 4337 QualType ArgTyPtr = Context.getPointerType(ArgTy); 4338 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 4339 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 4340 ArgTy, SourceLocation()); 4341 4342 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 4343 // GCC extension, diagnose them. 4344 // FIXME: This diagnostic isn't actually visible because the location is in 4345 // a system header! 4346 if (NumComponents != 1) 4347 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 4348 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 4349 4350 if (!Dependent) { 4351 // FIXME: Dependent case loses a lot of information here. And probably 4352 // leaks like a sieve. 4353 for (unsigned i = 0; i != NumComponents; ++i) { 4354 const OffsetOfComponent &OC = CompPtr[i]; 4355 if (OC.isBrackets) { 4356 // Offset of an array sub-field. TODO: Should we allow vector elements? 4357 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 4358 if (!AT) { 4359 Res->Destroy(Context); 4360 return Diag(OC.LocEnd, diag::err_offsetof_array_type) 4361 << Res->getType(); 4362 } 4363 4364 // FIXME: C++: Verify that operator[] isn't overloaded. 4365 4366 // Promote the array so it looks more like a normal array subscript 4367 // expression. 4368 DefaultFunctionArrayConversion(Res); 4369 4370 // C99 6.5.2.1p1 4371 Expr *Idx = static_cast<Expr*>(OC.U.E); 4372 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 4373 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript) 4374 << Idx->getSourceRange(); 4375 4376 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 4377 OC.LocEnd); 4378 continue; 4379 } 4380 4381 const RecordType *RC = Res->getType()->getAsRecordType(); 4382 if (!RC) { 4383 Res->Destroy(Context); 4384 return Diag(OC.LocEnd, diag::err_offsetof_record_type) 4385 << Res->getType(); 4386 } 4387 4388 // Get the decl corresponding to this. 4389 RecordDecl *RD = RC->getDecl(); 4390 FieldDecl *MemberDecl 4391 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, 4392 LookupMemberName) 4393 .getAsDecl()); 4394 if (!MemberDecl) 4395 return Diag(BuiltinLoc, diag::err_typecheck_no_member) 4396 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd); 4397 4398 // FIXME: C++: Verify that MemberDecl isn't a static field. 4399 // FIXME: Verify that MemberDecl isn't a bitfield. 4400 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 4401 // matter here. 4402 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 4403 MemberDecl->getType().getNonReferenceType()); 4404 } 4405 } 4406 4407 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 4408 Context.getSizeType(), BuiltinLoc); 4409} 4410 4411 4412Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 4413 TypeTy *arg1, TypeTy *arg2, 4414 SourceLocation RPLoc) { 4415 QualType argT1 = QualType::getFromOpaquePtr(arg1); 4416 QualType argT2 = QualType::getFromOpaquePtr(arg2); 4417 4418 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 4419 4420 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, 4421 argT2, RPLoc); 4422} 4423 4424Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 4425 ExprTy *expr1, ExprTy *expr2, 4426 SourceLocation RPLoc) { 4427 Expr *CondExpr = static_cast<Expr*>(cond); 4428 Expr *LHSExpr = static_cast<Expr*>(expr1); 4429 Expr *RHSExpr = static_cast<Expr*>(expr2); 4430 4431 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 4432 4433 QualType resType; 4434 if (CondExpr->isValueDependent()) { 4435 resType = Context.DependentTy; 4436 } else { 4437 // The conditional expression is required to be a constant expression. 4438 llvm::APSInt condEval(32); 4439 SourceLocation ExpLoc; 4440 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 4441 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) 4442 << CondExpr->getSourceRange(); 4443 4444 // If the condition is > zero, then the AST type is the same as the LSHExpr. 4445 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 4446 } 4447 4448 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 4449 resType, RPLoc); 4450} 4451 4452//===----------------------------------------------------------------------===// 4453// Clang Extensions. 4454//===----------------------------------------------------------------------===// 4455 4456/// ActOnBlockStart - This callback is invoked when a block literal is started. 4457void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 4458 // Analyze block parameters. 4459 BlockSemaInfo *BSI = new BlockSemaInfo(); 4460 4461 // Add BSI to CurBlock. 4462 BSI->PrevBlockInfo = CurBlock; 4463 CurBlock = BSI; 4464 ActiveScope = BlockScope; 4465 4466 BSI->ReturnType = 0; 4467 BSI->TheScope = BlockScope; 4468 BSI->hasBlockDeclRefExprs = false; 4469 4470 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 4471 PushDeclContext(BlockScope, BSI->TheDecl); 4472} 4473 4474void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 4475 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!"); 4476 4477 if (ParamInfo.getNumTypeObjects() == 0 4478 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 4479 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 4480 4481 // The type is entirely optional as well, if none, use DependentTy. 4482 if (T.isNull()) 4483 T = Context.DependentTy; 4484 4485 // The parameter list is optional, if there was none, assume (). 4486 if (!T->isFunctionType()) 4487 T = Context.getFunctionType(T, NULL, 0, 0, 0); 4488 4489 CurBlock->hasPrototype = true; 4490 CurBlock->isVariadic = false; 4491 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4492 .getTypePtr(); 4493 4494 if (!RetTy->isDependentType()) 4495 CurBlock->ReturnType = RetTy; 4496 return; 4497 } 4498 4499 // Analyze arguments to block. 4500 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 4501 "Not a function declarator!"); 4502 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 4503 4504 CurBlock->hasPrototype = FTI.hasPrototype; 4505 CurBlock->isVariadic = true; 4506 4507 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 4508 // no arguments, not a function that takes a single void argument. 4509 if (FTI.hasPrototype && 4510 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4511 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 4512 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 4513 // empty arg list, don't push any params. 4514 CurBlock->isVariadic = false; 4515 } else if (FTI.hasPrototype) { 4516 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 4517 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 4518 CurBlock->isVariadic = FTI.isVariadic; 4519 QualType T = GetTypeForDeclarator (ParamInfo, CurScope); 4520 4521 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType() 4522 .getTypePtr(); 4523 4524 if (!RetTy->isDependentType()) 4525 CurBlock->ReturnType = RetTy; 4526 } 4527 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size()); 4528 4529 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 4530 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 4531 // If this has an identifier, add it to the scope stack. 4532 if ((*AI)->getIdentifier()) 4533 PushOnScopeChains(*AI, CurBlock->TheScope); 4534} 4535 4536/// ActOnBlockError - If there is an error parsing a block, this callback 4537/// is invoked to pop the information about the block from the action impl. 4538void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 4539 // Ensure that CurBlock is deleted. 4540 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 4541 4542 // Pop off CurBlock, handle nested blocks. 4543 CurBlock = CurBlock->PrevBlockInfo; 4544 4545 // FIXME: Delete the ParmVarDecl objects as well??? 4546 4547} 4548 4549/// ActOnBlockStmtExpr - This is called when the body of a block statement 4550/// literal was successfully completed. ^(int x){...} 4551Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 4552 Scope *CurScope) { 4553 // Ensure that CurBlock is deleted. 4554 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 4555 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body)); 4556 4557 PopDeclContext(); 4558 4559 // Before poping CurBlock, set ActiveScope to this scopes parent. 4560 ActiveScope = CurBlock->TheScope->getParent(); 4561 4562 // Pop off CurBlock, handle nested blocks. 4563 CurBlock = CurBlock->PrevBlockInfo; 4564 4565 QualType RetTy = Context.VoidTy; 4566 if (BSI->ReturnType) 4567 RetTy = QualType(BSI->ReturnType, 0); 4568 4569 llvm::SmallVector<QualType, 8> ArgTypes; 4570 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 4571 ArgTypes.push_back(BSI->Params[i]->getType()); 4572 4573 QualType BlockTy; 4574 if (!BSI->hasPrototype) 4575 BlockTy = Context.getFunctionNoProtoType(RetTy); 4576 else 4577 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 4578 BSI->isVariadic, 0); 4579 4580 BlockTy = Context.getBlockPointerType(BlockTy); 4581 4582 BSI->TheDecl->setBody(Body.take()); 4583 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs); 4584} 4585 4586Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 4587 ExprTy *expr, TypeTy *type, 4588 SourceLocation RPLoc) { 4589 Expr *E = static_cast<Expr*>(expr); 4590 QualType T = QualType::getFromOpaquePtr(type); 4591 4592 InitBuiltinVaListType(); 4593 4594 // Get the va_list type 4595 QualType VaListType = Context.getBuiltinVaListType(); 4596 // Deal with implicit array decay; for example, on x86-64, 4597 // va_list is an array, but it's supposed to decay to 4598 // a pointer for va_arg. 4599 if (VaListType->isArrayType()) 4600 VaListType = Context.getArrayDecayedType(VaListType); 4601 // Make sure the input expression also decays appropriately. 4602 UsualUnaryConversions(E); 4603 4604 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 4605 return Diag(E->getLocStart(), 4606 diag::err_first_argument_to_va_arg_not_of_type_va_list) 4607 << E->getType() << E->getSourceRange(); 4608 4609 // FIXME: Warn if a non-POD type is passed in. 4610 4611 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc); 4612} 4613 4614Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 4615 // The type of __null will be int or long, depending on the size of 4616 // pointers on the target. 4617 QualType Ty; 4618 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 4619 Ty = Context.IntTy; 4620 else 4621 Ty = Context.LongTy; 4622 4623 return new (Context) GNUNullExpr(Ty, TokenLoc); 4624} 4625 4626bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 4627 SourceLocation Loc, 4628 QualType DstType, QualType SrcType, 4629 Expr *SrcExpr, const char *Flavor) { 4630 // Decode the result (notice that AST's are still created for extensions). 4631 bool isInvalid = false; 4632 unsigned DiagKind; 4633 switch (ConvTy) { 4634 default: assert(0 && "Unknown conversion type"); 4635 case Compatible: return false; 4636 case PointerToInt: 4637 DiagKind = diag::ext_typecheck_convert_pointer_int; 4638 break; 4639 case IntToPointer: 4640 DiagKind = diag::ext_typecheck_convert_int_pointer; 4641 break; 4642 case IncompatiblePointer: 4643 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 4644 break; 4645 case FunctionVoidPointer: 4646 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 4647 break; 4648 case CompatiblePointerDiscardsQualifiers: 4649 // If the qualifiers lost were because we were applying the 4650 // (deprecated) C++ conversion from a string literal to a char* 4651 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 4652 // Ideally, this check would be performed in 4653 // CheckPointerTypesForAssignment. However, that would require a 4654 // bit of refactoring (so that the second argument is an 4655 // expression, rather than a type), which should be done as part 4656 // of a larger effort to fix CheckPointerTypesForAssignment for 4657 // C++ semantics. 4658 if (getLangOptions().CPlusPlus && 4659 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 4660 return false; 4661 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 4662 break; 4663 case IntToBlockPointer: 4664 DiagKind = diag::err_int_to_block_pointer; 4665 break; 4666 case IncompatibleBlockPointer: 4667 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 4668 break; 4669 case IncompatibleObjCQualifiedId: 4670 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 4671 // it can give a more specific diagnostic. 4672 DiagKind = diag::warn_incompatible_qualified_id; 4673 break; 4674 case IncompatibleVectors: 4675 DiagKind = diag::warn_incompatible_vectors; 4676 break; 4677 case Incompatible: 4678 DiagKind = diag::err_typecheck_convert_incompatible; 4679 isInvalid = true; 4680 break; 4681 } 4682 4683 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 4684 << SrcExpr->getSourceRange(); 4685 return isInvalid; 4686} 4687 4688bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result) 4689{ 4690 Expr::EvalResult EvalResult; 4691 4692 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 4693 EvalResult.HasSideEffects) { 4694 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 4695 4696 if (EvalResult.Diag) { 4697 // We only show the note if it's not the usual "invalid subexpression" 4698 // or if it's actually in a subexpression. 4699 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 4700 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 4701 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4702 } 4703 4704 return true; 4705 } 4706 4707 if (EvalResult.Diag) { 4708 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 4709 E->getSourceRange(); 4710 4711 // Print the reason it's not a constant. 4712 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 4713 Diag(EvalResult.DiagLoc, EvalResult.Diag); 4714 } 4715 4716 if (Result) 4717 *Result = EvalResult.Val.getInt(); 4718 return false; 4719} 4720