SemaType.cpp revision ecb81f28cb279b7d8e84296445a4131fa80b69a9
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 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 type-related semantic analysis. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/Expr.h" 18#include "clang/Parse/DeclSpec.h" 19using namespace clang; 20 21/// \brief Convert the specified declspec to the appropriate type 22/// object. 23/// \param DS the declaration specifiers 24/// \returns The type described by the declaration specifiers, or NULL 25/// if there was an error. 26QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) { 27 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 28 // checking. 29 QualType Result; 30 31 switch (DS.getTypeSpecType()) { 32 default: assert(0 && "Unknown TypeSpecType!"); 33 case DeclSpec::TST_void: 34 Result = Context.VoidTy; 35 break; 36 case DeclSpec::TST_char: 37 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 38 Result = Context.CharTy; 39 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 40 Result = Context.SignedCharTy; 41 else { 42 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 43 "Unknown TSS value"); 44 Result = Context.UnsignedCharTy; 45 } 46 break; 47 case DeclSpec::TST_wchar: 48 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 49 Result = Context.WCharTy; 50 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 51 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 52 << DS.getSpecifierName(DS.getTypeSpecType()); 53 Result = Context.getSignedWCharType(); 54 } else { 55 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 56 "Unknown TSS value"); 57 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 58 << DS.getSpecifierName(DS.getTypeSpecType()); 59 Result = Context.getUnsignedWCharType(); 60 } 61 break; 62 case DeclSpec::TST_unspecified: 63 // "<proto1,proto2>" is an objc qualified ID with a missing id. 64 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 65 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, 66 DS.getNumProtocolQualifiers()); 67 break; 68 } 69 70 // Unspecified typespec defaults to int in C90. However, the C90 grammar 71 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 72 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 73 // Note that the one exception to this is function definitions, which are 74 // allowed to be completely missing a declspec. This is handled in the 75 // parser already though by it pretending to have seen an 'int' in this 76 // case. 77 if (getLangOptions().ImplicitInt) { 78 if ((DS.getParsedSpecifiers() & (DeclSpec::PQ_StorageClassSpecifier | 79 DeclSpec::PQ_TypeSpecifier | 80 DeclSpec::PQ_TypeQualifier)) == 0) 81 Diag(DS.getSourceRange().getBegin(), diag::ext_missing_declspec); 82 } else { 83 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 84 // "At least one type specifier shall be given in the declaration 85 // specifiers in each declaration, and in the specifier-qualifier list in 86 // each struct declaration and type name." 87 // FIXME: this should be a hard error in C++ 88 if (!DS.hasTypeSpecifier()) 89 Diag(DS.getSourceRange().getBegin(), diag::ext_missing_type_specifier); 90 } 91 92 // FALL THROUGH. 93 case DeclSpec::TST_int: { 94 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 95 switch (DS.getTypeSpecWidth()) { 96 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 97 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 98 case DeclSpec::TSW_long: Result = Context.LongTy; break; 99 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break; 100 } 101 } else { 102 switch (DS.getTypeSpecWidth()) { 103 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 104 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 105 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 106 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break; 107 } 108 } 109 break; 110 } 111 case DeclSpec::TST_float: Result = Context.FloatTy; break; 112 case DeclSpec::TST_double: 113 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 114 Result = Context.LongDoubleTy; 115 else 116 Result = Context.DoubleTy; 117 break; 118 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 119 case DeclSpec::TST_decimal32: // _Decimal32 120 case DeclSpec::TST_decimal64: // _Decimal64 121 case DeclSpec::TST_decimal128: // _Decimal128 122 assert(0 && "FIXME: GNU decimal extensions not supported yet!"); 123 case DeclSpec::TST_class: 124 case DeclSpec::TST_enum: 125 case DeclSpec::TST_union: 126 case DeclSpec::TST_struct: { 127 Decl *D = static_cast<Decl *>(DS.getTypeRep()); 128 assert(D && "Didn't get a decl for a class/enum/union/struct?"); 129 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 130 DS.getTypeSpecSign() == 0 && 131 "Can't handle qualifiers on typedef names yet!"); 132 // TypeQuals handled by caller. 133 Result = Context.getTypeDeclType(cast<TypeDecl>(D)); 134 break; 135 } 136 case DeclSpec::TST_typename: { 137 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 138 DS.getTypeSpecSign() == 0 && 139 "Can't handle qualifiers on typedef names yet!"); 140 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 141 142 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 143 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so 144 // we have this "hack" for now... 145 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType()) 146 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(), 147 (ObjCProtocolDecl**)PQ, 148 DS.getNumProtocolQualifiers()); 149 else if (Result == Context.getObjCIdType()) 150 // id<protocol-list> 151 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, 152 DS.getNumProtocolQualifiers()); 153 } 154 // TypeQuals handled by caller. 155 break; 156 } 157 case DeclSpec::TST_typeofType: 158 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 159 assert(!Result.isNull() && "Didn't get a type for typeof?"); 160 // TypeQuals handled by caller. 161 Result = Context.getTypeOfType(Result); 162 break; 163 case DeclSpec::TST_typeofExpr: { 164 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 165 assert(E && "Didn't get an expression for typeof?"); 166 // TypeQuals handled by caller. 167 Result = Context.getTypeOfExpr(E); 168 break; 169 } 170 } 171 172 // Handle complex types. 173 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 174 if (getLangOptions().Freestanding) 175 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 176 Result = Context.getComplexType(Result); 177 } 178 179 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 180 "FIXME: imaginary types not supported yet!"); 181 182 // See if there are any attributes on the declspec that apply to the type (as 183 // opposed to the decl). 184 if (const AttributeList *AL = DS.getAttributes()) 185 ProcessTypeAttributeList(Result, AL); 186 187 // Apply const/volatile/restrict qualifiers to T. 188 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 189 190 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 191 // or incomplete types shall not be restrict-qualified." C++ also allows 192 // restrict-qualified references. 193 if (TypeQuals & QualType::Restrict) { 194 if (const PointerLikeType *PT = Result->getAsPointerLikeType()) { 195 QualType EltTy = PT->getPointeeType(); 196 197 // If we have a pointer or reference, the pointee must have an object or 198 // incomplete type. 199 if (!EltTy->isIncompleteOrObjectType()) { 200 Diag(DS.getRestrictSpecLoc(), 201 diag::err_typecheck_invalid_restrict_invalid_pointee) 202 << EltTy << DS.getSourceRange(); 203 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 204 } 205 } else { 206 Diag(DS.getRestrictSpecLoc(), 207 diag::err_typecheck_invalid_restrict_not_pointer) 208 << Result << DS.getSourceRange(); 209 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 210 } 211 } 212 213 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 214 // of a function type includes any type qualifiers, the behavior is 215 // undefined." 216 if (Result->isFunctionType() && TypeQuals) { 217 // Get some location to point at, either the C or V location. 218 SourceLocation Loc; 219 if (TypeQuals & QualType::Const) 220 Loc = DS.getConstSpecLoc(); 221 else { 222 assert((TypeQuals & QualType::Volatile) && 223 "Has CV quals but not C or V?"); 224 Loc = DS.getVolatileSpecLoc(); 225 } 226 Diag(Loc, diag::warn_typecheck_function_qualifiers) 227 << Result << DS.getSourceRange(); 228 } 229 230 // C++ [dcl.ref]p1: 231 // Cv-qualified references are ill-formed except when the 232 // cv-qualifiers are introduced through the use of a typedef 233 // (7.1.3) or of a template type argument (14.3), in which 234 // case the cv-qualifiers are ignored. 235 // FIXME: Shouldn't we be checking SCS_typedef here? 236 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 237 TypeQuals && Result->isReferenceType()) { 238 TypeQuals &= ~QualType::Const; 239 TypeQuals &= ~QualType::Volatile; 240 } 241 242 Result = Result.getQualifiedType(TypeQuals); 243 } 244 return Result; 245} 246 247/// GetTypeForDeclarator - Convert the type for the specified 248/// declarator to Type instances. Skip the outermost Skip type 249/// objects. 250QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) { 251 bool OmittedReturnType = false; 252 253 if (D.getContext() == Declarator::BlockLiteralContext 254 && Skip == 0 255 && !D.getDeclSpec().hasTypeSpecifier() 256 && (D.getNumTypeObjects() == 0 257 || (D.getNumTypeObjects() == 1 258 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) 259 OmittedReturnType = true; 260 261 // long long is a C99 feature. 262 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 263 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) 264 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); 265 266 // Determine the type of the declarator. Not all forms of declarator 267 // have a type. 268 QualType T; 269 switch (D.getKind()) { 270 case Declarator::DK_Abstract: 271 case Declarator::DK_Normal: 272 case Declarator::DK_Operator: { 273 const DeclSpec& DS = D.getDeclSpec(); 274 if (OmittedReturnType) 275 // We default to a dependent type initially. Can be modified by 276 // the first return statement. 277 T = Context.DependentTy; 278 else 279 T = ConvertDeclSpecToType(DS); 280 break; 281 } 282 283 case Declarator::DK_Constructor: 284 case Declarator::DK_Destructor: 285 case Declarator::DK_Conversion: 286 // Constructors and destructors don't have return types. Use 287 // "void" instead. Conversion operators will check their return 288 // types separately. 289 T = Context.VoidTy; 290 break; 291 } 292 293 // Walk the DeclTypeInfo, building the recursive type as we go. 294 // DeclTypeInfos are ordered from the identifier out, which is 295 // opposite of what we want :). 296 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { 297 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); 298 switch (DeclType.Kind) { 299 default: assert(0 && "Unknown decltype!"); 300 case DeclaratorChunk::BlockPointer: 301 if (DeclType.Cls.TypeQuals) 302 Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type); 303 if (!T.getTypePtr()->isFunctionType()) 304 Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type); 305 else 306 T = Context.getBlockPointerType(T); 307 break; 308 case DeclaratorChunk::Pointer: 309 if (T->isReferenceType()) { 310 // C++ 8.3.2p4: There shall be no ... pointers to references ... 311 Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference) 312 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 313 D.setInvalidType(true); 314 T = Context.IntTy; 315 } 316 317 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 318 // object or incomplete types shall not be restrict-qualified." 319 if ((DeclType.Ptr.TypeQuals & QualType::Restrict) && 320 !T->isIncompleteOrObjectType()) { 321 Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 322 << T; 323 DeclType.Ptr.TypeQuals &= ~QualType::Restrict; 324 } 325 326 // Apply the pointer typequals to the pointer object. 327 T = Context.getPointerType(T).getQualifiedType(DeclType.Ptr.TypeQuals); 328 break; 329 case DeclaratorChunk::Reference: { 330 // Whether we should suppress the creation of the reference. 331 bool SuppressReference = false; 332 if (T->isReferenceType()) { 333 // C++ [dcl.ref]p4: There shall be no references to references. 334 // 335 // According to C++ DR 106, references to references are only 336 // diagnosed when they are written directly (e.g., "int & &"), 337 // but not when they happen via a typedef: 338 // 339 // typedef int& intref; 340 // typedef intref& intref2; 341 // 342 // Parser::ParserDeclaratorInternal diagnoses the case where 343 // references are written directly; here, we handle the 344 // collapsing of references-to-references as described in C++ 345 // DR 106 and amended by C++ DR 540. 346 SuppressReference = true; 347 } 348 349 // C++ [dcl.ref]p1: 350 // A declarator that specifies the type “reference to cv void” 351 // is ill-formed. 352 if (T->isVoidType()) { 353 Diag(DeclType.Loc, diag::err_reference_to_void); 354 D.setInvalidType(true); 355 T = Context.IntTy; 356 } 357 358 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 359 // object or incomplete types shall not be restrict-qualified." 360 if (DeclType.Ref.HasRestrict && 361 !T->isIncompleteOrObjectType()) { 362 Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 363 << T; 364 DeclType.Ref.HasRestrict = false; 365 } 366 367 if (!SuppressReference) 368 T = Context.getReferenceType(T); 369 370 // Handle restrict on references. 371 if (DeclType.Ref.HasRestrict) 372 T.addRestrict(); 373 break; 374 } 375 case DeclaratorChunk::Array: { 376 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 377 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 378 ArrayType::ArraySizeModifier ASM; 379 if (ATI.isStar) 380 ASM = ArrayType::Star; 381 else if (ATI.hasStatic) 382 ASM = ArrayType::Static; 383 else 384 ASM = ArrayType::Normal; 385 386 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 387 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 388 if (DiagnoseIncompleteType(D.getIdentifierLoc(), T, 389 diag::err_illegal_decl_array_incomplete_type)) { 390 T = Context.IntTy; 391 D.setInvalidType(true); 392 } else if (T->isFunctionType()) { 393 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_functions) 394 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 395 T = Context.getPointerType(T); 396 D.setInvalidType(true); 397 } else if (const ReferenceType *RT = T->getAsReferenceType()) { 398 // C++ 8.3.2p4: There shall be no ... arrays of references ... 399 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_references) 400 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 401 T = RT->getPointeeType(); 402 D.setInvalidType(true); 403 } else if (const RecordType *EltTy = T->getAsRecordType()) { 404 // If the element type is a struct or union that contains a variadic 405 // array, accept it as a GNU extension: C99 6.7.2.1p2. 406 if (EltTy->getDecl()->hasFlexibleArrayMember()) 407 Diag(DeclType.Loc, diag::ext_flexible_array_in_array) << T; 408 } else if (T->isObjCInterfaceType()) { 409 Diag(DeclType.Loc, diag::warn_objc_array_of_interfaces) << T; 410 } 411 412 // C99 6.7.5.2p1: The size expression shall have integer type. 413 if (ArraySize && !ArraySize->getType()->isIntegerType()) { 414 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 415 << ArraySize->getType() << ArraySize->getSourceRange(); 416 D.setInvalidType(true); 417 ArraySize->Destroy(Context); 418 ATI.NumElts = ArraySize = 0; 419 } 420 llvm::APSInt ConstVal(32); 421 if (!ArraySize) { 422 T = Context.getIncompleteArrayType(T, ASM, ATI.TypeQuals); 423 } else if (ArraySize->isValueDependent()) { 424 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, ATI.TypeQuals); 425 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 426 !T->isConstantSizeType()) { 427 // Per C99, a variable array is an array with either a non-constant 428 // size or an element type that has a non-constant-size 429 T = Context.getVariableArrayType(T, ArraySize, ASM, ATI.TypeQuals); 430 } else { 431 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 432 // have a value greater than zero. 433 if (ConstVal.isSigned()) { 434 if (ConstVal.isNegative()) { 435 Diag(ArraySize->getLocStart(), 436 diag::err_typecheck_negative_array_size) 437 << ArraySize->getSourceRange(); 438 D.setInvalidType(true); 439 } else if (ConstVal == 0) { 440 // GCC accepts zero sized static arrays. 441 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) 442 << ArraySize->getSourceRange(); 443 } 444 } 445 T = Context.getConstantArrayType(T, ConstVal, ASM, ATI.TypeQuals); 446 } 447 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 448 if (!getLangOptions().C99) { 449 if (ArraySize && !ArraySize->isValueDependent() && 450 !ArraySize->isIntegerConstantExpr(Context)) 451 Diag(D.getIdentifierLoc(), diag::ext_vla); 452 else if (ASM != ArrayType::Normal || ATI.TypeQuals != 0) 453 Diag(D.getIdentifierLoc(), diag::ext_c99_array_usage); 454 } 455 break; 456 } 457 case DeclaratorChunk::Function: { 458 // If the function declarator has a prototype (i.e. it is not () and 459 // does not have a K&R-style identifier list), then the arguments are part 460 // of the type, otherwise the argument list is (). 461 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 462 463 // C99 6.7.5.3p1: The return type may not be a function or array type. 464 if (T->isArrayType() || T->isFunctionType()) { 465 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; 466 T = Context.IntTy; 467 D.setInvalidType(true); 468 } 469 470 if (FTI.NumArgs == 0) { 471 if (getLangOptions().CPlusPlus) { 472 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 473 // function takes no arguments. 474 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals); 475 } else { 476 // Simple void foo(), where the incoming T is the result type. 477 T = Context.getFunctionTypeNoProto(T); 478 } 479 } else if (FTI.ArgInfo[0].Param == 0) { 480 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 481 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 482 } else { 483 // Otherwise, we have a function with an argument list that is 484 // potentially variadic. 485 llvm::SmallVector<QualType, 16> ArgTys; 486 487 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 488 ParmVarDecl *Param = (ParmVarDecl *)FTI.ArgInfo[i].Param; 489 QualType ArgTy = Param->getType(); 490 assert(!ArgTy.isNull() && "Couldn't parse type?"); 491 // 492 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 493 // This matches the conversion that is done in 494 // Sema::ActOnParamDeclarator(). Without this conversion, the 495 // argument type in the function prototype *will not* match the 496 // type in ParmVarDecl (which makes the code generator unhappy). 497 // 498 // FIXME: We still apparently need the conversion in 499 // Sema::ActOnParamDeclarator(). This doesn't make any sense, since 500 // it should be driving off the type being created here. 501 // 502 // FIXME: If a source translation tool needs to see the original type, 503 // then we need to consider storing both types somewhere... 504 // 505 if (ArgTy->isArrayType()) { 506 ArgTy = Context.getArrayDecayedType(ArgTy); 507 } else if (ArgTy->isFunctionType()) 508 ArgTy = Context.getPointerType(ArgTy); 509 510 // Look for 'void'. void is allowed only as a single argument to a 511 // function with no other parameters (C99 6.7.5.3p10). We record 512 // int(void) as a FunctionTypeProto with an empty argument list. 513 else if (ArgTy->isVoidType()) { 514 // If this is something like 'float(int, void)', reject it. 'void' 515 // is an incomplete type (C99 6.2.5p19) and function decls cannot 516 // have arguments of incomplete type. 517 if (FTI.NumArgs != 1 || FTI.isVariadic) { 518 Diag(DeclType.Loc, diag::err_void_only_param); 519 ArgTy = Context.IntTy; 520 Param->setType(ArgTy); 521 } else if (FTI.ArgInfo[i].Ident) { 522 // Reject, but continue to parse 'int(void abc)'. 523 Diag(FTI.ArgInfo[i].IdentLoc, 524 diag::err_param_with_void_type); 525 ArgTy = Context.IntTy; 526 Param->setType(ArgTy); 527 } else { 528 // Reject, but continue to parse 'float(const void)'. 529 if (ArgTy.getCVRQualifiers()) 530 Diag(DeclType.Loc, diag::err_void_param_qualified); 531 532 // Do not add 'void' to the ArgTys list. 533 break; 534 } 535 } else if (!FTI.hasPrototype) { 536 if (ArgTy->isPromotableIntegerType()) { 537 ArgTy = Context.IntTy; 538 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { 539 if (BTy->getKind() == BuiltinType::Float) 540 ArgTy = Context.DoubleTy; 541 } 542 } 543 544 ArgTys.push_back(ArgTy); 545 } 546 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 547 FTI.isVariadic, FTI.TypeQuals); 548 } 549 break; 550 } 551 case DeclaratorChunk::MemberPointer: 552 // The scope spec must refer to a class, or be dependent. 553 DeclContext *DC = static_cast<DeclContext*>( 554 DeclType.Mem.Scope().getScopeRep()); 555 QualType ClsType; 556 // FIXME: Extend for dependent types when it's actually supported. 557 // See ActOnCXXNestedNameSpecifier. 558 if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) { 559 ClsType = Context.getTagDeclType(RD); 560 } else { 561 if (DC) { 562 Diag(DeclType.Mem.Scope().getBeginLoc(), 563 diag::err_illegal_decl_mempointer_in_nonclass) 564 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 565 << DeclType.Mem.Scope().getRange(); 566 } 567 D.setInvalidType(true); 568 ClsType = Context.IntTy; 569 } 570 571 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 572 // with reference type, or "cv void." 573 if (T->isReferenceType()) { 574 Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference) 575 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 576 D.setInvalidType(true); 577 T = Context.IntTy; 578 } 579 if (T->isVoidType()) { 580 Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void) 581 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 582 T = Context.IntTy; 583 } 584 585 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 586 // object or incomplete types shall not be restrict-qualified." 587 if ((DeclType.Mem.TypeQuals & QualType::Restrict) && 588 !T->isIncompleteOrObjectType()) { 589 Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 590 << T; 591 DeclType.Mem.TypeQuals &= ~QualType::Restrict; 592 } 593 594 T = Context.getMemberPointerType(T, ClsType.getTypePtr()). 595 getQualifiedType(DeclType.Mem.TypeQuals); 596 597 break; 598 } 599 600 // See if there are any attributes on this declarator chunk. 601 if (const AttributeList *AL = DeclType.getAttrs()) 602 ProcessTypeAttributeList(T, AL); 603 } 604 605 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 606 const FunctionTypeProto *FnTy = T->getAsFunctionTypeProto(); 607 assert(FnTy && "Why oh why is there not a FunctionTypeProto here ?"); 608 609 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 610 // for a nonstatic member function, the function type to which a pointer 611 // to member refers, or the top-level function type of a function typedef 612 // declaration. 613 if (FnTy->getTypeQuals() != 0 && 614 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 615 ((D.getContext() != Declarator::MemberContext && 616 (!D.getCXXScopeSpec().isSet() || 617 !static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep()) 618 ->isRecord())) || 619 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 620 if (D.isFunctionDeclarator()) 621 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 622 else 623 Diag(D.getIdentifierLoc(), 624 diag::err_invalid_qualified_typedef_function_type_use); 625 626 // Strip the cv-quals from the type. 627 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 628 FnTy->getNumArgs(), FnTy->isVariadic(), 0); 629 } 630 } 631 632 // If there were any type attributes applied to the decl itself (not the 633 // type, apply the type attribute to the type!) 634 if (const AttributeList *Attrs = D.getAttributes()) 635 ProcessTypeAttributeList(T, Attrs); 636 637 return T; 638} 639 640/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition 641/// declarator 642QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) { 643 ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(static_cast<Decl *>(D)); 644 QualType T = MDecl->getResultType(); 645 llvm::SmallVector<QualType, 16> ArgTys; 646 647 // Add the first two invisible argument types for self and _cmd. 648 if (MDecl->isInstanceMethod()) { 649 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); 650 selfTy = Context.getPointerType(selfTy); 651 ArgTys.push_back(selfTy); 652 } 653 else 654 ArgTys.push_back(Context.getObjCIdType()); 655 ArgTys.push_back(Context.getObjCSelType()); 656 657 for (int i = 0, e = MDecl->getNumParams(); i != e; ++i) { 658 ParmVarDecl *PDecl = MDecl->getParamDecl(i); 659 QualType ArgTy = PDecl->getType(); 660 assert(!ArgTy.isNull() && "Couldn't parse type?"); 661 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 662 // This matches the conversion that is done in 663 // Sema::ActOnParamDeclarator(). 664 if (ArgTy->isArrayType()) 665 ArgTy = Context.getArrayDecayedType(ArgTy); 666 else if (ArgTy->isFunctionType()) 667 ArgTy = Context.getPointerType(ArgTy); 668 ArgTys.push_back(ArgTy); 669 } 670 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 671 MDecl->isVariadic(), 0); 672 return T; 673} 674 675/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 676/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 677/// they point to and return true. If T1 and T2 aren't pointer types 678/// or pointer-to-member types, or if they are not similar at this 679/// level, returns false and leaves T1 and T2 unchanged. Top-level 680/// qualifiers on T1 and T2 are ignored. This function will typically 681/// be called in a loop that successively "unwraps" pointer and 682/// pointer-to-member types to compare them at each level. 683bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 684 const PointerType *T1PtrType = T1->getAsPointerType(), 685 *T2PtrType = T2->getAsPointerType(); 686 if (T1PtrType && T2PtrType) { 687 T1 = T1PtrType->getPointeeType(); 688 T2 = T2PtrType->getPointeeType(); 689 return true; 690 } 691 692 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), 693 *T2MPType = T2->getAsMemberPointerType(); 694 if (T1MPType && T2MPType && 695 Context.getCanonicalType(T1MPType->getClass()) == 696 Context.getCanonicalType(T2MPType->getClass())) { 697 T1 = T1MPType->getPointeeType(); 698 T2 = T2MPType->getPointeeType(); 699 return true; 700 } 701 return false; 702} 703 704Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 705 // C99 6.7.6: Type names have no identifier. This is already validated by 706 // the parser. 707 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 708 709 QualType T = GetTypeForDeclarator(D, S); 710 711 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 712 713 // Check that there are no default arguments (C++ only). 714 if (getLangOptions().CPlusPlus) 715 CheckExtraCXXDefaultArguments(D); 716 717 // In this context, we *do not* check D.getInvalidType(). If the declarator 718 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 719 // though it will not reflect the user specified type. 720 return T.getAsOpaquePtr(); 721} 722 723 724 725//===----------------------------------------------------------------------===// 726// Type Attribute Processing 727//===----------------------------------------------------------------------===// 728 729/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 730/// specified type. The attribute contains 1 argument, the id of the address 731/// space for the type. 732static void HandleAddressSpaceTypeAttribute(QualType &Type, 733 const AttributeList &Attr, Sema &S){ 734 // If this type is already address space qualified, reject it. 735 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 736 // for two or more different address spaces." 737 if (Type.getAddressSpace()) { 738 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 739 return; 740 } 741 742 // Check the attribute arguments. 743 if (Attr.getNumArgs() != 1) { 744 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 745 return; 746 } 747 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 748 llvm::APSInt addrSpace(32); 749 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 750 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 751 << ASArgExpr->getSourceRange(); 752 return; 753 } 754 755 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 756 Type = S.Context.getASQualType(Type, ASIdx); 757} 758 759void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { 760 // Scan through and apply attributes to this type where it makes sense. Some 761 // attributes (such as __address_space__, __vector_size__, etc) apply to the 762 // type, but others can be present in the type specifiers even though they 763 // apply to the decl. Here we apply type attributes and ignore the rest. 764 for (; AL; AL = AL->getNext()) { 765 // If this is an attribute we can handle, do so now, otherwise, add it to 766 // the LeftOverAttrs list for rechaining. 767 switch (AL->getKind()) { 768 default: break; 769 case AttributeList::AT_address_space: 770 HandleAddressSpaceTypeAttribute(Result, *AL, *this); 771 break; 772 } 773 } 774} 775 776/// @brief If the type T is incomplete and cannot be completed, 777/// produce a suitable diagnostic. 778/// 779/// This routine checks whether the type @p T is complete in any 780/// context where a complete type is required. If @p T is a complete 781/// type, returns false. If @p T is incomplete, issues the diagnostic 782/// @p diag (giving it the type @p T) and returns true. 783/// 784/// @param Loc The location in the source that the incomplete type 785/// diagnostic should refer to. 786/// 787/// @param T The type that this routine is examining for completeness. 788/// 789/// @param diag The diagnostic value (e.g., 790/// @c diag::err_typecheck_decl_incomplete_type) that will be used 791/// for the error message if @p T is incomplete. 792/// 793/// @param Range1 An optional range in the source code that will be a 794/// part of the "incomplete type" error message. 795/// 796/// @param Range2 An optional range in the source code that will be a 797/// part of the "incomplete type" error message. 798/// 799/// @param PrintType If non-NULL, the type that should be printed 800/// instead of @p T. This parameter should be used when the type that 801/// we're checking for incompleteness isn't the type that should be 802/// displayed to the user, e.g., when T is a type and PrintType is a 803/// pointer to T. 804/// 805/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 806/// @c false otherwise. 807/// 808/// @todo When Clang gets proper support for C++ templates, this 809/// routine will also be able perform template instantiation when @p T 810/// is a class template specialization. 811bool Sema::DiagnoseIncompleteType(SourceLocation Loc, QualType T, unsigned diag, 812 SourceRange Range1, SourceRange Range2, 813 QualType PrintType) { 814 // If we have a complete type, we're done. 815 if (!T->isIncompleteType()) 816 return false; 817 818 if (PrintType.isNull()) 819 PrintType = T; 820 821 // We have an incomplete type. Produce a diagnostic. 822 Diag(Loc, diag) << PrintType << Range1 << Range2; 823 824 // If the type was a forward declaration of a class/struct/union 825 // type, produce 826 const TagType *Tag = 0; 827 if (const RecordType *Record = T->getAsRecordType()) 828 Tag = Record; 829 else if (const EnumType *Enum = T->getAsEnumType()) 830 Tag = Enum; 831 832 if (Tag && !Tag->getDecl()->isInvalidDecl()) 833 Diag(Tag->getDecl()->getLocation(), 834 Tag->isBeingDefined() ? diag::note_type_being_defined 835 : diag::note_forward_declaration) 836 << QualType(Tag, 0); 837 838 return true; 839} 840