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