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