SemaExpr.cpp revision 080b332959f0a1886c8d0a515f656fe6215a9ce3
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 "SemaUtil.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/Parse/DeclSpec.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Lex/LiteralSupport.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Basic/TargetInfo.h" 26#include "llvm/ADT/OwningPtr.h" 27#include "llvm/ADT/SmallString.h" 28#include "llvm/ADT/StringExtras.h" 29using namespace clang; 30 31/// ActOnStringLiteral - The specified tokens were lexed as pasted string 32/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 34/// multiple tokens. However, the common case is that StringToks points to one 35/// string. 36/// 37Action::ExprResult 38Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 39 assert(NumStringToks && "Must have at least one string!"); 40 41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target); 42 if (Literal.hadError) 43 return ExprResult(true); 44 45 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 46 for (unsigned i = 0; i != NumStringToks; ++i) 47 StringTokLocs.push_back(StringToks[i].getLocation()); 48 49 // Verify that pascal strings aren't too large. 50 if (Literal.Pascal && Literal.GetStringLength() > 256) 51 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long, 52 SourceRange(StringToks[0].getLocation(), 53 StringToks[NumStringToks-1].getLocation())); 54 55 QualType StrTy = Context.CharTy; 56 if (Literal.AnyWide) StrTy = Context.getWcharType(); 57 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 58 59 // Get an array type for the string, according to C99 6.4.5. This includes 60 // the nul terminator character as well as the string length for pascal 61 // strings. 62 StrTy = Context.getConstantArrayType(StrTy, 63 llvm::APInt(32, Literal.GetStringLength()+1), 64 ArrayType::Normal, 0); 65 66 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 67 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 68 Literal.AnyWide, StrTy, 69 StringToks[0].getLocation(), 70 StringToks[NumStringToks-1].getLocation()); 71} 72 73 74/// ActOnIdentifierExpr - The parser read an identifier in expression context, 75/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 76/// identifier is used in a function call context. 77Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 78 IdentifierInfo &II, 79 bool HasTrailingLParen) { 80 // Could be enum-constant, value decl, instance variable, etc. 81 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S); 82 83 // If this reference is in an Objective-C method, then ivar lookup happens as 84 // well. 85 if (getCurMethodDecl()) { 86 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D); 87 // There are two cases to handle here. 1) scoped lookup could have failed, 88 // in which case we should look for an ivar. 2) scoped lookup could have 89 // found a decl, but that decl is outside the current method (i.e. a global 90 // variable). In these two cases, we do a lookup for an ivar with this 91 // name, if the lookup suceeds, we replace it our current decl. 92 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) { 93 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 94 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) { 95 // FIXME: This should use a new expr for a direct reference, don't turn 96 // this into Self->ivar, just return a BareIVarExpr or something. 97 IdentifierInfo &II = Context.Idents.get("self"); 98 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 99 return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 100 static_cast<Expr*>(SelfExpr.Val), true, true); 101 } 102 } 103 if (SD == 0 && !strcmp(II.getName(), "super")) { 104 QualType T = Context.getPointerType(Context.getObjCInterfaceType( 105 getCurMethodDecl()->getClassInterface())); 106 return new ObjCSuperRefExpr(T, Loc); 107 } 108 } 109 110 if (D == 0) { 111 // Otherwise, this could be an implicitly declared function reference (legal 112 // in C90, extension in C99). 113 if (HasTrailingLParen && 114 !getLangOptions().CPlusPlus) // Not in C++. 115 D = ImplicitlyDefineFunction(Loc, II, S); 116 else { 117 // If this name wasn't predeclared and if this is not a function call, 118 // diagnose the problem. 119 return Diag(Loc, diag::err_undeclared_var_use, II.getName()); 120 } 121 } 122 123 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 124 // check if referencing an identifier with __attribute__((deprecated)). 125 if (VD->getAttr<DeprecatedAttr>()) 126 Diag(Loc, diag::warn_deprecated, VD->getName()); 127 128 // Only create DeclRefExpr's for valid Decl's. 129 if (VD->isInvalidDecl()) 130 return true; 131 return new DeclRefExpr(VD, VD->getType(), Loc); 132 } 133 134 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) { 135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 136 if (MD->isStatic()) 137 // "invalid use of member 'x' in static member function" 138 return Diag(Loc, diag::err_invalid_member_use_in_static_method, 139 FD->getName()); 140 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent()) 141 // "invalid use of nonstatic data member 'x'" 142 return Diag(Loc, diag::err_invalid_non_static_member_use, 143 FD->getName()); 144 145 if (FD->isInvalidDecl()) 146 return true; 147 148 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference. 149 ExprResult ThisExpr = ActOnCXXThis(SourceLocation()); 150 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val), 151 true, FD, Loc, FD->getType()); 152 } 153 154 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName()); 155 } 156 157 if (isa<TypedefDecl>(D)) 158 return Diag(Loc, diag::err_unexpected_typedef, II.getName()); 159 if (isa<ObjCInterfaceDecl>(D)) 160 return Diag(Loc, diag::err_unexpected_interface, II.getName()); 161 if (isa<NamespaceDecl>(D)) 162 return Diag(Loc, diag::err_unexpected_namespace, II.getName()); 163 164 assert(0 && "Invalid decl"); 165 abort(); 166} 167 168Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc, 169 tok::TokenKind Kind) { 170 PreDefinedExpr::IdentType IT; 171 172 switch (Kind) { 173 default: assert(0 && "Unknown simple primary expr!"); 174 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2] 175 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break; 176 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break; 177 } 178 179 // Verify that this is in a function context. 180 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0) 181 return Diag(Loc, diag::err_predef_outside_function); 182 183 // Pre-defined identifiers are of type char[x], where x is the length of the 184 // string. 185 unsigned Length; 186 if (getCurFunctionDecl()) 187 Length = getCurFunctionDecl()->getIdentifier()->getLength(); 188 else 189 Length = getCurMethodDecl()->getSynthesizedMethodSize(); 190 191 llvm::APInt LengthI(32, Length + 1); 192 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 193 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 194 return new PreDefinedExpr(Loc, ResTy, IT); 195} 196 197Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 198 llvm::SmallString<16> CharBuffer; 199 CharBuffer.resize(Tok.getLength()); 200 const char *ThisTokBegin = &CharBuffer[0]; 201 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 202 203 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 204 Tok.getLocation(), PP); 205 if (Literal.hadError()) 206 return ExprResult(true); 207 208 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 209 210 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type, 211 Tok.getLocation()); 212} 213 214Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 215 // fast path for a single digit (which is quite common). A single digit 216 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 217 if (Tok.getLength() == 1) { 218 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation()); 219 220 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy)); 221 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'), 222 Context.IntTy, 223 Tok.getLocation())); 224 } 225 llvm::SmallString<512> IntegerBuffer; 226 IntegerBuffer.resize(Tok.getLength()); 227 const char *ThisTokBegin = &IntegerBuffer[0]; 228 229 // Get the spelling of the token, which eliminates trigraphs, etc. 230 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 231 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 232 Tok.getLocation(), PP); 233 if (Literal.hadError) 234 return ExprResult(true); 235 236 Expr *Res; 237 238 if (Literal.isFloatingLiteral()) { 239 QualType Ty; 240 if (Literal.isFloat) 241 Ty = Context.FloatTy; 242 else if (!Literal.isLong) 243 Ty = Context.DoubleTy; 244 else 245 Ty = Context.LongDoubleTy; 246 247 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 248 249 // isExact will be set by GetFloatValue(). 250 bool isExact = false; 251 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, 252 Ty, Tok.getLocation()); 253 254 } else if (!Literal.isIntegerLiteral()) { 255 return ExprResult(true); 256 } else { 257 QualType Ty; 258 259 // long long is a C99 feature. 260 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 261 Literal.isLongLong) 262 Diag(Tok.getLocation(), diag::ext_longlong); 263 264 // Get the value in the widest-possible width. 265 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 266 267 if (Literal.GetIntegerValue(ResultVal)) { 268 // If this value didn't fit into uintmax_t, warn and force to ull. 269 Diag(Tok.getLocation(), diag::warn_integer_too_large); 270 Ty = Context.UnsignedLongLongTy; 271 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 272 "long long is not intmax_t?"); 273 } else { 274 // If this value fits into a ULL, try to figure out what else it fits into 275 // according to the rules of C99 6.4.4.1p5. 276 277 // Octal, Hexadecimal, and integers with a U suffix are allowed to 278 // be an unsigned int. 279 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 280 281 // Check from smallest to largest, picking the smallest type we can. 282 unsigned Width = 0; 283 if (!Literal.isLong && !Literal.isLongLong) { 284 // Are int/unsigned possibilities? 285 unsigned IntSize = Context.Target.getIntWidth(); 286 287 // Does it fit in a unsigned int? 288 if (ResultVal.isIntN(IntSize)) { 289 // Does it fit in a signed int? 290 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 291 Ty = Context.IntTy; 292 else if (AllowUnsigned) 293 Ty = Context.UnsignedIntTy; 294 Width = IntSize; 295 } 296 } 297 298 // Are long/unsigned long possibilities? 299 if (Ty.isNull() && !Literal.isLongLong) { 300 unsigned LongSize = Context.Target.getLongWidth(); 301 302 // Does it fit in a unsigned long? 303 if (ResultVal.isIntN(LongSize)) { 304 // Does it fit in a signed long? 305 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 306 Ty = Context.LongTy; 307 else if (AllowUnsigned) 308 Ty = Context.UnsignedLongTy; 309 Width = LongSize; 310 } 311 } 312 313 // Finally, check long long if needed. 314 if (Ty.isNull()) { 315 unsigned LongLongSize = Context.Target.getLongLongWidth(); 316 317 // Does it fit in a unsigned long long? 318 if (ResultVal.isIntN(LongLongSize)) { 319 // Does it fit in a signed long long? 320 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 321 Ty = Context.LongLongTy; 322 else if (AllowUnsigned) 323 Ty = Context.UnsignedLongLongTy; 324 Width = LongLongSize; 325 } 326 } 327 328 // If we still couldn't decide a type, we probably have something that 329 // does not fit in a signed long long, but has no U suffix. 330 if (Ty.isNull()) { 331 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 332 Ty = Context.UnsignedLongLongTy; 333 Width = Context.Target.getLongLongWidth(); 334 } 335 336 if (ResultVal.getBitWidth() != Width) 337 ResultVal.trunc(Width); 338 } 339 340 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 341 } 342 343 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 344 if (Literal.isImaginary) 345 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); 346 347 return Res; 348} 349 350Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, 351 ExprTy *Val) { 352 Expr *E = (Expr *)Val; 353 assert((E != 0) && "ActOnParenExpr() missing expr"); 354 return new ParenExpr(L, R, E); 355} 356 357/// The UsualUnaryConversions() function is *not* called by this routine. 358/// See C99 6.3.2.1p[2-4] for more details. 359QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType, 360 SourceLocation OpLoc, bool isSizeof) { 361 // C99 6.5.3.4p1: 362 if (isa<FunctionType>(exprType) && isSizeof) 363 // alignof(function) is allowed. 364 Diag(OpLoc, diag::ext_sizeof_function_type); 365 else if (exprType->isVoidType()) 366 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof"); 367 else if (exprType->isIncompleteType()) { 368 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 369 diag::err_alignof_incomplete_type, 370 exprType.getAsString()); 371 return QualType(); // error 372 } 373 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 374 return Context.getSizeType(); 375} 376 377Action::ExprResult Sema:: 378ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 379 SourceLocation LPLoc, TypeTy *Ty, 380 SourceLocation RPLoc) { 381 // If error parsing type, ignore. 382 if (Ty == 0) return true; 383 384 // Verify that this is a valid expression. 385 QualType ArgTy = QualType::getFromOpaquePtr(Ty); 386 387 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof); 388 389 if (resultType.isNull()) 390 return true; 391 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc); 392} 393 394QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 395 DefaultFunctionArrayConversion(V); 396 397 // These operators return the element type of a complex type. 398 if (const ComplexType *CT = V->getType()->getAsComplexType()) 399 return CT->getElementType(); 400 401 // Otherwise they pass through real integer and floating point types here. 402 if (V->getType()->isArithmeticType()) 403 return V->getType(); 404 405 // Reject anything else. 406 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString()); 407 return QualType(); 408} 409 410 411 412Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc, 413 tok::TokenKind Kind, 414 ExprTy *Input) { 415 UnaryOperator::Opcode Opc; 416 switch (Kind) { 417 default: assert(0 && "Unknown unary op!"); 418 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 419 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 420 } 421 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc); 422 if (result.isNull()) 423 return true; 424 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc); 425} 426 427Action::ExprResult Sema:: 428ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc, 429 ExprTy *Idx, SourceLocation RLoc) { 430 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 431 432 // Perform default conversions. 433 DefaultFunctionArrayConversion(LHSExp); 434 DefaultFunctionArrayConversion(RHSExp); 435 436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 437 438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 440 // in the subscript position. As a result, we need to derive the array base 441 // and index from the expression types. 442 Expr *BaseExpr, *IndexExpr; 443 QualType ResultType; 444 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 445 BaseExpr = LHSExp; 446 IndexExpr = RHSExp; 447 // FIXME: need to deal with const... 448 ResultType = PTy->getPointeeType(); 449 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 450 // Handle the uncommon case of "123[Ptr]". 451 BaseExpr = RHSExp; 452 IndexExpr = LHSExp; 453 // FIXME: need to deal with const... 454 ResultType = PTy->getPointeeType(); 455 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 456 BaseExpr = LHSExp; // vectors: V[123] 457 IndexExpr = RHSExp; 458 459 // Component access limited to variables (reject vec4.rg[1]). 460 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 461 !isa<ExtVectorElementExpr>(BaseExpr)) 462 return Diag(LLoc, diag::err_ext_vector_component_access, 463 SourceRange(LLoc, RLoc)); 464 // FIXME: need to deal with const... 465 ResultType = VTy->getElementType(); 466 } else { 467 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value, 468 RHSExp->getSourceRange()); 469 } 470 // C99 6.5.2.1p1 471 if (!IndexExpr->getType()->isIntegerType()) 472 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript, 473 IndexExpr->getSourceRange()); 474 475 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 476 // the following check catches trying to index a pointer to a function (e.g. 477 // void (*)(int)) and pointers to incomplete types. Functions are not 478 // objects in C99. 479 if (!ResultType->isObjectType()) 480 return Diag(BaseExpr->getLocStart(), 481 diag::err_typecheck_subscript_not_object, 482 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange()); 483 484 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 485} 486 487QualType Sema:: 488CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 489 IdentifierInfo &CompName, SourceLocation CompLoc) { 490 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 491 492 // This flag determines whether or not the component is to be treated as a 493 // special name, or a regular GLSL-style component access. 494 bool SpecialComponent = false; 495 496 // The vector accessor can't exceed the number of elements. 497 const char *compStr = CompName.getName(); 498 if (strlen(compStr) > vecType->getNumElements()) { 499 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 500 baseType.getAsString(), SourceRange(CompLoc)); 501 return QualType(); 502 } 503 504 // Check that we've found one of the special components, or that the component 505 // names must come from the same set. 506 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 507 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 508 SpecialComponent = true; 509 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 510 do 511 compStr++; 512 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 513 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 514 do 515 compStr++; 516 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 517 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 518 do 519 compStr++; 520 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 521 } 522 523 if (!SpecialComponent && *compStr) { 524 // We didn't get to the end of the string. This means the component names 525 // didn't come from the same set *or* we encountered an illegal name. 526 Diag(OpLoc, diag::err_ext_vector_component_name_illegal, 527 std::string(compStr,compStr+1), SourceRange(CompLoc)); 528 return QualType(); 529 } 530 // Each component accessor can't exceed the vector type. 531 compStr = CompName.getName(); 532 while (*compStr) { 533 if (vecType->isAccessorWithinNumElements(*compStr)) 534 compStr++; 535 else 536 break; 537 } 538 if (!SpecialComponent && *compStr) { 539 // We didn't get to the end of the string. This means a component accessor 540 // exceeds the number of elements in the vector. 541 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 542 baseType.getAsString(), SourceRange(CompLoc)); 543 return QualType(); 544 } 545 546 // If we have a special component name, verify that the current vector length 547 // is an even number, since all special component names return exactly half 548 // the elements. 549 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 550 return QualType(); 551 } 552 553 // The component accessor looks fine - now we need to compute the actual type. 554 // The vector type is implied by the component accessor. For example, 555 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 556 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 557 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 558 : strlen(CompName.getName()); 559 if (CompSize == 1) 560 return vecType->getElementType(); 561 562 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 563 // Now look up the TypeDefDecl from the vector type. Without this, 564 // diagostics look bad. We want extended vector types to appear built-in. 565 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 566 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 567 return Context.getTypedefType(ExtVectorDecls[i]); 568 } 569 return VT; // should never get here (a typedef type should always be found). 570} 571 572Action::ExprResult Sema:: 573ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 574 tok::TokenKind OpKind, SourceLocation MemberLoc, 575 IdentifierInfo &Member) { 576 Expr *BaseExpr = static_cast<Expr *>(Base); 577 assert(BaseExpr && "no record expression"); 578 579 // Perform default conversions. 580 DefaultFunctionArrayConversion(BaseExpr); 581 582 QualType BaseType = BaseExpr->getType(); 583 assert(!BaseType.isNull() && "no type for member expression"); 584 585 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 586 // must have pointer type, and the accessed type is the pointee. 587 if (OpKind == tok::arrow) { 588 if (const PointerType *PT = BaseType->getAsPointerType()) 589 BaseType = PT->getPointeeType(); 590 else 591 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow, 592 BaseType.getAsString(), BaseExpr->getSourceRange()); 593 } 594 595 // Handle field access to simple records. This also handles access to fields 596 // of the ObjC 'id' struct. 597 if (const RecordType *RTy = BaseType->getAsRecordType()) { 598 RecordDecl *RDecl = RTy->getDecl(); 599 if (RTy->isIncompleteType()) 600 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(), 601 BaseExpr->getSourceRange()); 602 // The record definition is complete, now make sure the member is valid. 603 FieldDecl *MemberDecl = RDecl->getMember(&Member); 604 if (!MemberDecl) 605 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(), 606 BaseExpr->getSourceRange()); 607 608 // Figure out the type of the member; see C99 6.5.2.3p3 609 // FIXME: Handle address space modifiers 610 QualType MemberType = MemberDecl->getType(); 611 unsigned combinedQualifiers = 612 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 613 MemberType = MemberType.getQualifiedType(combinedQualifiers); 614 615 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 616 MemberLoc, MemberType); 617 } 618 619 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 620 // (*Obj).ivar. 621 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 622 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 623 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 624 OpKind == tok::arrow); 625 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar, 626 IFTy->getDecl()->getName(), Member.getName(), 627 BaseExpr->getSourceRange()); 628 } 629 630 // Handle Objective-C property access, which is "Obj.property" where Obj is a 631 // pointer to a (potentially qualified) interface type. 632 const PointerType *PTy; 633 const ObjCInterfaceType *IFTy; 634 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 635 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 636 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 637 638 // FIXME: The logic for looking up nullary and unary selectors should be 639 // shared with the code in ActOnInstanceMessage. 640 641 // Before we look for explicit property declarations, we check for 642 // nullary methods (which allow '.' notation). 643 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 644 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel)) 645 return new ObjCPropertyRefExpr(MD, MD->getResultType(), 646 MemberLoc, BaseExpr); 647 648 // If this reference is in an @implementation, check for 'private' methods. 649 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 650 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 651 if (ObjCImplementationDecl *ImpDecl = 652 ObjCImplementations[ClassDecl->getIdentifier()]) 653 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel)) 654 return new ObjCPropertyRefExpr(MD, MD->getResultType(), 655 MemberLoc, BaseExpr); 656 } 657 658 // FIXME: Need to deal with setter methods that take 1 argument. E.g.: 659 // @interface NSBundle : NSObject {} 660 // - (NSString *)bundlePath; 661 // - (void)setBundlePath:(NSString *)x; 662 // @end 663 // void someMethod() { frameworkBundle.bundlePath = 0; } 664 // 665 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 666 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 667 668 // Lastly, check protocols on qualified interfaces. 669 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 670 E = IFTy->qual_end(); I != E; ++I) 671 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 672 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 673 } 674 675 // Handle 'field access' to vectors, such as 'V.xx'. 676 if (BaseType->isExtVectorType() && OpKind == tok::period) { 677 // Component access limited to variables (reject vec4.rg.g). 678 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 679 !isa<ExtVectorElementExpr>(BaseExpr)) 680 return Diag(MemberLoc, diag::err_ext_vector_component_access, 681 BaseExpr->getSourceRange()); 682 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 683 if (ret.isNull()) 684 return true; 685 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 686 } 687 688 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union, 689 BaseType.getAsString(), BaseExpr->getSourceRange()); 690} 691 692/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 693/// This provides the location of the left/right parens and a list of comma 694/// locations. 695Action::ExprResult Sema:: 696ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 697 ExprTy **args, unsigned NumArgs, 698 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 699 Expr *Fn = static_cast<Expr *>(fn); 700 Expr **Args = reinterpret_cast<Expr**>(args); 701 assert(Fn && "no function call expression"); 702 FunctionDecl *FDecl = NULL; 703 704 // Promote the function operand. 705 UsualUnaryConversions(Fn); 706 707 // If we're directly calling a function, get the declaration for 708 // that function. 709 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 710 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr())) 711 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 712 713 // Make the call expr early, before semantic checks. This guarantees cleanup 714 // of arguments and function on error. 715 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 716 Context.BoolTy, RParenLoc)); 717 718 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have 719 // type pointer to function". 720 const PointerType *PT = Fn->getType()->getAsPointerType(); 721 if (PT == 0) 722 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function, 723 SourceRange(Fn->getLocStart(), RParenLoc)); 724 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType(); 725 if (FuncT == 0) 726 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function, 727 SourceRange(Fn->getLocStart(), RParenLoc)); 728 729 // We know the result type of the call, set it. 730 TheCall->setType(FuncT->getResultType()); 731 732 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 733 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 734 // assignment, to the types of the corresponding parameter, ... 735 unsigned NumArgsInProto = Proto->getNumArgs(); 736 unsigned NumArgsToCheck = NumArgs; 737 738 // If too few arguments are available (and we don't have default 739 // arguments for the remaining parameters), don't make the call. 740 if (NumArgs < NumArgsInProto) { 741 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) { 742 // Use default arguments for missing arguments 743 NumArgsToCheck = NumArgsInProto; 744 TheCall->setNumArgs(NumArgsInProto); 745 } else 746 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 747 Fn->getSourceRange()); 748 } 749 750 // If too many are passed and not variadic, error on the extras and drop 751 // them. 752 if (NumArgs > NumArgsInProto) { 753 if (!Proto->isVariadic()) { 754 Diag(Args[NumArgsInProto]->getLocStart(), 755 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(), 756 SourceRange(Args[NumArgsInProto]->getLocStart(), 757 Args[NumArgs-1]->getLocEnd())); 758 // This deletes the extra arguments. 759 TheCall->setNumArgs(NumArgsInProto); 760 } 761 NumArgsToCheck = NumArgsInProto; 762 } 763 764 // Continue to check argument types (even if we have too few/many args). 765 for (unsigned i = 0; i != NumArgsToCheck; i++) { 766 QualType ProtoArgType = Proto->getArgType(i); 767 768 Expr *Arg; 769 if (i < NumArgs) 770 Arg = Args[i]; 771 else 772 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 773 QualType ArgType = Arg->getType(); 774 775 // Compute implicit casts from the operand to the formal argument type. 776 AssignConvertType ConvTy = 777 CheckSingleAssignmentConstraints(ProtoArgType, Arg); 778 TheCall->setArg(i, Arg); 779 780 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType, 781 ArgType, Arg, "passing")) 782 return true; 783 } 784 785 // If this is a variadic call, handle args passed through "...". 786 if (Proto->isVariadic()) { 787 // Promote the arguments (C99 6.5.2.2p7). 788 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 789 Expr *Arg = Args[i]; 790 DefaultArgumentPromotion(Arg); 791 TheCall->setArg(i, Arg); 792 } 793 } 794 } else { 795 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 796 797 // Promote the arguments (C99 6.5.2.2p6). 798 for (unsigned i = 0; i != NumArgs; i++) { 799 Expr *Arg = Args[i]; 800 DefaultArgumentPromotion(Arg); 801 TheCall->setArg(i, Arg); 802 } 803 } 804 805 // Do special checking on direct calls to functions. 806 if (FDecl) 807 return CheckFunctionCall(FDecl, TheCall.take()); 808 809 return TheCall.take(); 810} 811 812Action::ExprResult Sema:: 813ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 814 SourceLocation RParenLoc, ExprTy *InitExpr) { 815 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 816 QualType literalType = QualType::getFromOpaquePtr(Ty); 817 // FIXME: put back this assert when initializers are worked out. 818 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 819 Expr *literalExpr = static_cast<Expr*>(InitExpr); 820 821 if (literalType->isArrayType()) { 822 if (literalType->getAsVariableArrayType()) 823 return Diag(LParenLoc, 824 diag::err_variable_object_no_init, 825 SourceRange(LParenLoc, 826 literalExpr->getSourceRange().getEnd())); 827 } else if (literalType->isIncompleteType()) { 828 return Diag(LParenLoc, 829 diag::err_typecheck_decl_incomplete_type, 830 literalType.getAsString(), 831 SourceRange(LParenLoc, 832 literalExpr->getSourceRange().getEnd())); 833 } 834 835 if (CheckInitializerTypes(literalExpr, literalType)) 836 return true; 837 838 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 839 if (isFileScope) { // 6.5.2.5p3 840 if (CheckForConstantInitializer(literalExpr, literalType)) 841 return true; 842 } 843 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope); 844} 845 846Action::ExprResult Sema:: 847ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 848 SourceLocation RBraceLoc) { 849 Expr **InitList = reinterpret_cast<Expr**>(initlist); 850 851 // Semantic analysis for initializers is done by ActOnDeclarator() and 852 // CheckInitializer() - it requires knowledge of the object being intialized. 853 854 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc); 855 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 856 return E; 857} 858 859bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 860 assert(VectorTy->isVectorType() && "Not a vector type!"); 861 862 if (Ty->isVectorType() || Ty->isIntegerType()) { 863 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 864 return Diag(R.getBegin(), 865 Ty->isVectorType() ? 866 diag::err_invalid_conversion_between_vectors : 867 diag::err_invalid_conversion_between_vector_and_integer, 868 VectorTy.getAsString().c_str(), 869 Ty.getAsString().c_str(), R); 870 } else 871 return Diag(R.getBegin(), 872 diag::err_invalid_conversion_between_vector_and_scalar, 873 VectorTy.getAsString().c_str(), 874 Ty.getAsString().c_str(), R); 875 876 return false; 877} 878 879Action::ExprResult Sema:: 880ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 881 SourceLocation RParenLoc, ExprTy *Op) { 882 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 883 884 Expr *castExpr = static_cast<Expr*>(Op); 885 QualType castType = QualType::getFromOpaquePtr(Ty); 886 887 UsualUnaryConversions(castExpr); 888 889 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 890 // type needs to be scalar. 891 if (!castType->isVoidType()) { // Cast to void allows any expr type. 892 if (!castType->isScalarType() && !castType->isVectorType()) { 893 // GCC struct/union extension. 894 if (castType == castExpr->getType() && 895 castType->isStructureType() || castType->isUnionType()) { 896 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar, 897 SourceRange(LParenLoc, RParenLoc)); 898 return new CastExpr(castType, castExpr, LParenLoc); 899 } else 900 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar, 901 castType.getAsString(), SourceRange(LParenLoc, RParenLoc)); 902 } 903 if (!castExpr->getType()->isScalarType() && 904 !castExpr->getType()->isVectorType()) 905 return Diag(castExpr->getLocStart(), 906 diag::err_typecheck_expect_scalar_operand, 907 castExpr->getType().getAsString(),castExpr->getSourceRange()); 908 909 if (castExpr->getType()->isVectorType()) { 910 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 911 castExpr->getType(), castType)) 912 return true; 913 } else if (castType->isVectorType()) { 914 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 915 castType, castExpr->getType())) 916 return true; 917 } 918 } 919 return new CastExpr(castType, castExpr, LParenLoc); 920} 921 922/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 923/// In that case, lex = cond. 924inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 925 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 926 UsualUnaryConversions(cond); 927 UsualUnaryConversions(lex); 928 UsualUnaryConversions(rex); 929 QualType condT = cond->getType(); 930 QualType lexT = lex->getType(); 931 QualType rexT = rex->getType(); 932 933 // first, check the condition. 934 if (!condT->isScalarType()) { // C99 6.5.15p2 935 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar, 936 condT.getAsString()); 937 return QualType(); 938 } 939 940 // Now check the two expressions. 941 942 // If both operands have arithmetic type, do the usual arithmetic conversions 943 // to find a common type: C99 6.5.15p3,5. 944 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 945 UsualArithmeticConversions(lex, rex); 946 return lex->getType(); 947 } 948 949 // If both operands are the same structure or union type, the result is that 950 // type. 951 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 952 if (const RecordType *RHSRT = rexT->getAsRecordType()) 953 if (LHSRT->getDecl() == RHSRT->getDecl()) 954 // "If both the operands have structure or union type, the result has 955 // that type." This implies that CV qualifiers are dropped. 956 return lexT.getUnqualifiedType(); 957 } 958 959 // C99 6.5.15p5: "If both operands have void type, the result has void type." 960 // The following || allows only one side to be void (a GCC-ism). 961 if (lexT->isVoidType() || rexT->isVoidType()) { 962 if (!lexT->isVoidType()) 963 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void, 964 rex->getSourceRange()); 965 if (!rexT->isVoidType()) 966 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void, 967 lex->getSourceRange()); 968 ImpCastExprToType(lex, Context.VoidTy); 969 ImpCastExprToType(rex, Context.VoidTy); 970 return Context.VoidTy; 971 } 972 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 973 // the type of the other operand." 974 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) { 975 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 976 return lexT; 977 } 978 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) { 979 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 980 return rexT; 981 } 982 // Handle the case where both operands are pointers before we handle null 983 // pointer constants in case both operands are null pointer constants. 984 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 985 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 986 // get the "pointed to" types 987 QualType lhptee = LHSPT->getPointeeType(); 988 QualType rhptee = RHSPT->getPointeeType(); 989 990 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 991 if (lhptee->isVoidType() && 992 rhptee->isIncompleteOrObjectType()) { 993 // Figure out necessary qualifiers (C99 6.5.15p6) 994 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 995 QualType destType = Context.getPointerType(destPointee); 996 ImpCastExprToType(lex, destType); // add qualifiers if necessary 997 ImpCastExprToType(rex, destType); // promote to void* 998 return destType; 999 } 1000 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 1001 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 1002 QualType destType = Context.getPointerType(destPointee); 1003 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1004 ImpCastExprToType(rex, destType); // promote to void* 1005 return destType; 1006 } 1007 1008 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1009 rhptee.getUnqualifiedType())) { 1010 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers, 1011 lexT.getAsString(), rexT.getAsString(), 1012 lex->getSourceRange(), rex->getSourceRange()); 1013 // In this situation, we assume void* type. No especially good 1014 // reason, but this is what gcc does, and we do have to pick 1015 // to get a consistent AST. 1016 QualType voidPtrTy = Context.getPointerType(Context.VoidTy); 1017 ImpCastExprToType(lex, voidPtrTy); 1018 ImpCastExprToType(rex, voidPtrTy); 1019 return voidPtrTy; 1020 } 1021 // The pointer types are compatible. 1022 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1023 // differently qualified versions of compatible types, the result type is 1024 // a pointer to an appropriately qualified version of the *composite* 1025 // type. 1026 // FIXME: Need to calculate the composite type. 1027 // FIXME: Need to add qualifiers 1028 QualType compositeType = lexT; 1029 ImpCastExprToType(lex, compositeType); 1030 ImpCastExprToType(rex, compositeType); 1031 return compositeType; 1032 } 1033 } 1034 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1035 // evaluates to "struct objc_object *" (and is handled above when comparing 1036 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType? 1037 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1038 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true)) 1039 return Context.getObjCIdType(); 1040 } 1041 // Otherwise, the operands are not compatible. 1042 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands, 1043 lexT.getAsString(), rexT.getAsString(), 1044 lex->getSourceRange(), rex->getSourceRange()); 1045 return QualType(); 1046} 1047 1048/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1049/// in the case of a the GNU conditional expr extension. 1050Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1051 SourceLocation ColonLoc, 1052 ExprTy *Cond, ExprTy *LHS, 1053 ExprTy *RHS) { 1054 Expr *CondExpr = (Expr *) Cond; 1055 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1056 1057 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1058 // was the condition. 1059 bool isLHSNull = LHSExpr == 0; 1060 if (isLHSNull) 1061 LHSExpr = CondExpr; 1062 1063 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1064 RHSExpr, QuestionLoc); 1065 if (result.isNull()) 1066 return true; 1067 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1068 RHSExpr, result); 1069} 1070 1071/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 1072/// do not have a prototype. Arguments that have type float are promoted to 1073/// double. All other argument types are converted by UsualUnaryConversions(). 1074void Sema::DefaultArgumentPromotion(Expr *&Expr) { 1075 QualType Ty = Expr->getType(); 1076 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 1077 1078 // If this is a 'float' (CVR qualified or typedef) promote to double. 1079 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 1080 if (BT->getKind() == BuiltinType::Float) 1081 return ImpCastExprToType(Expr, Context.DoubleTy); 1082 1083 UsualUnaryConversions(Expr); 1084} 1085 1086/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 1087void Sema::DefaultFunctionArrayConversion(Expr *&E) { 1088 QualType Ty = E->getType(); 1089 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 1090 1091 if (const ReferenceType *ref = Ty->getAsReferenceType()) { 1092 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr] 1093 Ty = E->getType(); 1094 } 1095 if (Ty->isFunctionType()) 1096 ImpCastExprToType(E, Context.getPointerType(Ty)); 1097 else if (Ty->isArrayType()) 1098 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 1099} 1100 1101/// UsualUnaryConversions - Performs various conversions that are common to most 1102/// operators (C99 6.3). The conversions of array and function types are 1103/// sometimes surpressed. For example, the array->pointer conversion doesn't 1104/// apply if the array is an argument to the sizeof or address (&) operators. 1105/// In these instances, this routine should *not* be called. 1106Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 1107 QualType Ty = Expr->getType(); 1108 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 1109 1110 if (const ReferenceType *Ref = Ty->getAsReferenceType()) { 1111 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr] 1112 Ty = Expr->getType(); 1113 } 1114 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 1115 ImpCastExprToType(Expr, Context.IntTy); 1116 else 1117 DefaultFunctionArrayConversion(Expr); 1118 1119 return Expr; 1120} 1121 1122/// UsualArithmeticConversions - Performs various conversions that are common to 1123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1124/// routine returns the first non-arithmetic type found. The client is 1125/// responsible for emitting appropriate error diagnostics. 1126/// FIXME: verify the conversion rules for "complex int" are consistent with 1127/// GCC. 1128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 1129 bool isCompAssign) { 1130 if (!isCompAssign) { 1131 UsualUnaryConversions(lhsExpr); 1132 UsualUnaryConversions(rhsExpr); 1133 } 1134 // For conversion purposes, we ignore any qualifiers. 1135 // For example, "const float" and "float" are equivalent. 1136 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType(); 1137 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType(); 1138 1139 // If both types are identical, no conversion is needed. 1140 if (lhs == rhs) 1141 return lhs; 1142 1143 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1144 // The caller can deal with this (e.g. pointer + int). 1145 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 1146 return lhs; 1147 1148 // At this point, we have two different arithmetic types. 1149 1150 // Handle complex types first (C99 6.3.1.8p1). 1151 if (lhs->isComplexType() || rhs->isComplexType()) { 1152 // if we have an integer operand, the result is the complex type. 1153 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 1154 // convert the rhs to the lhs complex type. 1155 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1156 return lhs; 1157 } 1158 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 1159 // convert the lhs to the rhs complex type. 1160 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1161 return rhs; 1162 } 1163 // This handles complex/complex, complex/float, or float/complex. 1164 // When both operands are complex, the shorter operand is converted to the 1165 // type of the longer, and that is the type of the result. This corresponds 1166 // to what is done when combining two real floating-point operands. 1167 // The fun begins when size promotion occur across type domains. 1168 // From H&S 6.3.4: When one operand is complex and the other is a real 1169 // floating-point type, the less precise type is converted, within it's 1170 // real or complex domain, to the precision of the other type. For example, 1171 // when combining a "long double" with a "double _Complex", the 1172 // "double _Complex" is promoted to "long double _Complex". 1173 int result = Context.getFloatingTypeOrder(lhs, rhs); 1174 1175 if (result > 0) { // The left side is bigger, convert rhs. 1176 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 1177 if (!isCompAssign) 1178 ImpCastExprToType(rhsExpr, rhs); 1179 } else if (result < 0) { // The right side is bigger, convert lhs. 1180 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 1181 if (!isCompAssign) 1182 ImpCastExprToType(lhsExpr, lhs); 1183 } 1184 // At this point, lhs and rhs have the same rank/size. Now, make sure the 1185 // domains match. This is a requirement for our implementation, C99 1186 // does not require this promotion. 1187 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 1188 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 1189 if (!isCompAssign) 1190 ImpCastExprToType(lhsExpr, rhs); 1191 return rhs; 1192 } else { // handle "_Complex double, double". 1193 if (!isCompAssign) 1194 ImpCastExprToType(rhsExpr, lhs); 1195 return lhs; 1196 } 1197 } 1198 return lhs; // The domain/size match exactly. 1199 } 1200 // Now handle "real" floating types (i.e. float, double, long double). 1201 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 1202 // if we have an integer operand, the result is the real floating type. 1203 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 1204 // convert rhs to the lhs floating point type. 1205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1206 return lhs; 1207 } 1208 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 1209 // convert lhs to the rhs floating point type. 1210 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1211 return rhs; 1212 } 1213 // We have two real floating types, float/complex combos were handled above. 1214 // Convert the smaller operand to the bigger result. 1215 int result = Context.getFloatingTypeOrder(lhs, rhs); 1216 1217 if (result > 0) { // convert the rhs 1218 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1219 return lhs; 1220 } 1221 if (result < 0) { // convert the lhs 1222 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs 1223 return rhs; 1224 } 1225 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison"); 1226 } 1227 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 1228 // Handle GCC complex int extension. 1229 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 1230 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 1231 1232 if (lhsComplexInt && rhsComplexInt) { 1233 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 1234 rhsComplexInt->getElementType()) >= 0) { 1235 // convert the rhs 1236 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1237 return lhs; 1238 } 1239 if (!isCompAssign) 1240 ImpCastExprToType(lhsExpr, rhs); // convert the lhs 1241 return rhs; 1242 } else if (lhsComplexInt && rhs->isIntegerType()) { 1243 // convert the rhs to the lhs complex type. 1244 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1245 return lhs; 1246 } else if (rhsComplexInt && lhs->isIntegerType()) { 1247 // convert the lhs to the rhs complex type. 1248 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1249 return rhs; 1250 } 1251 } 1252 // Finally, we have two differing integer types. 1253 // The rules for this case are in C99 6.3.1.8 1254 int compare = Context.getIntegerTypeOrder(lhs, rhs); 1255 bool lhsSigned = lhs->isSignedIntegerType(), 1256 rhsSigned = rhs->isSignedIntegerType(); 1257 QualType destType; 1258 if (lhsSigned == rhsSigned) { 1259 // Same signedness; use the higher-ranked type 1260 destType = compare >= 0 ? lhs : rhs; 1261 } else if (compare != (lhsSigned ? 1 : -1)) { 1262 // The unsigned type has greater than or equal rank to the 1263 // signed type, so use the unsigned type 1264 destType = lhsSigned ? rhs : lhs; 1265 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 1266 // The two types are different widths; if we are here, that 1267 // means the signed type is larger than the unsigned type, so 1268 // use the signed type. 1269 destType = lhsSigned ? lhs : rhs; 1270 } else { 1271 // The signed type is higher-ranked than the unsigned type, 1272 // but isn't actually any bigger (like unsigned int and long 1273 // on most 32-bit systems). Use the unsigned type corresponding 1274 // to the signed type. 1275 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 1276 } 1277 if (!isCompAssign) { 1278 ImpCastExprToType(lhsExpr, destType); 1279 ImpCastExprToType(rhsExpr, destType); 1280 } 1281 return destType; 1282} 1283 1284// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1285// being closely modeled after the C99 spec:-). The odd characteristic of this 1286// routine is it effectively iqnores the qualifiers on the top level pointee. 1287// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1288// FIXME: add a couple examples in this comment. 1289Sema::AssignConvertType 1290Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1291 QualType lhptee, rhptee; 1292 1293 // get the "pointed to" type (ignoring qualifiers at the top level) 1294 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1295 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1296 1297 // make sure we operate on the canonical type 1298 lhptee = lhptee.getCanonicalType(); 1299 rhptee = rhptee.getCanonicalType(); 1300 1301 AssignConvertType ConvTy = Compatible; 1302 1303 // C99 6.5.16.1p1: This following citation is common to constraints 1304 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1305 // qualifiers of the type *pointed to* by the right; 1306 // FIXME: Handle ASQualType 1307 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) != 1308 rhptee.getCVRQualifiers()) 1309 ConvTy = CompatiblePointerDiscardsQualifiers; 1310 1311 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1312 // incomplete type and the other is a pointer to a qualified or unqualified 1313 // version of void... 1314 if (lhptee->isVoidType()) { 1315 if (rhptee->isIncompleteOrObjectType()) 1316 return ConvTy; 1317 1318 // As an extension, we allow cast to/from void* to function pointer. 1319 assert(rhptee->isFunctionType()); 1320 return FunctionVoidPointer; 1321 } 1322 1323 if (rhptee->isVoidType()) { 1324 if (lhptee->isIncompleteOrObjectType()) 1325 return ConvTy; 1326 1327 // As an extension, we allow cast to/from void* to function pointer. 1328 assert(lhptee->isFunctionType()); 1329 return FunctionVoidPointer; 1330 } 1331 1332 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1333 // unqualified versions of compatible types, ... 1334 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1335 rhptee.getUnqualifiedType())) 1336 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1337 return ConvTy; 1338} 1339 1340/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1341/// has code to accommodate several GCC extensions when type checking 1342/// pointers. Here are some objectionable examples that GCC considers warnings: 1343/// 1344/// int a, *pint; 1345/// short *pshort; 1346/// struct foo *pfoo; 1347/// 1348/// pint = pshort; // warning: assignment from incompatible pointer type 1349/// a = pint; // warning: assignment makes integer from pointer without a cast 1350/// pint = a; // warning: assignment makes pointer from integer without a cast 1351/// pint = pfoo; // warning: assignment from incompatible pointer type 1352/// 1353/// As a result, the code for dealing with pointers is more complex than the 1354/// C99 spec dictates. 1355/// 1356Sema::AssignConvertType 1357Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1358 // Get canonical types. We're not formatting these types, just comparing 1359 // them. 1360 lhsType = lhsType.getCanonicalType().getUnqualifiedType(); 1361 rhsType = rhsType.getCanonicalType().getUnqualifiedType(); 1362 1363 if (lhsType == rhsType) 1364 return Compatible; // Common case: fast path an exact match. 1365 1366 if (lhsType->isReferenceType() || rhsType->isReferenceType()) { 1367 if (Context.typesAreCompatible(lhsType, rhsType)) 1368 return Compatible; 1369 return Incompatible; 1370 } 1371 1372 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1373 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1374 return Compatible; 1375 // Relax integer conversions like we do for pointers below. 1376 if (rhsType->isIntegerType()) 1377 return IntToPointer; 1378 if (lhsType->isIntegerType()) 1379 return PointerToInt; 1380 return Incompatible; 1381 } 1382 1383 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1384 // For ExtVector, allow vector splats; float -> <n x float> 1385 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1386 if (LV->getElementType() == rhsType) 1387 return Compatible; 1388 1389 // If we are allowing lax vector conversions, and LHS and RHS are both 1390 // vectors, the total size only needs to be the same. This is a bitcast; 1391 // no bits are changed but the result type is different. 1392 if (getLangOptions().LaxVectorConversions && 1393 lhsType->isVectorType() && rhsType->isVectorType()) { 1394 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1395 return Compatible; 1396 } 1397 return Incompatible; 1398 } 1399 1400 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1401 return Compatible; 1402 1403 if (isa<PointerType>(lhsType)) { 1404 if (rhsType->isIntegerType()) 1405 return IntToPointer; 1406 1407 if (isa<PointerType>(rhsType)) 1408 return CheckPointerTypesForAssignment(lhsType, rhsType); 1409 return Incompatible; 1410 } 1411 1412 if (isa<PointerType>(rhsType)) { 1413 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1414 if (lhsType == Context.BoolTy) 1415 return Compatible; 1416 1417 if (lhsType->isIntegerType()) 1418 return PointerToInt; 1419 1420 if (isa<PointerType>(lhsType)) 1421 return CheckPointerTypesForAssignment(lhsType, rhsType); 1422 return Incompatible; 1423 } 1424 1425 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1426 if (Context.typesAreCompatible(lhsType, rhsType)) 1427 return Compatible; 1428 } 1429 return Incompatible; 1430} 1431 1432Sema::AssignConvertType 1433Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 1434 // C99 6.5.16.1p1: the left operand is a pointer and the right is 1435 // a null pointer constant. 1436 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType()) 1437 && rExpr->isNullPointerConstant(Context)) { 1438 ImpCastExprToType(rExpr, lhsType); 1439 return Compatible; 1440 } 1441 // This check seems unnatural, however it is necessary to ensure the proper 1442 // conversion of functions/arrays. If the conversion were done for all 1443 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 1444 // expressions that surpress this implicit conversion (&, sizeof). 1445 // 1446 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references 1447 // are better understood. 1448 if (!lhsType->isReferenceType()) 1449 DefaultFunctionArrayConversion(rExpr); 1450 1451 Sema::AssignConvertType result = 1452 CheckAssignmentConstraints(lhsType, rExpr->getType()); 1453 1454 // C99 6.5.16.1p2: The value of the right operand is converted to the 1455 // type of the assignment expression. 1456 if (rExpr->getType() != lhsType) 1457 ImpCastExprToType(rExpr, lhsType); 1458 return result; 1459} 1460 1461Sema::AssignConvertType 1462Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 1463 return CheckAssignmentConstraints(lhsType, rhsType); 1464} 1465 1466QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) { 1467 Diag(loc, diag::err_typecheck_invalid_operands, 1468 lex->getType().getAsString(), rex->getType().getAsString(), 1469 lex->getSourceRange(), rex->getSourceRange()); 1470 return QualType(); 1471} 1472 1473inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex, 1474 Expr *&rex) { 1475 // For conversion purposes, we ignore any qualifiers. 1476 // For example, "const float" and "float" are equivalent. 1477 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType(); 1478 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType(); 1479 1480 // If the vector types are identical, return. 1481 if (lhsType == rhsType) 1482 return lhsType; 1483 1484 // Handle the case of a vector & extvector type of the same size and element 1485 // type. It would be nice if we only had one vector type someday. 1486 if (getLangOptions().LaxVectorConversions) 1487 if (const VectorType *LV = lhsType->getAsVectorType()) 1488 if (const VectorType *RV = rhsType->getAsVectorType()) 1489 if (LV->getElementType() == RV->getElementType() && 1490 LV->getNumElements() == RV->getNumElements()) 1491 return lhsType->isExtVectorType() ? lhsType : rhsType; 1492 1493 // If the lhs is an extended vector and the rhs is a scalar of the same type 1494 // or a literal, promote the rhs to the vector type. 1495 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 1496 QualType eltType = V->getElementType(); 1497 1498 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 1499 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 1500 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 1501 ImpCastExprToType(rex, lhsType); 1502 return lhsType; 1503 } 1504 } 1505 1506 // If the rhs is an extended vector and the lhs is a scalar of the same type, 1507 // promote the lhs to the vector type. 1508 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 1509 QualType eltType = V->getElementType(); 1510 1511 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 1512 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 1513 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 1514 ImpCastExprToType(lex, rhsType); 1515 return rhsType; 1516 } 1517 } 1518 1519 // You cannot convert between vector values of different size. 1520 Diag(loc, diag::err_typecheck_vector_not_convertable, 1521 lex->getType().getAsString(), rex->getType().getAsString(), 1522 lex->getSourceRange(), rex->getSourceRange()); 1523 return QualType(); 1524} 1525 1526inline QualType Sema::CheckMultiplyDivideOperands( 1527 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1528{ 1529 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1530 1531 if (lhsType->isVectorType() || rhsType->isVectorType()) 1532 return CheckVectorOperands(loc, lex, rex); 1533 1534 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1535 1536 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1537 return compType; 1538 return InvalidOperands(loc, lex, rex); 1539} 1540 1541inline QualType Sema::CheckRemainderOperands( 1542 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1543{ 1544 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1545 1546 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1547 1548 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1549 return compType; 1550 return InvalidOperands(loc, lex, rex); 1551} 1552 1553inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 1554 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1555{ 1556 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1557 return CheckVectorOperands(loc, lex, rex); 1558 1559 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1560 1561 // handle the common case first (both operands are arithmetic). 1562 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1563 return compType; 1564 1565 // Put any potential pointer into PExp 1566 Expr* PExp = lex, *IExp = rex; 1567 if (IExp->getType()->isPointerType()) 1568 std::swap(PExp, IExp); 1569 1570 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 1571 if (IExp->getType()->isIntegerType()) { 1572 // Check for arithmetic on pointers to incomplete types 1573 if (!PTy->getPointeeType()->isObjectType()) { 1574 if (PTy->getPointeeType()->isVoidType()) { 1575 Diag(loc, diag::ext_gnu_void_ptr, 1576 lex->getSourceRange(), rex->getSourceRange()); 1577 } else { 1578 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type, 1579 lex->getType().getAsString(), lex->getSourceRange()); 1580 return QualType(); 1581 } 1582 } 1583 return PExp->getType(); 1584 } 1585 } 1586 1587 return InvalidOperands(loc, lex, rex); 1588} 1589 1590// C99 6.5.6 1591QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 1592 SourceLocation loc, bool isCompAssign) { 1593 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1594 return CheckVectorOperands(loc, lex, rex); 1595 1596 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1597 1598 // Enforce type constraints: C99 6.5.6p3. 1599 1600 // Handle the common case first (both operands are arithmetic). 1601 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1602 return compType; 1603 1604 // Either ptr - int or ptr - ptr. 1605 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 1606 QualType lpointee = LHSPTy->getPointeeType(); 1607 1608 // The LHS must be an object type, not incomplete, function, etc. 1609 if (!lpointee->isObjectType()) { 1610 // Handle the GNU void* extension. 1611 if (lpointee->isVoidType()) { 1612 Diag(loc, diag::ext_gnu_void_ptr, 1613 lex->getSourceRange(), rex->getSourceRange()); 1614 } else { 1615 Diag(loc, diag::err_typecheck_sub_ptr_object, 1616 lex->getType().getAsString(), lex->getSourceRange()); 1617 return QualType(); 1618 } 1619 } 1620 1621 // The result type of a pointer-int computation is the pointer type. 1622 if (rex->getType()->isIntegerType()) 1623 return lex->getType(); 1624 1625 // Handle pointer-pointer subtractions. 1626 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 1627 QualType rpointee = RHSPTy->getPointeeType(); 1628 1629 // RHS must be an object type, unless void (GNU). 1630 if (!rpointee->isObjectType()) { 1631 // Handle the GNU void* extension. 1632 if (rpointee->isVoidType()) { 1633 if (!lpointee->isVoidType()) 1634 Diag(loc, diag::ext_gnu_void_ptr, 1635 lex->getSourceRange(), rex->getSourceRange()); 1636 } else { 1637 Diag(loc, diag::err_typecheck_sub_ptr_object, 1638 rex->getType().getAsString(), rex->getSourceRange()); 1639 return QualType(); 1640 } 1641 } 1642 1643 // Pointee types must be compatible. 1644 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(), 1645 rpointee.getUnqualifiedType())) { 1646 Diag(loc, diag::err_typecheck_sub_ptr_compatible, 1647 lex->getType().getAsString(), rex->getType().getAsString(), 1648 lex->getSourceRange(), rex->getSourceRange()); 1649 return QualType(); 1650 } 1651 1652 return Context.getPointerDiffType(); 1653 } 1654 } 1655 1656 return InvalidOperands(loc, lex, rex); 1657} 1658 1659// C99 6.5.7 1660QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1661 bool isCompAssign) { 1662 // C99 6.5.7p2: Each of the operands shall have integer type. 1663 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 1664 return InvalidOperands(loc, lex, rex); 1665 1666 // Shifts don't perform usual arithmetic conversions, they just do integer 1667 // promotions on each operand. C99 6.5.7p3 1668 if (!isCompAssign) 1669 UsualUnaryConversions(lex); 1670 UsualUnaryConversions(rex); 1671 1672 // "The type of the result is that of the promoted left operand." 1673 return lex->getType(); 1674} 1675 1676// C99 6.5.8 1677QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1678 bool isRelational) { 1679 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1680 return CheckVectorCompareOperands(lex, rex, loc, isRelational); 1681 1682 // C99 6.5.8p3 / C99 6.5.9p4 1683 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1684 UsualArithmeticConversions(lex, rex); 1685 else { 1686 UsualUnaryConversions(lex); 1687 UsualUnaryConversions(rex); 1688 } 1689 QualType lType = lex->getType(); 1690 QualType rType = rex->getType(); 1691 1692 // For non-floating point types, check for self-comparisons of the form 1693 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1694 // often indicate logic errors in the program. 1695 if (!lType->isFloatingType()) { 1696 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1697 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1698 if (DRL->getDecl() == DRR->getDecl()) 1699 Diag(loc, diag::warn_selfcomparison); 1700 } 1701 1702 if (isRelational) { 1703 if (lType->isRealType() && rType->isRealType()) 1704 return Context.IntTy; 1705 } else { 1706 // Check for comparisons of floating point operands using != and ==. 1707 if (lType->isFloatingType()) { 1708 assert (rType->isFloatingType()); 1709 CheckFloatComparison(loc,lex,rex); 1710 } 1711 1712 if (lType->isArithmeticType() && rType->isArithmeticType()) 1713 return Context.IntTy; 1714 } 1715 1716 bool LHSIsNull = lex->isNullPointerConstant(Context); 1717 bool RHSIsNull = rex->isNullPointerConstant(Context); 1718 1719 // All of the following pointer related warnings are GCC extensions, except 1720 // when handling null pointer constants. One day, we can consider making them 1721 // errors (when -pedantic-errors is enabled). 1722 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 1723 QualType LCanPointeeTy = 1724 lType->getAsPointerType()->getPointeeType().getCanonicalType(); 1725 QualType RCanPointeeTy = 1726 rType->getAsPointerType()->getPointeeType().getCanonicalType(); 1727 1728 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 1729 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 1730 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 1731 RCanPointeeTy.getUnqualifiedType())) { 1732 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers, 1733 lType.getAsString(), rType.getAsString(), 1734 lex->getSourceRange(), rex->getSourceRange()); 1735 } 1736 ImpCastExprToType(rex, lType); // promote the pointer to pointer 1737 return Context.IntTy; 1738 } 1739 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 1740 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 1741 ImpCastExprToType(rex, lType); 1742 return Context.IntTy; 1743 } 1744 } 1745 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 1746 rType->isIntegerType()) { 1747 if (!RHSIsNull) 1748 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1749 lType.getAsString(), rType.getAsString(), 1750 lex->getSourceRange(), rex->getSourceRange()); 1751 ImpCastExprToType(rex, lType); // promote the integer to pointer 1752 return Context.IntTy; 1753 } 1754 if (lType->isIntegerType() && 1755 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 1756 if (!LHSIsNull) 1757 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1758 lType.getAsString(), rType.getAsString(), 1759 lex->getSourceRange(), rex->getSourceRange()); 1760 ImpCastExprToType(lex, rType); // promote the integer to pointer 1761 return Context.IntTy; 1762 } 1763 return InvalidOperands(loc, lex, rex); 1764} 1765 1766/// CheckVectorCompareOperands - vector comparisons are a clang extension that 1767/// operates on extended vector types. Instead of producing an IntTy result, 1768/// like a scalar comparison, a vector comparison produces a vector of integer 1769/// types. 1770QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 1771 SourceLocation loc, 1772 bool isRelational) { 1773 // Check to make sure we're operating on vectors of the same type and width, 1774 // Allowing one side to be a scalar of element type. 1775 QualType vType = CheckVectorOperands(loc, lex, rex); 1776 if (vType.isNull()) 1777 return vType; 1778 1779 QualType lType = lex->getType(); 1780 QualType rType = rex->getType(); 1781 1782 // For non-floating point types, check for self-comparisons of the form 1783 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1784 // often indicate logic errors in the program. 1785 if (!lType->isFloatingType()) { 1786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1788 if (DRL->getDecl() == DRR->getDecl()) 1789 Diag(loc, diag::warn_selfcomparison); 1790 } 1791 1792 // Check for comparisons of floating point operands using != and ==. 1793 if (!isRelational && lType->isFloatingType()) { 1794 assert (rType->isFloatingType()); 1795 CheckFloatComparison(loc,lex,rex); 1796 } 1797 1798 // Return the type for the comparison, which is the same as vector type for 1799 // integer vectors, or an integer type of identical size and number of 1800 // elements for floating point vectors. 1801 if (lType->isIntegerType()) 1802 return lType; 1803 1804 const VectorType *VTy = lType->getAsVectorType(); 1805 1806 // FIXME: need to deal with non-32b int / non-64b long long 1807 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 1808 if (TypeSize == 32) { 1809 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 1810 } 1811 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 1812 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 1813} 1814 1815inline QualType Sema::CheckBitwiseOperands( 1816 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1817{ 1818 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1819 return CheckVectorOperands(loc, lex, rex); 1820 1821 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1822 1823 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1824 return compType; 1825 return InvalidOperands(loc, lex, rex); 1826} 1827 1828inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 1829 Expr *&lex, Expr *&rex, SourceLocation loc) 1830{ 1831 UsualUnaryConversions(lex); 1832 UsualUnaryConversions(rex); 1833 1834 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 1835 return Context.IntTy; 1836 return InvalidOperands(loc, lex, rex); 1837} 1838 1839inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1 1840 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType) 1841{ 1842 QualType lhsType = lex->getType(); 1843 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType; 1844 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(); 1845 1846 switch (mlval) { // C99 6.5.16p2 1847 case Expr::MLV_Valid: 1848 break; 1849 case Expr::MLV_ConstQualified: 1850 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange()); 1851 return QualType(); 1852 case Expr::MLV_ArrayType: 1853 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue, 1854 lhsType.getAsString(), lex->getSourceRange()); 1855 return QualType(); 1856 case Expr::MLV_NotObjectType: 1857 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue, 1858 lhsType.getAsString(), lex->getSourceRange()); 1859 return QualType(); 1860 case Expr::MLV_InvalidExpression: 1861 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue, 1862 lex->getSourceRange()); 1863 return QualType(); 1864 case Expr::MLV_IncompleteType: 1865 case Expr::MLV_IncompleteVoidType: 1866 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 1867 lhsType.getAsString(), lex->getSourceRange()); 1868 return QualType(); 1869 case Expr::MLV_DuplicateVectorComponents: 1870 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue, 1871 lex->getSourceRange()); 1872 return QualType(); 1873 } 1874 1875 AssignConvertType ConvTy; 1876 if (compoundType.isNull()) 1877 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex); 1878 else 1879 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType); 1880 1881 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType, 1882 rex, "assigning")) 1883 return QualType(); 1884 1885 // C99 6.5.16p3: The type of an assignment expression is the type of the 1886 // left operand unless the left operand has qualified type, in which case 1887 // it is the unqualified version of the type of the left operand. 1888 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 1889 // is converted to the type of the assignment expression (above). 1890 // C++ 5.17p1: the type of the assignment expression is that of its left 1891 // oprdu. 1892 return lhsType.getUnqualifiedType(); 1893} 1894 1895inline QualType Sema::CheckCommaOperands( // C99 6.5.17 1896 Expr *&lex, Expr *&rex, SourceLocation loc) { 1897 // Comma does not perform unary or binary promotions. 1898 return rex->getType(); 1899} 1900 1901/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 1902/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 1903QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) { 1904 QualType resType = op->getType(); 1905 assert(!resType.isNull() && "no type for increment/decrement expression"); 1906 1907 // C99 6.5.2.4p1: We allow complex as a GCC extension. 1908 if (const PointerType *pt = resType->getAsPointerType()) { 1909 if (pt->getPointeeType()->isVoidType()) { 1910 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange()); 1911 } else if (!pt->getPointeeType()->isObjectType()) { 1912 // C99 6.5.2.4p2, 6.5.6p2 1913 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type, 1914 resType.getAsString(), op->getSourceRange()); 1915 return QualType(); 1916 } 1917 } else if (!resType->isRealType()) { 1918 if (resType->isComplexType()) 1919 // C99 does not support ++/-- on complex types. 1920 Diag(OpLoc, diag::ext_integer_increment_complex, 1921 resType.getAsString(), op->getSourceRange()); 1922 else { 1923 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement, 1924 resType.getAsString(), op->getSourceRange()); 1925 return QualType(); 1926 } 1927 } 1928 // At this point, we know we have a real, complex or pointer type. 1929 // Now make sure the operand is a modifiable lvalue. 1930 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(); 1931 if (mlval != Expr::MLV_Valid) { 1932 // FIXME: emit a more precise diagnostic... 1933 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr, 1934 op->getSourceRange()); 1935 return QualType(); 1936 } 1937 return resType; 1938} 1939 1940/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 1941/// This routine allows us to typecheck complex/recursive expressions 1942/// where the declaration is needed for type checking. Here are some 1943/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2]. 1944static ValueDecl *getPrimaryDecl(Expr *E) { 1945 switch (E->getStmtClass()) { 1946 case Stmt::DeclRefExprClass: 1947 return cast<DeclRefExpr>(E)->getDecl(); 1948 case Stmt::MemberExprClass: 1949 // Fields cannot be declared with a 'register' storage class. 1950 // &X->f is always ok, even if X is declared register. 1951 if (cast<MemberExpr>(E)->isArrow()) 1952 return 0; 1953 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 1954 case Stmt::ArraySubscriptExprClass: { 1955 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer. 1956 1957 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 1958 if (!VD || VD->getType()->isPointerType()) 1959 return 0; 1960 else 1961 return VD; 1962 } 1963 case Stmt::UnaryOperatorClass: 1964 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr()); 1965 case Stmt::ParenExprClass: 1966 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 1967 case Stmt::ImplicitCastExprClass: 1968 // &X[4] when X is an array, has an implicit cast from array to pointer. 1969 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 1970 default: 1971 return 0; 1972 } 1973} 1974 1975/// CheckAddressOfOperand - The operand of & must be either a function 1976/// designator or an lvalue designating an object. If it is an lvalue, the 1977/// object cannot be declared with storage class register or be a bit field. 1978/// Note: The usual conversions are *not* applied to the operand of the & 1979/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 1980QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 1981 if (getLangOptions().C99) { 1982 // Implement C99-only parts of addressof rules. 1983 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 1984 if (uOp->getOpcode() == UnaryOperator::Deref) 1985 // Per C99 6.5.3.2, the address of a deref always returns a valid result 1986 // (assuming the deref expression is valid). 1987 return uOp->getSubExpr()->getType(); 1988 } 1989 // Technically, there should be a check for array subscript 1990 // expressions here, but the result of one is always an lvalue anyway. 1991 } 1992 ValueDecl *dcl = getPrimaryDecl(op); 1993 Expr::isLvalueResult lval = op->isLvalue(); 1994 1995 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 1996 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 1997 // FIXME: emit more specific diag... 1998 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof, 1999 op->getSourceRange()); 2000 return QualType(); 2001 } 2002 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 2003 if (MemExpr->getMemberDecl()->isBitField()) { 2004 Diag(OpLoc, diag::err_typecheck_address_of, 2005 std::string("bit-field"), op->getSourceRange()); 2006 return QualType(); 2007 } 2008 // Check for Apple extension for accessing vector components. 2009 } else if (isa<ArraySubscriptExpr>(op) && 2010 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 2011 Diag(OpLoc, diag::err_typecheck_address_of, 2012 std::string("vector"), op->getSourceRange()); 2013 return QualType(); 2014 } else if (dcl) { // C99 6.5.3.2p1 2015 // We have an lvalue with a decl. Make sure the decl is not declared 2016 // with the register storage-class specifier. 2017 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2018 if (vd->getStorageClass() == VarDecl::Register) { 2019 Diag(OpLoc, diag::err_typecheck_address_of, 2020 std::string("register variable"), op->getSourceRange()); 2021 return QualType(); 2022 } 2023 } else 2024 assert(0 && "Unknown/unexpected decl type"); 2025 } 2026 // If the operand has type "type", the result has type "pointer to type". 2027 return Context.getPointerType(op->getType()); 2028} 2029 2030QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2031 UsualUnaryConversions(op); 2032 QualType qType = op->getType(); 2033 2034 if (const PointerType *PT = qType->getAsPointerType()) { 2035 // Note that per both C89 and C99, this is always legal, even 2036 // if ptype is an incomplete type or void. 2037 // It would be possible to warn about dereferencing a 2038 // void pointer, but it's completely well-defined, 2039 // and such a warning is unlikely to catch any mistakes. 2040 return PT->getPointeeType(); 2041 } 2042 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer, 2043 qType.getAsString(), op->getSourceRange()); 2044 return QualType(); 2045} 2046 2047static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2048 tok::TokenKind Kind) { 2049 BinaryOperator::Opcode Opc; 2050 switch (Kind) { 2051 default: assert(0 && "Unknown binop!"); 2052 case tok::star: Opc = BinaryOperator::Mul; break; 2053 case tok::slash: Opc = BinaryOperator::Div; break; 2054 case tok::percent: Opc = BinaryOperator::Rem; break; 2055 case tok::plus: Opc = BinaryOperator::Add; break; 2056 case tok::minus: Opc = BinaryOperator::Sub; break; 2057 case tok::lessless: Opc = BinaryOperator::Shl; break; 2058 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2059 case tok::lessequal: Opc = BinaryOperator::LE; break; 2060 case tok::less: Opc = BinaryOperator::LT; break; 2061 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2062 case tok::greater: Opc = BinaryOperator::GT; break; 2063 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2064 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2065 case tok::amp: Opc = BinaryOperator::And; break; 2066 case tok::caret: Opc = BinaryOperator::Xor; break; 2067 case tok::pipe: Opc = BinaryOperator::Or; break; 2068 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2069 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2070 case tok::equal: Opc = BinaryOperator::Assign; break; 2071 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2072 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2073 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2074 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2075 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2076 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2077 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2078 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2079 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2080 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2081 case tok::comma: Opc = BinaryOperator::Comma; break; 2082 } 2083 return Opc; 2084} 2085 2086static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2087 tok::TokenKind Kind) { 2088 UnaryOperator::Opcode Opc; 2089 switch (Kind) { 2090 default: assert(0 && "Unknown unary op!"); 2091 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2092 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2093 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2094 case tok::star: Opc = UnaryOperator::Deref; break; 2095 case tok::plus: Opc = UnaryOperator::Plus; break; 2096 case tok::minus: Opc = UnaryOperator::Minus; break; 2097 case tok::tilde: Opc = UnaryOperator::Not; break; 2098 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2099 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break; 2100 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break; 2101 case tok::kw___real: Opc = UnaryOperator::Real; break; 2102 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2103 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2104 } 2105 return Opc; 2106} 2107 2108// Binary Operators. 'Tok' is the token for the operator. 2109Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind, 2110 ExprTy *LHS, ExprTy *RHS) { 2111 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2112 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2113 2114 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2115 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2116 2117 QualType ResultTy; // Result type of the binary operator. 2118 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2119 2120 switch (Opc) { 2121 default: 2122 assert(0 && "Unknown binary expr!"); 2123 case BinaryOperator::Assign: 2124 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType()); 2125 break; 2126 case BinaryOperator::Mul: 2127 case BinaryOperator::Div: 2128 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc); 2129 break; 2130 case BinaryOperator::Rem: 2131 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc); 2132 break; 2133 case BinaryOperator::Add: 2134 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc); 2135 break; 2136 case BinaryOperator::Sub: 2137 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc); 2138 break; 2139 case BinaryOperator::Shl: 2140 case BinaryOperator::Shr: 2141 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc); 2142 break; 2143 case BinaryOperator::LE: 2144 case BinaryOperator::LT: 2145 case BinaryOperator::GE: 2146 case BinaryOperator::GT: 2147 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true); 2148 break; 2149 case BinaryOperator::EQ: 2150 case BinaryOperator::NE: 2151 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false); 2152 break; 2153 case BinaryOperator::And: 2154 case BinaryOperator::Xor: 2155 case BinaryOperator::Or: 2156 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc); 2157 break; 2158 case BinaryOperator::LAnd: 2159 case BinaryOperator::LOr: 2160 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc); 2161 break; 2162 case BinaryOperator::MulAssign: 2163 case BinaryOperator::DivAssign: 2164 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true); 2165 if (!CompTy.isNull()) 2166 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2167 break; 2168 case BinaryOperator::RemAssign: 2169 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true); 2170 if (!CompTy.isNull()) 2171 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2172 break; 2173 case BinaryOperator::AddAssign: 2174 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true); 2175 if (!CompTy.isNull()) 2176 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2177 break; 2178 case BinaryOperator::SubAssign: 2179 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true); 2180 if (!CompTy.isNull()) 2181 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2182 break; 2183 case BinaryOperator::ShlAssign: 2184 case BinaryOperator::ShrAssign: 2185 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true); 2186 if (!CompTy.isNull()) 2187 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2188 break; 2189 case BinaryOperator::AndAssign: 2190 case BinaryOperator::XorAssign: 2191 case BinaryOperator::OrAssign: 2192 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true); 2193 if (!CompTy.isNull()) 2194 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2195 break; 2196 case BinaryOperator::Comma: 2197 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc); 2198 break; 2199 } 2200 if (ResultTy.isNull()) 2201 return true; 2202 if (CompTy.isNull()) 2203 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc); 2204 else 2205 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc); 2206} 2207 2208// Unary Operators. 'Tok' is the token for the operator. 2209Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op, 2210 ExprTy *input) { 2211 Expr *Input = (Expr*)input; 2212 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 2213 QualType resultType; 2214 switch (Opc) { 2215 default: 2216 assert(0 && "Unimplemented unary expr!"); 2217 case UnaryOperator::PreInc: 2218 case UnaryOperator::PreDec: 2219 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 2220 break; 2221 case UnaryOperator::AddrOf: 2222 resultType = CheckAddressOfOperand(Input, OpLoc); 2223 break; 2224 case UnaryOperator::Deref: 2225 DefaultFunctionArrayConversion(Input); 2226 resultType = CheckIndirectionOperand(Input, OpLoc); 2227 break; 2228 case UnaryOperator::Plus: 2229 case UnaryOperator::Minus: 2230 UsualUnaryConversions(Input); 2231 resultType = Input->getType(); 2232 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1 2233 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2234 resultType.getAsString()); 2235 break; 2236 case UnaryOperator::Not: // bitwise complement 2237 UsualUnaryConversions(Input); 2238 resultType = Input->getType(); 2239 // C99 6.5.3.3p1. We allow complex as a GCC extension. 2240 if (!resultType->isIntegerType()) { 2241 if (resultType->isComplexType()) 2242 // C99 does not support '~' for complex conjugation. 2243 Diag(OpLoc, diag::ext_integer_complement_complex, 2244 resultType.getAsString()); 2245 else 2246 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2247 resultType.getAsString()); 2248 } 2249 break; 2250 case UnaryOperator::LNot: // logical negation 2251 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 2252 DefaultFunctionArrayConversion(Input); 2253 resultType = Input->getType(); 2254 if (!resultType->isScalarType()) // C99 6.5.3.3p1 2255 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2256 resultType.getAsString()); 2257 // LNot always has type int. C99 6.5.3.3p5. 2258 resultType = Context.IntTy; 2259 break; 2260 case UnaryOperator::SizeOf: 2261 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true); 2262 break; 2263 case UnaryOperator::AlignOf: 2264 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false); 2265 break; 2266 case UnaryOperator::Real: 2267 case UnaryOperator::Imag: 2268 resultType = CheckRealImagOperand(Input, OpLoc); 2269 break; 2270 case UnaryOperator::Extension: 2271 resultType = Input->getType(); 2272 break; 2273 } 2274 if (resultType.isNull()) 2275 return true; 2276 return new UnaryOperator(Input, Opc, resultType, OpLoc); 2277} 2278 2279/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2280Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 2281 SourceLocation LabLoc, 2282 IdentifierInfo *LabelII) { 2283 // Look up the record for this label identifier. 2284 LabelStmt *&LabelDecl = LabelMap[LabelII]; 2285 2286 // If we haven't seen this label yet, create a forward reference. 2287 if (LabelDecl == 0) 2288 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 2289 2290 // Create the AST node. The address of a label always has type 'void*'. 2291 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 2292 Context.getPointerType(Context.VoidTy)); 2293} 2294 2295Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 2296 SourceLocation RPLoc) { // "({..})" 2297 Stmt *SubStmt = static_cast<Stmt*>(substmt); 2298 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 2299 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 2300 2301 // FIXME: there are a variety of strange constraints to enforce here, for 2302 // example, it is not possible to goto into a stmt expression apparently. 2303 // More semantic analysis is needed. 2304 2305 // FIXME: the last statement in the compount stmt has its value used. We 2306 // should not warn about it being unused. 2307 2308 // If there are sub stmts in the compound stmt, take the type of the last one 2309 // as the type of the stmtexpr. 2310 QualType Ty = Context.VoidTy; 2311 2312 if (!Compound->body_empty()) 2313 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back())) 2314 Ty = LastExpr->getType(); 2315 2316 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 2317} 2318 2319Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 2320 SourceLocation TypeLoc, 2321 TypeTy *argty, 2322 OffsetOfComponent *CompPtr, 2323 unsigned NumComponents, 2324 SourceLocation RPLoc) { 2325 QualType ArgTy = QualType::getFromOpaquePtr(argty); 2326 assert(!ArgTy.isNull() && "Missing type argument!"); 2327 2328 // We must have at least one component that refers to the type, and the first 2329 // one is known to be a field designator. Verify that the ArgTy represents 2330 // a struct/union/class. 2331 if (!ArgTy->isRecordType()) 2332 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString()); 2333 2334 // Otherwise, create a compound literal expression as the base, and 2335 // iteratively process the offsetof designators. 2336 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 2337 2338 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 2339 // GCC extension, diagnose them. 2340 if (NumComponents != 1) 2341 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator, 2342 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd)); 2343 2344 for (unsigned i = 0; i != NumComponents; ++i) { 2345 const OffsetOfComponent &OC = CompPtr[i]; 2346 if (OC.isBrackets) { 2347 // Offset of an array sub-field. TODO: Should we allow vector elements? 2348 const ArrayType *AT = Res->getType()->getAsArrayType(); 2349 if (!AT) { 2350 delete Res; 2351 return Diag(OC.LocEnd, diag::err_offsetof_array_type, 2352 Res->getType().getAsString()); 2353 } 2354 2355 // FIXME: C++: Verify that operator[] isn't overloaded. 2356 2357 // C99 6.5.2.1p1 2358 Expr *Idx = static_cast<Expr*>(OC.U.E); 2359 if (!Idx->getType()->isIntegerType()) 2360 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript, 2361 Idx->getSourceRange()); 2362 2363 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 2364 continue; 2365 } 2366 2367 const RecordType *RC = Res->getType()->getAsRecordType(); 2368 if (!RC) { 2369 delete Res; 2370 return Diag(OC.LocEnd, diag::err_offsetof_record_type, 2371 Res->getType().getAsString()); 2372 } 2373 2374 // Get the decl corresponding to this. 2375 RecordDecl *RD = RC->getDecl(); 2376 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 2377 if (!MemberDecl) 2378 return Diag(BuiltinLoc, diag::err_typecheck_no_member, 2379 OC.U.IdentInfo->getName(), 2380 SourceRange(OC.LocStart, OC.LocEnd)); 2381 2382 // FIXME: C++: Verify that MemberDecl isn't a static field. 2383 // FIXME: Verify that MemberDecl isn't a bitfield. 2384 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 2385 // matter here. 2386 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType()); 2387 } 2388 2389 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 2390 BuiltinLoc); 2391} 2392 2393 2394Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 2395 TypeTy *arg1, TypeTy *arg2, 2396 SourceLocation RPLoc) { 2397 QualType argT1 = QualType::getFromOpaquePtr(arg1); 2398 QualType argT2 = QualType::getFromOpaquePtr(arg2); 2399 2400 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 2401 2402 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 2403} 2404 2405Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 2406 ExprTy *expr1, ExprTy *expr2, 2407 SourceLocation RPLoc) { 2408 Expr *CondExpr = static_cast<Expr*>(cond); 2409 Expr *LHSExpr = static_cast<Expr*>(expr1); 2410 Expr *RHSExpr = static_cast<Expr*>(expr2); 2411 2412 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 2413 2414 // The conditional expression is required to be a constant expression. 2415 llvm::APSInt condEval(32); 2416 SourceLocation ExpLoc; 2417 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 2418 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant, 2419 CondExpr->getSourceRange()); 2420 2421 // If the condition is > zero, then the AST type is the same as the LSHExpr. 2422 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 2423 RHSExpr->getType(); 2424 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 2425} 2426 2427/// ExprsMatchFnType - return true if the Exprs in array Args have 2428/// QualTypes that match the QualTypes of the arguments of the FnType. 2429/// The number of arguments has already been validated to match the number of 2430/// arguments in FnType. 2431static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) { 2432 unsigned NumParams = FnType->getNumArgs(); 2433 for (unsigned i = 0; i != NumParams; ++i) { 2434 QualType ExprTy = Args[i]->getType().getCanonicalType(); 2435 QualType ParmTy = FnType->getArgType(i).getCanonicalType(); 2436 2437 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 2438 return false; 2439 } 2440 return true; 2441} 2442 2443Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 2444 SourceLocation *CommaLocs, 2445 SourceLocation BuiltinLoc, 2446 SourceLocation RParenLoc) { 2447 // __builtin_overload requires at least 2 arguments 2448 if (NumArgs < 2) 2449 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2450 SourceRange(BuiltinLoc, RParenLoc)); 2451 2452 // The first argument is required to be a constant expression. It tells us 2453 // the number of arguments to pass to each of the functions to be overloaded. 2454 Expr **Args = reinterpret_cast<Expr**>(args); 2455 Expr *NParamsExpr = Args[0]; 2456 llvm::APSInt constEval(32); 2457 SourceLocation ExpLoc; 2458 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 2459 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2460 NParamsExpr->getSourceRange()); 2461 2462 // Verify that the number of parameters is > 0 2463 unsigned NumParams = constEval.getZExtValue(); 2464 if (NumParams == 0) 2465 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2466 NParamsExpr->getSourceRange()); 2467 // Verify that we have at least 1 + NumParams arguments to the builtin. 2468 if ((NumParams + 1) > NumArgs) 2469 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2470 SourceRange(BuiltinLoc, RParenLoc)); 2471 2472 // Figure out the return type, by matching the args to one of the functions 2473 // listed after the parameters. 2474 OverloadExpr *OE = 0; 2475 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 2476 // UsualUnaryConversions will convert the function DeclRefExpr into a 2477 // pointer to function. 2478 Expr *Fn = UsualUnaryConversions(Args[i]); 2479 FunctionTypeProto *FnType = 0; 2480 if (const PointerType *PT = Fn->getType()->getAsPointerType()) { 2481 QualType PointeeType = PT->getPointeeType().getCanonicalType(); 2482 FnType = dyn_cast<FunctionTypeProto>(PointeeType); 2483 } 2484 2485 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 2486 // parameters, and the number of parameters must match the value passed to 2487 // the builtin. 2488 if (!FnType || (FnType->getNumArgs() != NumParams)) 2489 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype, 2490 Fn->getSourceRange()); 2491 2492 // Scan the parameter list for the FunctionType, checking the QualType of 2493 // each parameter against the QualTypes of the arguments to the builtin. 2494 // If they match, return a new OverloadExpr. 2495 if (ExprsMatchFnType(Args+1, FnType)) { 2496 if (OE) 2497 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match, 2498 OE->getFn()->getSourceRange()); 2499 // Remember our match, and continue processing the remaining arguments 2500 // to catch any errors. 2501 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(), 2502 BuiltinLoc, RParenLoc); 2503 } 2504 } 2505 // Return the newly created OverloadExpr node, if we succeded in matching 2506 // exactly one of the candidate functions. 2507 if (OE) 2508 return OE; 2509 2510 // If we didn't find a matching function Expr in the __builtin_overload list 2511 // the return an error. 2512 std::string typeNames; 2513 for (unsigned i = 0; i != NumParams; ++i) { 2514 if (i != 0) typeNames += ", "; 2515 typeNames += Args[i+1]->getType().getAsString(); 2516 } 2517 2518 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames, 2519 SourceRange(BuiltinLoc, RParenLoc)); 2520} 2521 2522Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 2523 ExprTy *expr, TypeTy *type, 2524 SourceLocation RPLoc) { 2525 Expr *E = static_cast<Expr*>(expr); 2526 QualType T = QualType::getFromOpaquePtr(type); 2527 2528 InitBuiltinVaListType(); 2529 2530 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType()) 2531 != Compatible) 2532 return Diag(E->getLocStart(), 2533 diag::err_first_argument_to_va_arg_not_of_type_va_list, 2534 E->getType().getAsString(), 2535 E->getSourceRange()); 2536 2537 // FIXME: Warn if a non-POD type is passed in. 2538 2539 return new VAArgExpr(BuiltinLoc, E, T, RPLoc); 2540} 2541 2542bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 2543 SourceLocation Loc, 2544 QualType DstType, QualType SrcType, 2545 Expr *SrcExpr, const char *Flavor) { 2546 // Decode the result (notice that AST's are still created for extensions). 2547 bool isInvalid = false; 2548 unsigned DiagKind; 2549 switch (ConvTy) { 2550 default: assert(0 && "Unknown conversion type"); 2551 case Compatible: return false; 2552 case PointerToInt: 2553 DiagKind = diag::ext_typecheck_convert_pointer_int; 2554 break; 2555 case IntToPointer: 2556 DiagKind = diag::ext_typecheck_convert_int_pointer; 2557 break; 2558 case IncompatiblePointer: 2559 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 2560 break; 2561 case FunctionVoidPointer: 2562 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 2563 break; 2564 case CompatiblePointerDiscardsQualifiers: 2565 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 2566 break; 2567 case Incompatible: 2568 DiagKind = diag::err_typecheck_convert_incompatible; 2569 isInvalid = true; 2570 break; 2571 } 2572 2573 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor, 2574 SrcExpr->getSourceRange()); 2575 return isInvalid; 2576} 2577