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/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/Parse/DeclSpec.h"
20 using namespace clang;
21 
22 /// \brief Perform adjustment on the parameter type of a function.
23 ///
24 /// This routine adjusts the given parameter type @p T to the actual
25 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
26 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
27 QualType Sema::adjustParameterType(QualType T) {
28   // C99 6.7.5.3p7:
29   if (T->isArrayType()) {
30     // C99 6.7.5.3p7:
31     //   A declaration of a parameter as "array of type" shall be
32     //   adjusted to "qualified pointer to type", where the type
33     //   qualifiers (if any) are those specified within the [ and ] of
34     //   the array type derivation.
35     return Context.getArrayDecayedType(T);
36   } else if (T->isFunctionType())
37     // C99 6.7.5.3p8:
38     //   A declaration of a parameter as "function returning type"
39     //   shall be adjusted to "pointer to function returning type", as
40     //   in 6.3.2.1.
41     return Context.getPointerType(T);
42 
43   return T;
44 }
45 
46 /// \brief Convert the specified declspec to the appropriate type
47 /// object.
48 /// \param DS  the declaration specifiers
49 /// \param DeclLoc The location of the declarator identifier or invalid if none.
50 /// \returns The type described by the declaration specifiers.  This function
51 /// never returns null.
52 QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
53                                      SourceLocation DeclLoc,
54                                      bool &isInvalid) {
55   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
56   // checking.
57   QualType Result;
58 
59   switch (DS.getTypeSpecType()) {
60   case DeclSpec::TST_void:
61     Result = Context.VoidTy;
62     break;
63   case DeclSpec::TST_char:
64     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
65       Result = Context.CharTy;
66     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
67       Result = Context.SignedCharTy;
68     else {
69       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
70              "Unknown TSS value");
71       Result = Context.UnsignedCharTy;
72     }
73     break;
74   case DeclSpec::TST_wchar:
75     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
76       Result = Context.WCharTy;
77     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
78       Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
79         << DS.getSpecifierName(DS.getTypeSpecType());
80       Result = Context.getSignedWCharType();
81     } else {
82       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
83         "Unknown TSS value");
84       Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
85         << DS.getSpecifierName(DS.getTypeSpecType());
86       Result = Context.getUnsignedWCharType();
87     }
88     break;
89   case DeclSpec::TST_unspecified:
90     // "<proto1,proto2>" is an objc qualified ID with a missing id.
91     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
92       Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ,
93                                                 DS.getNumProtocolQualifiers());
94       break;
95     }
96 
97     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
98     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
99     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
100     // Note that the one exception to this is function definitions, which are
101     // allowed to be completely missing a declspec.  This is handled in the
102     // parser already though by it pretending to have seen an 'int' in this
103     // case.
104     if (getLangOptions().ImplicitInt) {
105       // In C89 mode, we only warn if there is a completely missing declspec
106       // when one is not allowed.
107       if (DS.isEmpty()) {
108         if (DeclLoc.isInvalid())
109           DeclLoc = DS.getSourceRange().getBegin();
110         Diag(DeclLoc, diag::ext_missing_declspec)
111           << DS.getSourceRange()
112         << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
113                                                  "int");
114       }
115     } else if (!DS.hasTypeSpecifier()) {
116       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
117       // "At least one type specifier shall be given in the declaration
118       // specifiers in each declaration, and in the specifier-qualifier list in
119       // each struct declaration and type name."
120       // FIXME: Does Microsoft really have the implicit int extension in C++?
121       if (DeclLoc.isInvalid())
122         DeclLoc = DS.getSourceRange().getBegin();
123 
124       if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) {
125         Diag(DeclLoc, diag::err_missing_type_specifier)
126           << DS.getSourceRange();
127 
128         // When this occurs in C++ code, often something is very broken with the
129         // value being declared, poison it as invalid so we don't get chains of
130         // errors.
131         isInvalid = true;
132       } else {
133         Diag(DeclLoc, diag::ext_missing_type_specifier)
134           << DS.getSourceRange();
135       }
136     }
137 
138     // FALL THROUGH.
139   case DeclSpec::TST_int: {
140     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
141       switch (DS.getTypeSpecWidth()) {
142       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
143       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
144       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
145       case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
146       }
147     } else {
148       switch (DS.getTypeSpecWidth()) {
149       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
150       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
151       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
152       case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
153       }
154     }
155     break;
156   }
157   case DeclSpec::TST_float: Result = Context.FloatTy; break;
158   case DeclSpec::TST_double:
159     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
160       Result = Context.LongDoubleTy;
161     else
162       Result = Context.DoubleTy;
163     break;
164   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
165   case DeclSpec::TST_decimal32:    // _Decimal32
166   case DeclSpec::TST_decimal64:    // _Decimal64
167   case DeclSpec::TST_decimal128:   // _Decimal128
168     Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
169     Result = Context.IntTy;
170     isInvalid = true;
171     break;
172   case DeclSpec::TST_class:
173   case DeclSpec::TST_enum:
174   case DeclSpec::TST_union:
175   case DeclSpec::TST_struct: {
176     Decl *D = static_cast<Decl *>(DS.getTypeRep());
177     assert(D && "Didn't get a decl for a class/enum/union/struct?");
178     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
179            DS.getTypeSpecSign() == 0 &&
180            "Can't handle qualifiers on typedef names yet!");
181     // TypeQuals handled by caller.
182     Result = Context.getTypeDeclType(cast<TypeDecl>(D));
183 
184     if (D->isInvalidDecl())
185       isInvalid = true;
186     break;
187   }
188   case DeclSpec::TST_typename: {
189     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
190            DS.getTypeSpecSign() == 0 &&
191            "Can't handle qualifiers on typedef names yet!");
192     Result = QualType::getFromOpaquePtr(DS.getTypeRep());
193 
194     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
195       // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have
196       // this "hack" for now...
197       if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
198         Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
199                                                        (ObjCProtocolDecl**)PQ,
200                                                DS.getNumProtocolQualifiers());
201       else if (Result == Context.getObjCIdType())
202         // id<protocol-list>
203         Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ,
204                                                  DS.getNumProtocolQualifiers());
205       else if (Result == Context.getObjCClassType()) {
206         if (DeclLoc.isInvalid())
207           DeclLoc = DS.getSourceRange().getBegin();
208         // Class<protocol-list>
209         Diag(DeclLoc, diag::err_qualified_class_unsupported)
210           << DS.getSourceRange();
211       } else {
212         if (DeclLoc.isInvalid())
213           DeclLoc = DS.getSourceRange().getBegin();
214         Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
215           << DS.getSourceRange();
216         isInvalid = true;
217       }
218     }
219 
220     // If this is a reference to an invalid typedef, propagate the invalidity.
221     if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
222       if (TDT->getDecl()->isInvalidDecl())
223         isInvalid = true;
224 
225     // TypeQuals handled by caller.
226     break;
227   }
228   case DeclSpec::TST_typeofType:
229     Result = QualType::getFromOpaquePtr(DS.getTypeRep());
230     assert(!Result.isNull() && "Didn't get a type for typeof?");
231     // TypeQuals handled by caller.
232     Result = Context.getTypeOfType(Result);
233     break;
234   case DeclSpec::TST_typeofExpr: {
235     Expr *E = static_cast<Expr *>(DS.getTypeRep());
236     assert(E && "Didn't get an expression for typeof?");
237     // TypeQuals handled by caller.
238     Result = Context.getTypeOfExprType(E);
239     break;
240   }
241   case DeclSpec::TST_decltype: {
242     Expr *E = static_cast<Expr *>(DS.getTypeRep());
243     assert(E && "Didn't get an expression for decltype?");
244     // TypeQuals handled by caller.
245     Result = BuildDecltypeType(E);
246     if (Result.isNull()) {
247       Result = Context.IntTy;
248       isInvalid = true;
249     }
250     break;
251   }
252   case DeclSpec::TST_auto: {
253     // TypeQuals handled by caller.
254     Result = Context.UndeducedAutoTy;
255     break;
256   }
257 
258   case DeclSpec::TST_error:
259     Result = Context.IntTy;
260     isInvalid = true;
261     break;
262   }
263 
264   // Handle complex types.
265   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
266     if (getLangOptions().Freestanding)
267       Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
268     Result = Context.getComplexType(Result);
269   }
270 
271   assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
272          "FIXME: imaginary types not supported yet!");
273 
274   // See if there are any attributes on the declspec that apply to the type (as
275   // opposed to the decl).
276   if (const AttributeList *AL = DS.getAttributes())
277     ProcessTypeAttributeList(Result, AL);
278 
279   // Apply const/volatile/restrict qualifiers to T.
280   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
281 
282     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
283     // or incomplete types shall not be restrict-qualified."  C++ also allows
284     // restrict-qualified references.
285     if (TypeQuals & QualType::Restrict) {
286       if (Result->isPointerType() || Result->isReferenceType()) {
287         QualType EltTy = Result->isPointerType() ?
288           Result->getAsPointerType()->getPointeeType() :
289           Result->getAsReferenceType()->getPointeeType();
290 
291         // If we have a pointer or reference, the pointee must have an object
292         // incomplete type.
293         if (!EltTy->isIncompleteOrObjectType()) {
294           Diag(DS.getRestrictSpecLoc(),
295                diag::err_typecheck_invalid_restrict_invalid_pointee)
296             << EltTy << DS.getSourceRange();
297           TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
298         }
299       } else {
300         Diag(DS.getRestrictSpecLoc(),
301              diag::err_typecheck_invalid_restrict_not_pointer)
302           << Result << DS.getSourceRange();
303         TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
304       }
305     }
306 
307     // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
308     // of a function type includes any type qualifiers, the behavior is
309     // undefined."
310     if (Result->isFunctionType() && TypeQuals) {
311       // Get some location to point at, either the C or V location.
312       SourceLocation Loc;
313       if (TypeQuals & QualType::Const)
314         Loc = DS.getConstSpecLoc();
315       else {
316         assert((TypeQuals & QualType::Volatile) &&
317                "Has CV quals but not C or V?");
318         Loc = DS.getVolatileSpecLoc();
319       }
320       Diag(Loc, diag::warn_typecheck_function_qualifiers)
321         << Result << DS.getSourceRange();
322     }
323 
324     // C++ [dcl.ref]p1:
325     //   Cv-qualified references are ill-formed except when the
326     //   cv-qualifiers are introduced through the use of a typedef
327     //   (7.1.3) or of a template type argument (14.3), in which
328     //   case the cv-qualifiers are ignored.
329     // FIXME: Shouldn't we be checking SCS_typedef here?
330     if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
331         TypeQuals && Result->isReferenceType()) {
332       TypeQuals &= ~QualType::Const;
333       TypeQuals &= ~QualType::Volatile;
334     }
335 
336     Result = Result.getQualifiedType(TypeQuals);
337   }
338   return Result;
339 }
340 
341 static std::string getPrintableNameForEntity(DeclarationName Entity) {
342   if (Entity)
343     return Entity.getAsString();
344 
345   return "type name";
346 }
347 
348 /// \brief Build a pointer type.
349 ///
350 /// \param T The type to which we'll be building a pointer.
351 ///
352 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
353 ///
354 /// \param Loc The location of the entity whose type involves this
355 /// pointer type or, if there is no such entity, the location of the
356 /// type that will have pointer type.
357 ///
358 /// \param Entity The name of the entity that involves the pointer
359 /// type, if known.
360 ///
361 /// \returns A suitable pointer type, if there are no
362 /// errors. Otherwise, returns a NULL type.
363 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
364                                 SourceLocation Loc, DeclarationName Entity) {
365   if (T->isReferenceType()) {
366     // C++ 8.3.2p4: There shall be no ... pointers to references ...
367     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
368       << getPrintableNameForEntity(Entity);
369     return QualType();
370   }
371 
372   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
373   // object or incomplete types shall not be restrict-qualified."
374   if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
375     Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
376       << T;
377     Quals &= ~QualType::Restrict;
378   }
379 
380   // Build the pointer type.
381   return Context.getPointerType(T).getQualifiedType(Quals);
382 }
383 
384 /// \brief Build a reference type.
385 ///
386 /// \param T The type to which we'll be building a reference.
387 ///
388 /// \param Quals The cvr-qualifiers to be applied to the reference type.
389 ///
390 /// \param Loc The location of the entity whose type involves this
391 /// reference type or, if there is no such entity, the location of the
392 /// type that will have reference type.
393 ///
394 /// \param Entity The name of the entity that involves the reference
395 /// type, if known.
396 ///
397 /// \returns A suitable reference type, if there are no
398 /// errors. Otherwise, returns a NULL type.
399 QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
400                                   SourceLocation Loc, DeclarationName Entity) {
401   if (LValueRef) {
402     if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
403       // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
404       //   reference to a type T, and attempt to create the type "lvalue
405       //   reference to cv TD" creates the type "lvalue reference to T".
406       // We use the qualifiers (restrict or none) of the original reference,
407       // not the new ones. This is consistent with GCC.
408       return Context.getLValueReferenceType(R->getPointeeType()).
409                getQualifiedType(T.getCVRQualifiers());
410     }
411   }
412   if (T->isReferenceType()) {
413     // C++ [dcl.ref]p4: There shall be no references to references.
414     //
415     // According to C++ DR 106, references to references are only
416     // diagnosed when they are written directly (e.g., "int & &"),
417     // but not when they happen via a typedef:
418     //
419     //   typedef int& intref;
420     //   typedef intref& intref2;
421     //
422     // Parser::ParserDeclaratorInternal diagnoses the case where
423     // references are written directly; here, we handle the
424     // collapsing of references-to-references as described in C++
425     // DR 106 and amended by C++ DR 540.
426     return T;
427   }
428 
429   // C++ [dcl.ref]p1:
430   //   A declarator that specifies the type “reference to cv void”
431   //   is ill-formed.
432   if (T->isVoidType()) {
433     Diag(Loc, diag::err_reference_to_void);
434     return QualType();
435   }
436 
437   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
438   // object or incomplete types shall not be restrict-qualified."
439   if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
440     Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
441       << T;
442     Quals &= ~QualType::Restrict;
443   }
444 
445   // C++ [dcl.ref]p1:
446   //   [...] Cv-qualified references are ill-formed except when the
447   //   cv-qualifiers are introduced through the use of a typedef
448   //   (7.1.3) or of a template type argument (14.3), in which case
449   //   the cv-qualifiers are ignored.
450   //
451   // We diagnose extraneous cv-qualifiers for the non-typedef,
452   // non-template type argument case within the parser. Here, we just
453   // ignore any extraneous cv-qualifiers.
454   Quals &= ~QualType::Const;
455   Quals &= ~QualType::Volatile;
456 
457   // Handle restrict on references.
458   if (LValueRef)
459     return Context.getLValueReferenceType(T).getQualifiedType(Quals);
460   return Context.getRValueReferenceType(T).getQualifiedType(Quals);
461 }
462 
463 /// \brief Build an array type.
464 ///
465 /// \param T The type of each element in the array.
466 ///
467 /// \param ASM C99 array size modifier (e.g., '*', 'static').
468 ///
469 /// \param ArraySize Expression describing the size of the array.
470 ///
471 /// \param Quals The cvr-qualifiers to be applied to the array's
472 /// element type.
473 ///
474 /// \param Loc The location of the entity whose type involves this
475 /// array type or, if there is no such entity, the location of the
476 /// type that will have array type.
477 ///
478 /// \param Entity The name of the entity that involves the array
479 /// type, if known.
480 ///
481 /// \returns A suitable array type, if there are no errors. Otherwise,
482 /// returns a NULL type.
483 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
484                               Expr *ArraySize, unsigned Quals,
485                               SourceLocation Loc, DeclarationName Entity) {
486   // C99 6.7.5.2p1: If the element type is an incomplete or function type,
487   // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
488   if (RequireCompleteType(Loc, T,
489                              diag::err_illegal_decl_array_incomplete_type))
490     return QualType();
491 
492   if (T->isFunctionType()) {
493     Diag(Loc, diag::err_illegal_decl_array_of_functions)
494       << getPrintableNameForEntity(Entity);
495     return QualType();
496   }
497 
498   // C++ 8.3.2p4: There shall be no ... arrays of references ...
499   if (T->isReferenceType()) {
500     Diag(Loc, diag::err_illegal_decl_array_of_references)
501       << getPrintableNameForEntity(Entity);
502     return QualType();
503   }
504 
505   if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
506     Diag(Loc,  diag::err_illegal_decl_array_of_auto)
507       << getPrintableNameForEntity(Entity);
508     return QualType();
509   }
510 
511   if (const RecordType *EltTy = T->getAsRecordType()) {
512     // If the element type is a struct or union that contains a variadic
513     // array, accept it as a GNU extension: C99 6.7.2.1p2.
514     if (EltTy->getDecl()->hasFlexibleArrayMember())
515       Diag(Loc, diag::ext_flexible_array_in_array) << T;
516   } else if (T->isObjCInterfaceType()) {
517     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
518     return QualType();
519   }
520 
521   // C99 6.7.5.2p1: The size expression shall have integer type.
522   if (ArraySize && !ArraySize->isTypeDependent() &&
523       !ArraySize->getType()->isIntegerType()) {
524     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
525       << ArraySize->getType() << ArraySize->getSourceRange();
526     ArraySize->Destroy(Context);
527     return QualType();
528   }
529   llvm::APSInt ConstVal(32);
530   if (!ArraySize) {
531     if (ASM == ArrayType::Star)
532       T = Context.getVariableArrayType(T, 0, ASM, Quals);
533     else
534       T = Context.getIncompleteArrayType(T, ASM, Quals);
535   } else if (ArraySize->isValueDependent()) {
536     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
537   } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
538              (!T->isDependentType() && !T->isConstantSizeType())) {
539     // Per C99, a variable array is an array with either a non-constant
540     // size or an element type that has a non-constant-size
541     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
542   } else {
543     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
544     // have a value greater than zero.
545     if (ConstVal.isSigned()) {
546       if (ConstVal.isNegative()) {
547         Diag(ArraySize->getLocStart(),
548              diag::err_typecheck_negative_array_size)
549           << ArraySize->getSourceRange();
550         return QualType();
551       } else if (ConstVal == 0) {
552         // GCC accepts zero sized static arrays.
553         Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
554           << ArraySize->getSourceRange();
555       }
556     }
557     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
558   }
559   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
560   if (!getLangOptions().C99) {
561     if (ArraySize && !ArraySize->isTypeDependent() &&
562         !ArraySize->isValueDependent() &&
563         !ArraySize->isIntegerConstantExpr(Context))
564       Diag(Loc, diag::ext_vla);
565     else if (ASM != ArrayType::Normal || Quals != 0)
566       Diag(Loc, diag::ext_c99_array_usage);
567   }
568 
569   return T;
570 }
571 
572 /// \brief Build an ext-vector type.
573 ///
574 /// Run the required checks for the extended vector type.
575 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
576                                   SourceLocation AttrLoc) {
577 
578   Expr *Arg = (Expr *)ArraySize.get();
579 
580   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
581   // in conjunction with complex types (pointers, arrays, functions, etc.).
582   if (!T->isDependentType() &&
583       !T->isIntegerType() && !T->isRealFloatingType()) {
584     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
585     return QualType();
586   }
587 
588   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
589     llvm::APSInt vecSize(32);
590     if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
591       Diag(AttrLoc, diag::err_attribute_argument_not_int)
592       << "ext_vector_type" << Arg->getSourceRange();
593       return QualType();
594     }
595 
596     // unlike gcc's vector_size attribute, the size is specified as the
597     // number of elements, not the number of bytes.
598     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
599 
600     if (vectorSize == 0) {
601       Diag(AttrLoc, diag::err_attribute_zero_size)
602       << Arg->getSourceRange();
603       return QualType();
604     }
605 
606     if (!T->isDependentType())
607       return Context.getExtVectorType(T, vectorSize);
608   }
609 
610   return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
611                                                 AttrLoc);
612 }
613 
614 /// \brief Build a function type.
615 ///
616 /// This routine checks the function type according to C++ rules and
617 /// under the assumption that the result type and parameter types have
618 /// just been instantiated from a template. It therefore duplicates
619 /// some of the behavior of GetTypeForDeclarator, but in a much
620 /// simpler form that is only suitable for this narrow use case.
621 ///
622 /// \param T The return type of the function.
623 ///
624 /// \param ParamTypes The parameter types of the function. This array
625 /// will be modified to account for adjustments to the types of the
626 /// function parameters.
627 ///
628 /// \param NumParamTypes The number of parameter types in ParamTypes.
629 ///
630 /// \param Variadic Whether this is a variadic function type.
631 ///
632 /// \param Quals The cvr-qualifiers to be applied to the function type.
633 ///
634 /// \param Loc The location of the entity whose type involves this
635 /// function type or, if there is no such entity, the location of the
636 /// type that will have function type.
637 ///
638 /// \param Entity The name of the entity that involves the function
639 /// type, if known.
640 ///
641 /// \returns A suitable function type, if there are no
642 /// errors. Otherwise, returns a NULL type.
643 QualType Sema::BuildFunctionType(QualType T,
644                                  QualType *ParamTypes,
645                                  unsigned NumParamTypes,
646                                  bool Variadic, unsigned Quals,
647                                  SourceLocation Loc, DeclarationName Entity) {
648   if (T->isArrayType() || T->isFunctionType()) {
649     Diag(Loc, diag::err_func_returning_array_function) << T;
650     return QualType();
651   }
652 
653   bool Invalid = false;
654   for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
655     QualType ParamType = adjustParameterType(ParamTypes[Idx]);
656     if (ParamType->isVoidType()) {
657       Diag(Loc, diag::err_param_with_void_type);
658       Invalid = true;
659     }
660 
661     ParamTypes[Idx] = ParamType;
662   }
663 
664   if (Invalid)
665     return QualType();
666 
667   return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
668                                  Quals);
669 }
670 
671 /// \brief Build a member pointer type \c T Class::*.
672 ///
673 /// \param T the type to which the member pointer refers.
674 /// \param Class the class type into which the member pointer points.
675 /// \param Quals Qualifiers applied to the member pointer type
676 /// \param Loc the location where this type begins
677 /// \param Entity the name of the entity that will have this member pointer type
678 ///
679 /// \returns a member pointer type, if successful, or a NULL type if there was
680 /// an error.
681 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
682                                       unsigned Quals, SourceLocation Loc,
683                                       DeclarationName Entity) {
684   // Verify that we're not building a pointer to pointer to function with
685   // exception specification.
686   if (CheckDistantExceptionSpec(T)) {
687     Diag(Loc, diag::err_distant_exception_spec);
688 
689     // FIXME: If we're doing this as part of template instantiation,
690     // we should return immediately.
691 
692     // Build the type anyway, but use the canonical type so that the
693     // exception specifiers are stripped off.
694     T = Context.getCanonicalType(T);
695   }
696 
697   // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
698   //   with reference type, or "cv void."
699   if (T->isReferenceType()) {
700     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
701       << (Entity? Entity.getAsString() : "type name");
702     return QualType();
703   }
704 
705   if (T->isVoidType()) {
706     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
707       << (Entity? Entity.getAsString() : "type name");
708     return QualType();
709   }
710 
711   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
712   // object or incomplete types shall not be restrict-qualified."
713   if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
714     Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
715       << T;
716 
717     // FIXME: If we're doing this as part of template instantiation,
718     // we should return immediately.
719     Quals &= ~QualType::Restrict;
720   }
721 
722   if (!Class->isDependentType() && !Class->isRecordType()) {
723     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
724     return QualType();
725   }
726 
727   return Context.getMemberPointerType(T, Class.getTypePtr())
728            .getQualifiedType(Quals);
729 }
730 
731 /// \brief Build a block pointer type.
732 ///
733 /// \param T The type to which we'll be building a block pointer.
734 ///
735 /// \param Quals The cvr-qualifiers to be applied to the block pointer type.
736 ///
737 /// \param Loc The location of the entity whose type involves this
738 /// block pointer type or, if there is no such entity, the location of the
739 /// type that will have block pointer type.
740 ///
741 /// \param Entity The name of the entity that involves the block pointer
742 /// type, if known.
743 ///
744 /// \returns A suitable block pointer type, if there are no
745 /// errors. Otherwise, returns a NULL type.
746 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
747                                      SourceLocation Loc,
748                                      DeclarationName Entity) {
749   if (!T.getTypePtr()->isFunctionType()) {
750     Diag(Loc, diag::err_nonfunction_block_type);
751     return QualType();
752   }
753 
754   return Context.getBlockPointerType(T).getQualifiedType(Quals);
755 }
756 
757 /// GetTypeForDeclarator - Convert the type for the specified
758 /// declarator to Type instances. Skip the outermost Skip type
759 /// objects.
760 ///
761 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
762 /// owns the declaration of a type (e.g., the definition of a struct
763 /// type), then *OwnedDecl will receive the owned declaration.
764 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
765                                     TagDecl **OwnedDecl) {
766   bool OmittedReturnType = false;
767 
768   if (D.getContext() == Declarator::BlockLiteralContext
769       && Skip == 0
770       && !D.getDeclSpec().hasTypeSpecifier()
771       && (D.getNumTypeObjects() == 0
772           || (D.getNumTypeObjects() == 1
773               && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
774     OmittedReturnType = true;
775 
776   // long long is a C99 feature.
777   if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
778       D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
779     Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
780 
781   // Determine the type of the declarator. Not all forms of declarator
782   // have a type.
783   QualType T;
784   switch (D.getKind()) {
785   case Declarator::DK_Abstract:
786   case Declarator::DK_Normal:
787   case Declarator::DK_Operator: {
788     const DeclSpec &DS = D.getDeclSpec();
789     if (OmittedReturnType) {
790       // We default to a dependent type initially.  Can be modified by
791       // the first return statement.
792       T = Context.DependentTy;
793     } else {
794       bool isInvalid = false;
795       T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
796       if (isInvalid)
797         D.setInvalidType(true);
798       else if (OwnedDecl && DS.isTypeSpecOwned())
799         *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
800     }
801     break;
802   }
803 
804   case Declarator::DK_Constructor:
805   case Declarator::DK_Destructor:
806   case Declarator::DK_Conversion:
807     // Constructors and destructors don't have return types. Use
808     // "void" instead. Conversion operators will check their return
809     // types separately.
810     T = Context.VoidTy;
811     break;
812   }
813 
814   if (T == Context.UndeducedAutoTy) {
815     int Error = -1;
816 
817     switch (D.getContext()) {
818     case Declarator::KNRTypeListContext:
819       assert(0 && "K&R type lists aren't allowed in C++");
820       break;
821     case Declarator::PrototypeContext:
822       Error = 0; // Function prototype
823       break;
824     case Declarator::MemberContext:
825       switch (cast<TagDecl>(CurContext)->getTagKind()) {
826       case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
827       case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
828       case TagDecl::TK_union:  Error = 2; /* Union member */ break;
829       case TagDecl::TK_class:  Error = 3; /* Class member */ break;
830       }
831       break;
832     case Declarator::CXXCatchContext:
833       Error = 4; // Exception declaration
834       break;
835     case Declarator::TemplateParamContext:
836       Error = 5; // Template parameter
837       break;
838     case Declarator::BlockLiteralContext:
839       Error = 6;  // Block literal
840       break;
841     case Declarator::FileContext:
842     case Declarator::BlockContext:
843     case Declarator::ForContext:
844     case Declarator::ConditionContext:
845     case Declarator::TypeNameContext:
846       break;
847     }
848 
849     if (Error != -1) {
850       Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
851         << Error;
852       T = Context.IntTy;
853       D.setInvalidType(true);
854     }
855   }
856 
857   // The name we're declaring, if any.
858   DeclarationName Name;
859   if (D.getIdentifier())
860     Name = D.getIdentifier();
861 
862   // Walk the DeclTypeInfo, building the recursive type as we go.
863   // DeclTypeInfos are ordered from the identifier out, which is
864   // opposite of what we want :).
865   for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
866     DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
867     switch (DeclType.Kind) {
868     default: assert(0 && "Unknown decltype!");
869     case DeclaratorChunk::BlockPointer:
870       // If blocks are disabled, emit an error.
871       if (!LangOpts.Blocks)
872         Diag(DeclType.Loc, diag::err_blocks_disable);
873 
874       T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
875                                 Name);
876       break;
877     case DeclaratorChunk::Pointer:
878       // Verify that we're not building a pointer to pointer to function with
879       // exception specification.
880       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
881         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
882         D.setInvalidType(true);
883         // Build the type anyway.
884       }
885       T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
886       break;
887     case DeclaratorChunk::Reference:
888       // Verify that we're not building a reference to pointer to function with
889       // exception specification.
890       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
891         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
892         D.setInvalidType(true);
893         // Build the type anyway.
894       }
895       T = BuildReferenceType(T, DeclType.Ref.LValueRef,
896                              DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
897                              DeclType.Loc, Name);
898       break;
899     case DeclaratorChunk::Array: {
900       // Verify that we're not building an array of pointers to function with
901       // exception specification.
902       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
903         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
904         D.setInvalidType(true);
905         // Build the type anyway.
906       }
907       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
908       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
909       ArrayType::ArraySizeModifier ASM;
910       if (ATI.isStar)
911         ASM = ArrayType::Star;
912       else if (ATI.hasStatic)
913         ASM = ArrayType::Static;
914       else
915         ASM = ArrayType::Normal;
916       if (ASM == ArrayType::Star &&
917           D.getContext() != Declarator::PrototypeContext) {
918         // FIXME: This check isn't quite right: it allows star in prototypes
919         // for function definitions, and disallows some edge cases detailed
920         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
921         Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
922         ASM = ArrayType::Normal;
923         D.setInvalidType(true);
924       }
925       T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
926       break;
927     }
928     case DeclaratorChunk::Function: {
929       // If the function declarator has a prototype (i.e. it is not () and
930       // does not have a K&R-style identifier list), then the arguments are part
931       // of the type, otherwise the argument list is ().
932       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
933 
934       // C99 6.7.5.3p1: The return type may not be a function or array type.
935       if (T->isArrayType() || T->isFunctionType()) {
936         Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
937         T = Context.IntTy;
938         D.setInvalidType(true);
939       }
940 
941       if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
942         // C++ [dcl.fct]p6:
943         //   Types shall not be defined in return or parameter types.
944         TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
945         if (Tag->isDefinition())
946           Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
947             << Context.getTypeDeclType(Tag);
948       }
949 
950       // Exception specs are not allowed in typedefs. Complain, but add it
951       // anyway.
952       if (FTI.hasExceptionSpec &&
953           D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
954         Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
955 
956       if (FTI.NumArgs == 0) {
957         if (getLangOptions().CPlusPlus) {
958           // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
959           // function takes no arguments.
960           llvm::SmallVector<QualType, 4> Exceptions;
961           Exceptions.reserve(FTI.NumExceptions);
962           for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
963             QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
964             // Check that the type is valid for an exception spec, and drop it
965             // if not.
966             if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
967               Exceptions.push_back(ET);
968           }
969           T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
970                                       FTI.hasExceptionSpec,
971                                       FTI.hasAnyExceptionSpec,
972                                       Exceptions.size(), Exceptions.data());
973         } else if (FTI.isVariadic) {
974           // We allow a zero-parameter variadic function in C if the
975           // function is marked with the "overloadable"
976           // attribute. Scan for this attribute now.
977           bool Overloadable = false;
978           for (const AttributeList *Attrs = D.getAttributes();
979                Attrs; Attrs = Attrs->getNext()) {
980             if (Attrs->getKind() == AttributeList::AT_overloadable) {
981               Overloadable = true;
982               break;
983             }
984           }
985 
986           if (!Overloadable)
987             Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
988           T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
989         } else {
990           // Simple void foo(), where the incoming T is the result type.
991           T = Context.getFunctionNoProtoType(T);
992         }
993       } else if (FTI.ArgInfo[0].Param == 0) {
994         // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
995         Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
996       } else {
997         // Otherwise, we have a function with an argument list that is
998         // potentially variadic.
999         llvm::SmallVector<QualType, 16> ArgTys;
1000 
1001         for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1002           ParmVarDecl *Param =
1003             cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1004           QualType ArgTy = Param->getType();
1005           assert(!ArgTy.isNull() && "Couldn't parse type?");
1006 
1007           // Adjust the parameter type.
1008           assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1009 
1010           // Look for 'void'.  void is allowed only as a single argument to a
1011           // function with no other parameters (C99 6.7.5.3p10).  We record
1012           // int(void) as a FunctionProtoType with an empty argument list.
1013           if (ArgTy->isVoidType()) {
1014             // If this is something like 'float(int, void)', reject it.  'void'
1015             // is an incomplete type (C99 6.2.5p19) and function decls cannot
1016             // have arguments of incomplete type.
1017             if (FTI.NumArgs != 1 || FTI.isVariadic) {
1018               Diag(DeclType.Loc, diag::err_void_only_param);
1019               ArgTy = Context.IntTy;
1020               Param->setType(ArgTy);
1021             } else if (FTI.ArgInfo[i].Ident) {
1022               // Reject, but continue to parse 'int(void abc)'.
1023               Diag(FTI.ArgInfo[i].IdentLoc,
1024                    diag::err_param_with_void_type);
1025               ArgTy = Context.IntTy;
1026               Param->setType(ArgTy);
1027             } else {
1028               // Reject, but continue to parse 'float(const void)'.
1029               if (ArgTy.getCVRQualifiers())
1030                 Diag(DeclType.Loc, diag::err_void_param_qualified);
1031 
1032               // Do not add 'void' to the ArgTys list.
1033               break;
1034             }
1035           } else if (!FTI.hasPrototype) {
1036             if (ArgTy->isPromotableIntegerType()) {
1037               ArgTy = Context.IntTy;
1038             } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
1039               if (BTy->getKind() == BuiltinType::Float)
1040                 ArgTy = Context.DoubleTy;
1041             }
1042           }
1043 
1044           ArgTys.push_back(ArgTy);
1045         }
1046 
1047         llvm::SmallVector<QualType, 4> Exceptions;
1048         Exceptions.reserve(FTI.NumExceptions);
1049         for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1050           QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
1051           // Check that the type is valid for an exception spec, and drop it if
1052           // not.
1053           if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1054             Exceptions.push_back(ET);
1055         }
1056 
1057         T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1058                                     FTI.isVariadic, FTI.TypeQuals,
1059                                     FTI.hasExceptionSpec,
1060                                     FTI.hasAnyExceptionSpec,
1061                                     Exceptions.size(), Exceptions.data());
1062       }
1063       break;
1064     }
1065     case DeclaratorChunk::MemberPointer:
1066       // The scope spec must refer to a class, or be dependent.
1067       QualType ClsType;
1068       if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1069         NestedNameSpecifier *NNS
1070           = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1071         assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1072         ClsType = QualType(NNS->getAsType(), 0);
1073       } else if (CXXRecordDecl *RD
1074                    = dyn_cast_or_null<CXXRecordDecl>(
1075                                     computeDeclContext(DeclType.Mem.Scope()))) {
1076         ClsType = Context.getTagDeclType(RD);
1077       } else {
1078         Diag(DeclType.Mem.Scope().getBeginLoc(),
1079              diag::err_illegal_decl_mempointer_in_nonclass)
1080           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1081           << DeclType.Mem.Scope().getRange();
1082         D.setInvalidType(true);
1083       }
1084 
1085       if (!ClsType.isNull())
1086         T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1087                                    DeclType.Loc, D.getIdentifier());
1088       if (T.isNull()) {
1089         T = Context.IntTy;
1090         D.setInvalidType(true);
1091       }
1092       break;
1093     }
1094 
1095     if (T.isNull()) {
1096       D.setInvalidType(true);
1097       T = Context.IntTy;
1098     }
1099 
1100     // See if there are any attributes on this declarator chunk.
1101     if (const AttributeList *AL = DeclType.getAttrs())
1102       ProcessTypeAttributeList(T, AL);
1103   }
1104 
1105   if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1106     const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
1107     assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
1108 
1109     // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1110     // for a nonstatic member function, the function type to which a pointer
1111     // to member refers, or the top-level function type of a function typedef
1112     // declaration.
1113     if (FnTy->getTypeQuals() != 0 &&
1114         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1115         ((D.getContext() != Declarator::MemberContext &&
1116           (!D.getCXXScopeSpec().isSet() ||
1117            !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
1118          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1119       if (D.isFunctionDeclarator())
1120         Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1121       else
1122         Diag(D.getIdentifierLoc(),
1123              diag::err_invalid_qualified_typedef_function_type_use);
1124 
1125       // Strip the cv-quals from the type.
1126       T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1127                                   FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1128     }
1129   }
1130 
1131   // If there were any type attributes applied to the decl itself (not the
1132   // type, apply the type attribute to the type!)
1133   if (const AttributeList *Attrs = D.getAttributes())
1134     ProcessTypeAttributeList(T, Attrs);
1135 
1136   return T;
1137 }
1138 
1139 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
1140 /// exception specification. Incomplete types, or pointers to incomplete types
1141 /// other than void are not allowed.
1142 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1143   // FIXME: This may not correctly work with the fix for core issue 437,
1144   // where a class's own type is considered complete within its body.
1145 
1146   // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1147   //   an incomplete type.
1148   if (T->isIncompleteType())
1149     return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1150       << Range << T << /*direct*/0;
1151 
1152   // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1153   //   an incomplete type a pointer or reference to an incomplete type, other
1154   //   than (cv) void*.
1155   int kind;
1156   if (const PointerType* IT = T->getAsPointerType()) {
1157     T = IT->getPointeeType();
1158     kind = 1;
1159   } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1160     T = IT->getPointeeType();
1161     kind = 2;
1162   } else
1163     return false;
1164 
1165   if (T->isIncompleteType() && !T->isVoidType())
1166     return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1167       << Range << T << /*indirect*/kind;
1168 
1169   return false;
1170 }
1171 
1172 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1173 /// to member to a function with an exception specification. This means that
1174 /// it is invalid to add another level of indirection.
1175 bool Sema::CheckDistantExceptionSpec(QualType T) {
1176   if (const PointerType *PT = T->getAsPointerType())
1177     T = PT->getPointeeType();
1178   else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1179     T = PT->getPointeeType();
1180   else
1181     return false;
1182 
1183   const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1184   if (!FnT)
1185     return false;
1186 
1187   return FnT->hasExceptionSpec();
1188 }
1189 
1190 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1191 /// declarator
1192 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1193   ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1194   QualType T = MDecl->getResultType();
1195   llvm::SmallVector<QualType, 16> ArgTys;
1196 
1197   // Add the first two invisible argument types for self and _cmd.
1198   if (MDecl->isInstanceMethod()) {
1199     QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1200     selfTy = Context.getPointerType(selfTy);
1201     ArgTys.push_back(selfTy);
1202   } else
1203     ArgTys.push_back(Context.getObjCIdType());
1204   ArgTys.push_back(Context.getObjCSelType());
1205 
1206   for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1207        E = MDecl->param_end(); PI != E; ++PI) {
1208     QualType ArgTy = (*PI)->getType();
1209     assert(!ArgTy.isNull() && "Couldn't parse type?");
1210     ArgTy = adjustParameterType(ArgTy);
1211     ArgTys.push_back(ArgTy);
1212   }
1213   T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1214                               MDecl->isVariadic(), 0);
1215   return T;
1216 }
1217 
1218 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1219 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1220 /// they point to and return true. If T1 and T2 aren't pointer types
1221 /// or pointer-to-member types, or if they are not similar at this
1222 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1223 /// qualifiers on T1 and T2 are ignored. This function will typically
1224 /// be called in a loop that successively "unwraps" pointer and
1225 /// pointer-to-member types to compare them at each level.
1226 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1227   const PointerType *T1PtrType = T1->getAsPointerType(),
1228                     *T2PtrType = T2->getAsPointerType();
1229   if (T1PtrType && T2PtrType) {
1230     T1 = T1PtrType->getPointeeType();
1231     T2 = T2PtrType->getPointeeType();
1232     return true;
1233   }
1234 
1235   const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1236                           *T2MPType = T2->getAsMemberPointerType();
1237   if (T1MPType && T2MPType &&
1238       Context.getCanonicalType(T1MPType->getClass()) ==
1239       Context.getCanonicalType(T2MPType->getClass())) {
1240     T1 = T1MPType->getPointeeType();
1241     T2 = T2MPType->getPointeeType();
1242     return true;
1243   }
1244   return false;
1245 }
1246 
1247 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1248   // C99 6.7.6: Type names have no identifier.  This is already validated by
1249   // the parser.
1250   assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1251 
1252   TagDecl *OwnedTag = 0;
1253   QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1254   if (D.isInvalidType())
1255     return true;
1256 
1257   if (getLangOptions().CPlusPlus) {
1258     // Check that there are no default arguments (C++ only).
1259     CheckExtraCXXDefaultArguments(D);
1260 
1261     // C++0x [dcl.type]p3:
1262     //   A type-specifier-seq shall not define a class or enumeration
1263     //   unless it appears in the type-id of an alias-declaration
1264     //   (7.1.3).
1265     if (OwnedTag && OwnedTag->isDefinition())
1266       Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1267         << Context.getTypeDeclType(OwnedTag);
1268   }
1269 
1270   return T.getAsOpaquePtr();
1271 }
1272 
1273 
1274 
1275 //===----------------------------------------------------------------------===//
1276 // Type Attribute Processing
1277 //===----------------------------------------------------------------------===//
1278 
1279 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1280 /// specified type.  The attribute contains 1 argument, the id of the address
1281 /// space for the type.
1282 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1283                                             const AttributeList &Attr, Sema &S){
1284   // If this type is already address space qualified, reject it.
1285   // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1286   // for two or more different address spaces."
1287   if (Type.getAddressSpace()) {
1288     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1289     return;
1290   }
1291 
1292   // Check the attribute arguments.
1293   if (Attr.getNumArgs() != 1) {
1294     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1295     return;
1296   }
1297   Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1298   llvm::APSInt addrSpace(32);
1299   if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1300     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1301       << ASArgExpr->getSourceRange();
1302     return;
1303   }
1304 
1305   unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1306   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1307 }
1308 
1309 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1310 /// specified type.  The attribute contains 1 argument, weak or strong.
1311 static void HandleObjCGCTypeAttribute(QualType &Type,
1312                                       const AttributeList &Attr, Sema &S) {
1313   if (Type.getObjCGCAttr() != QualType::GCNone) {
1314     S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1315     return;
1316   }
1317 
1318   // Check the attribute arguments.
1319   if (!Attr.getParameterName()) {
1320     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1321       << "objc_gc" << 1;
1322     return;
1323   }
1324   QualType::GCAttrTypes GCAttr;
1325   if (Attr.getNumArgs() != 0) {
1326     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1327     return;
1328   }
1329   if (Attr.getParameterName()->isStr("weak"))
1330     GCAttr = QualType::Weak;
1331   else if (Attr.getParameterName()->isStr("strong"))
1332     GCAttr = QualType::Strong;
1333   else {
1334     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1335       << "objc_gc" << Attr.getParameterName();
1336     return;
1337   }
1338 
1339   Type = S.Context.getObjCGCQualType(Type, GCAttr);
1340 }
1341 
1342 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1343   // Scan through and apply attributes to this type where it makes sense.  Some
1344   // attributes (such as __address_space__, __vector_size__, etc) apply to the
1345   // type, but others can be present in the type specifiers even though they
1346   // apply to the decl.  Here we apply type attributes and ignore the rest.
1347   for (; AL; AL = AL->getNext()) {
1348     // If this is an attribute we can handle, do so now, otherwise, add it to
1349     // the LeftOverAttrs list for rechaining.
1350     switch (AL->getKind()) {
1351     default: break;
1352     case AttributeList::AT_address_space:
1353       HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1354       break;
1355     case AttributeList::AT_objc_gc:
1356       HandleObjCGCTypeAttribute(Result, *AL, *this);
1357       break;
1358     }
1359   }
1360 }
1361 
1362 /// @brief Ensure that the type T is a complete type.
1363 ///
1364 /// This routine checks whether the type @p T is complete in any
1365 /// context where a complete type is required. If @p T is a complete
1366 /// type, returns false. If @p T is a class template specialization,
1367 /// this routine then attempts to perform class template
1368 /// instantiation. If instantiation fails, or if @p T is incomplete
1369 /// and cannot be completed, issues the diagnostic @p diag (giving it
1370 /// the type @p T) and returns true.
1371 ///
1372 /// @param Loc  The location in the source that the incomplete type
1373 /// diagnostic should refer to.
1374 ///
1375 /// @param T  The type that this routine is examining for completeness.
1376 ///
1377 /// @param diag The diagnostic value (e.g.,
1378 /// @c diag::err_typecheck_decl_incomplete_type) that will be used
1379 /// for the error message if @p T is incomplete.
1380 ///
1381 /// @param Range1  An optional range in the source code that will be a
1382 /// part of the "incomplete type" error message.
1383 ///
1384 /// @param Range2  An optional range in the source code that will be a
1385 /// part of the "incomplete type" error message.
1386 ///
1387 /// @param PrintType If non-NULL, the type that should be printed
1388 /// instead of @p T. This parameter should be used when the type that
1389 /// we're checking for incompleteness isn't the type that should be
1390 /// displayed to the user, e.g., when T is a type and PrintType is a
1391 /// pointer to T.
1392 ///
1393 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1394 /// @c false otherwise.
1395 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1396                                SourceRange Range1, SourceRange Range2,
1397                                QualType PrintType) {
1398   // FIXME: Add this assertion to help us flush out problems with
1399   // checking for dependent types and type-dependent expressions.
1400   //
1401   //  assert(!T->isDependentType() &&
1402   //         "Can't ask whether a dependent type is complete");
1403 
1404   // If we have a complete type, we're done.
1405   if (!T->isIncompleteType())
1406     return false;
1407 
1408   // If we have a class template specialization or a class member of a
1409   // class template specialization, try to instantiate it.
1410   if (const RecordType *Record = T->getAsRecordType()) {
1411     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1412           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1413       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1414         // Update the class template specialization's location to
1415         // refer to the point of instantiation.
1416         if (Loc.isValid())
1417           ClassTemplateSpec->setLocation(Loc);
1418         return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1419                                              /*ExplicitInstantiation=*/false);
1420       }
1421     } else if (CXXRecordDecl *Rec
1422                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1423       if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1424         // Find the class template specialization that surrounds this
1425         // member class.
1426         ClassTemplateSpecializationDecl *Spec = 0;
1427         for (DeclContext *Parent = Rec->getDeclContext();
1428              Parent && !Spec; Parent = Parent->getParent())
1429           Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1430         assert(Spec && "Not a member of a class template specialization?");
1431         return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1432                                 /*ExplicitInstantiation=*/false);
1433       }
1434     }
1435   }
1436 
1437   if (PrintType.isNull())
1438     PrintType = T;
1439 
1440   // We have an incomplete type. Produce a diagnostic.
1441   Diag(Loc, diag) << PrintType << Range1 << Range2;
1442 
1443   // If the type was a forward declaration of a class/struct/union
1444   // type, produce
1445   const TagType *Tag = 0;
1446   if (const RecordType *Record = T->getAsRecordType())
1447     Tag = Record;
1448   else if (const EnumType *Enum = T->getAsEnumType())
1449     Tag = Enum;
1450 
1451   if (Tag && !Tag->getDecl()->isInvalidDecl())
1452     Diag(Tag->getDecl()->getLocation(),
1453          Tag->isBeingDefined() ? diag::note_type_being_defined
1454                                : diag::note_forward_declaration)
1455         << QualType(Tag, 0);
1456 
1457   return true;
1458 }
1459 
1460 /// \brief Retrieve a version of the type 'T' that is qualified by the
1461 /// nested-name-specifier contained in SS.
1462 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1463   if (!SS.isSet() || SS.isInvalid() || T.isNull())
1464     return T;
1465 
1466   NestedNameSpecifier *NNS
1467     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1468   return Context.getQualifiedNameType(NNS, T);
1469 }
1470 
1471 QualType Sema::BuildTypeofExprType(Expr *E) {
1472   return Context.getTypeOfExprType(E);
1473 }
1474 
1475 QualType Sema::BuildDecltypeType(Expr *E) {
1476   if (E->getType() == Context.OverloadTy) {
1477     Diag(E->getLocStart(),
1478          diag::err_cannot_determine_declared_type_of_overloaded_function);
1479     return QualType();
1480   }
1481   return Context.getDecltypeType(E);
1482 }
1483