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