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