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