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