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